Проблема передачи данных о намерениях камеры Android - PullRequest
0 голосов
/ 11 декабря 2018

У меня есть эта проблема на Android:

Попытка вызвать виртуальный метод 'android.os.Bundle android.content.Intent.getExtras ()' для ссылки на пустой объект.

Я знаю, что делаю что-то не так, и я исследовал намерения и данные, но я очень смущен.Можете ли вы помочь мне с моим кодом?

Проблема на

Bundle extras = data.getExtras();

Я прочитал, что мне нужно передать его на onCreate, но затем я потерял все свои данные иЯ очень смущен.Вот мой код:

public class DeliveryGalleryActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_CODE_PHOTO = 123;

    FloatingActionButton btnTakePhoto, btnSave;
    ArrayList<byte[]> images;
    ViewPager mViewPager;
    SectionsPagerAdapter adapter;

    DeliveryInfo deliveryInfo;
    String delivery = "";

    ConectivityTask connTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_delivery_gallery);
        connTask = new ConectivityTask(DeliveryGalleryActivity.this, this);

        mViewPager = findViewById(R.id.container);
        btnTakePhoto = findViewById(R.id.btnTakePhoto);
        btnSave = findViewById(R.id.btnSave);

        btnTakePhoto.setOnClickListener(this);
        btnSave.setOnClickListener(this);

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        images = new ArrayList<>();

        adapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(adapter);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            delivery = bundle.getString("delivery");
            Gson gson = new Gson();
            deliveryInfo = gson.fromJson(delivery, DeliveryInfo.class);
        }

        TextView tvTitleToolbar = findViewById(R.id.tvTitle);
        if (deliveryInfo != null) {
            tvTitleToolbar.setText("Delivery " + deliveryInfo.getNumber());
            tvTitleToolbar.setPaintFlags(tvTitleToolbar.getPaintFlags()| Paint.UNDERLINE_TEXT_FLAG);
        } else {
            tvTitleToolbar.setText("Delivery");
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnTakePhoto:
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(Utils.getNameImage(this)));
                startActivityForResult(intent, REQUEST_CODE_PHOTO);
                break;
            case R.id.btnSave:
                try {
                    saveDelivery();
                } catch (IOException | DocumentException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PHOTO) {
            Bundle extras = data.getExtras();
            Bitmap thePic = extras.getParcelable("data");
            Bitmap croppedBitmap = Bitmap.createBitmap(thePic, 10, 10, thePic.getWidth() - 20, thePic.getHeight() - 20);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            croppedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            croppedBitmap.recycle();
            images.add(byteArray);
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            adapter.addItem();
        }
    }


    public void saveDelivery() throws DocumentException, IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        if (images.size() > 0) {
            Image img = Image.getInstance(images.get(0));
            Document document = new Document(img);
            PdfWriter.getInstance(document, byteArrayOutputStream);

            document.open();
            try {
                putImagesToPdf(document, deliveryInfo.getNumber());
            } catch (IOException e) {
                e.printStackTrace();
            }
            document.close();
        }
        byte[] pdfBytes = byteArrayOutputStream.toByteArray();

        String deliveryNumber = (deliveryInfo != null) ? deliveryInfo.getNumber() : "";

        DeliveryRequest deliveryRequest = new DeliveryRequest(deliveryInfo.getNumber(), PreferencesHelper.getUsername(DeliveryGalleryActivity.this), Utils.getDate(), "50.0", "50.0", "", "", "" + images.size(), pdfBytes, State.SAVED, Utils.getDateTime());
        Database database = new Database(this);

        try {
            database.open();
            //database.deleteDeliveryRequestSaved();
            //database.deleteDeliveryRequestSaved();
            database.saveDeliveryRequest(deliveryRequest);
            database.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Intent intent = new Intent(DeliveryGalleryActivity.this, DeliveryResumeActivity.class);
        intent.putExtra("delivery", delivery);
        startActivity(intent);
    }

    public void putImagesToPdf(Document document, String deliveryNumber) throws IOException, DocumentException {
        Image img;
        PdfWriter.getInstance(document, new FileOutputStream(Utils.getFolderImages(this).getPath() + "/" + deliveryNumber + ".pdf"));
        document.open();
        for (byte[] image : images) {
            img = Image.getInstance(image);
            document.setPageSize(img);
            document.newPage();
            img.setAbsolutePosition(0, 0);
            document.add(img);
        }
        document.close();
    }

    public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return PhotoFragment.newInstance(images.get(position));
        }

        @Override
        public int getCount() {
            return images.size();
        }

        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return "";
        }

        public void addItem() {
            this.notifyDataSetChanged();
        }
    }

    public void onPause() {
        super.onPause();
        connTask.cancelTask();
    }

    public void onResume() {
        super.onResume();
        ((android.widget.ImageView)findViewById(R.id.netImage)).setImageResource(new ConnectionDetector(this).isConnected() ? R.drawable.icon3 : R.drawable.icon5);
        try {
            connTask.execute(5000);
        } catch (Exception e) {

        }
    }

}
...