android – How to store capture image into Firebase?-ThrowExceptions

Exception or error:

I’ve been struggled in adding Image Captured to store in Firebase. In my code, there is two parts, one part for image choose from gallery and the another one is Camera Activity. Actually, the Camera is functioned, but I don’t know how to insert it into firebase. So anyone please help me to solve this issued. This Activity is quite long because i combined two activities (choose image from gallery, and Camera Activity)

Uploadfile.Java

public class Uploadfile extends AppCompatActivity implements PopupMenu.OnMenuItemClickListener {

    private static final int CHOOSE_IMAGE = 1;


    private Button chooseImage, btnUploadImage,ticketType,Ticketinformation;
    private Button viewGallery, Cameraa;
    private ImageView imgPreview;
    private EditText imgDescription;
    private Uri imgUrl;
    private ProgressBar mProgressbar;
    private StorageReference mStorageRef;
    private DatabaseReference mDatabaseRef;
    private StorageTask mUploadTask;
    private static final int PERMISSION_CODE = 1000;
    private static final int IMAGE_CAPTURE_CODE = 1001;
    Uri image_uri;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_uploadfile);

        ticketType = (Button)findViewById(R.id.tickettype);
        chooseImage = (Button)findViewById(R.id.choose2);
        Cameraa = (Button)findViewById(R.id.choose3);
        btnUploadImage = (Button)findViewById(R.id.uploadImage);
        viewGallery = (Button)findViewById(R.id.viewImage);
        Ticketinformation =(Button)findViewById(R.id.ticinfo);
        imgPreview = (ImageView)findViewById(R.id.imageup);
        imgDescription = (EditText)findViewById(R.id.imgDescript);
        mProgressbar = (ProgressBar)findViewById(R.id.progressImage);

        Cameraa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                {
                    if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED
                            || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)
                    {
                        String [] permission = {Manifest.permission.CAMERA , Manifest.permission.WRITE_EXTERNAL_STORAGE};
                        requestPermissions(permission,PERMISSION_CODE);
                    }
                    else
                    {
                        openCamera();
                    }
                }
                else
                {

                }
            }
        });

        viewGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Uploadfile.this,viewImageUpload.class);
                startActivity(intent);
            }
        });

        Ticketinformation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Uploadfile.this,TicketInfo.class);
                startActivity(intent);
            }
        });

        mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
        mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");

        chooseImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFileChoose();
            }
        });
        btnUploadImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mUploadTask !=null && mUploadTask.isInProgress())
                {
                    Toast.makeText(Uploadfile.this, "Upload in Progress ", Toast.LENGTH_LONG).show();
                }
                else
                {
                    uploadFile();
                }
            }
        });


        Bundle bundle = getIntent().getExtras();
        if (bundle != null)
        {
            if (bundle.getString("some") != null)
            {
                Toast.makeText(getApplicationContext(),"data:" +bundle.getString("some"),Toast.LENGTH_SHORT).show();
            }
        }

    }

    private  void openCamera ()
    {

        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, "New Picture");
        values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera");
        image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);

        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
        startActivityForResult(cameraIntent,IMAGE_CAPTURE_CODE);


    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode)
        {
            case PERMISSION_CODE:
            {
                if (grantResults.length > 0 && grantResults[0] ==PackageManager.PERMISSION_GRANTED)
                {
                    openCamera();
                }
                else
                {
                    Toast.makeText(this,"Permission Denied",Toast.LENGTH_SHORT).show();
                }
            }
        }
    }


    public void Popup  (View v)
    {

        PopupMenu popup = new PopupMenu(this,v);
        popup.setOnMenuItemClickListener(this);
        popup.inflate(R.menu.popupmenu);
        popup.show();
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
       switch (item.getItemId())
        {
            case R.id.bus:
                Toast.makeText(this,"Bus Ticket",Toast.LENGTH_SHORT).show();
                return true;
            case R.id.train:
                Toast.makeText(this,"Train Ticket",Toast.LENGTH_SHORT).show();
                return true;
            case R.id.concert:
                Toast.makeText(this,"Concert Ticket",Toast.LENGTH_SHORT).show();
                return true;
            case R.id.coupon:
                Toast.makeText(this,"Coupon Ticket",Toast.LENGTH_SHORT).show();
                return true;
                default:
                    return false;
        }
    }

    private void uploadFile() {
        if (imgUrl!=null)
        {
            final StorageReference filereference = mStorageRef.child(System.currentTimeMillis()+ "." +getFileExtension(imgUrl));
            filereference.putFile(imgUrl)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            Handler handler = new Handler();
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    mProgressbar.setProgress(0);
                                }
                            },5000);


                            filereference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {

                                    DatabaseImage databaseImage = new DatabaseImage(imgDescription.getText().toString().trim(),uri.toString());
                                    String uploadID= mDatabaseRef.push().getKey();
                                    mDatabaseRef.child(uploadID).setValue(databaseImage);
                                    Toast.makeText(Uploadfile.this,"Upload SuccessFull",Toast.LENGTH_SHORT).show();
                                    imgPreview.setImageResource(R.drawable.imagepreview);
                                    imgDescription.setText("");
                                    ticketType.setText("");
                                }
                            });



                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(Uploadfile.this,e.getMessage(),Toast.LENGTH_SHORT).show();


                        }
                    })
                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                            double progress = (100.0 *taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
                            mProgressbar.setProgress((int) progress);
                        }
                    });
        }
        else
        {
            Toast.makeText(this,"No File Selected", Toast.LENGTH_SHORT).show();
        }
    }

    private String getFileExtension (Uri uri)
    {
        ContentResolver cr = getContentResolver();
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        return mime.getExtensionFromMimeType(cr.getType(uri));
    }

    private void showFileChoose ()
    {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent,CHOOSE_IMAGE);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode==CHOOSE_IMAGE && resultCode== RESULT_OK && data !=null && data.getData() != null)
        {
            imgUrl = data.getData();
            Picasso.get().load(imgUrl).into(imgPreview);
        }
        if (resultCode == RESULT_OK) {

            image_uri = data.getData();
            imgPreview.setImageURI(image_uri);
        }

    }
}
How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *