Sir,I am making an chat app where I want to pick an image and upload it on database.for this i used intent and startActivityForResults to open a gallery then then selects required image and finally handle the data in onActivityResults.this works well for the first time but when i perform the same operation second time app stops responding.Here is my code
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(intent,1);
}
});
and handle code in same activity:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
Toast.makeText(this, "hello", Toast.LENGTH_LONG)
.show();
// When an Image is picked
if (requestCode == 1 && resultCode == RESULT_OK&& data!=null) {
// Get the Image from data
Uri selectedImageURI = data.getData();
UploadTask uploadTask = storageRef.child("images/" + "IMG" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())).putFile(selectedImageURI);
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
Toast.makeText(Chat.this, ""+progress, Toast.LENGTH_LONG)
.show();
}
}).addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
#Override
public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
System.out.println("Upload is paused");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
Toast.makeText(Chat.this, "You haven't failure Image",
Toast.LENGTH_LONG).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Handle successful uploads on complete
Uri downloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
Toast.makeText(Chat.this, "success", Toast.LENGTH_LONG).show();
}
});
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
there is no logcat error as app doesn't crashes.it just stops responding with a dialog box asking wait or stop.Please Help!!!
Related
I am quiet new to firebase and i'm trying to upload a image on firebase and whenever I try to upload It always say that uri is null. So I made a if condition if its null then it wont do the uploading.
I am quiet sure that the image is taking picture because I made a imageview so I can see the picture I've taken and its working properly
This is the code I use for my camera
private void askCameraPermissions() {
if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA}, CAMERA_PERM_CODE);
}
else
{
openCamera();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == CAMERA_PERM_CODE)
{
if (grantResults.length < 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
openCamera();
}
else{
Toast.makeText(this, "Camera Permission Needed", Toast.LENGTH_SHORT).show();
}
}
}
private void openCamera() {
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera, CAMERA_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && data != null) {
imageuri = data.getData();
Bitmap image = (Bitmap) data.getExtras().get("data");
selfie.setImageBitmap(image);
Toast.makeText(getApplicationContext(), "Upload Success", Toast.LENGTH_SHORT).show();
}
}
And this is the code I use to upload Image
private void uploadPicture() {
if (imageuri != null) {
final ProgressDialog pd = new ProgressDialog(this);
pd.setTitle("Uploading...");
pd.show();
StorageReference riversRef = storageReference.child(System.currentTimeMillis() + ".jpg");
riversRef.putFile(imageuri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
Snackbar.make(findViewById(android.R.id.content), "Attendance successful.", Snackbar.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
pd.dismiss();
Toast.makeText(getApplicationContext(), "Attendance Unsuccessful", Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double progressPercent = (100.00 * snapshot.getBytesTransferred() / snapshot.getTotalByteCount());
pd.setMessage("Progress: " + (int) progressPercent + "%");
}
});
}
else{
Toast.makeText(getApplicationContext(), "Attendance Unsuccessful", Toast.LENGTH_SHORT).show();
}
}
Here I am using imagecropper dependency to crop and upload it to Firebase.
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PICK_GALLERY_CODE) {
Uri image_uri = data.getData();
CropImage.activity(data.getData())
.setGuidelines(CropImageView.Guidelines.ON)
.start(getActivity());
//Updateprofilephoto(image_uri);
} else if (requestCode == IMAGE_PICK_CAMERA_CODE) {
//profileIv.setImageURI(image_uri);
CropImage.activity(data.getData())
.setGuidelines(CropImageView.Guidelines.ON)
.start(getActivity());
//uploadProfilePhoto(resulturi);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
Updateprofilephoto(resultUri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
My code works until this. I can crop the image by choosing an image from my gallery. But by using the following method I cannot upload my cropped image to the Firebase. The original image is uploaded to the Firebase. Not the cropped one. How can I solve that issue?
The code follows:
private void Updateprofilephoto(Uri resulturi) {
progressDialog.setMessage("Updating Account Info...");
progressDialog.setProgressStyle(progressDialog.STYLE_SPINNER);
progressDialog.show();
String filePathAndName = "profile_image/" + "" + firebaseAuth.getUid();
StorageReference storageReference = FirebaseStorage.getInstance().getReference(filePathAndName);
storageReference.putFile(resulturi)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) ;
Uri downloadImageUri = uriTask.getResult();
if (uriTask.isSuccessful()) {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("profileImage", "" + downloadImageUri);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
ref.child(firebaseAuth.getUid()).updateChildren(hashMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "Profile Picture is updated...", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
I have three buttons in my application. One is for a camera, second is for a gallery and the third one is to upload. I changed my upload method from web server to googles firebase. Currently, I am only able to upload from my camera button. If I try to upload from gallery button it starts searching image in a temporary folder where images are saved when they are taken by a camera.
Taking image from gallery:
private void ImageSelection()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, IMAGE_REQUEST);
}
On activity method:
else if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK && data != null)
{
Uri FilePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePath);
mImageView.setImageBitmap(bitmap);
mImageView.setVisibility(View.VISIBLE);
mEditText.setVisibility(View.VISIBLE);
staticSpinner.setVisibility(View.VISIBLE);
if (TextUtils.isEmpty(mEditText.getText())){
mEditText.setError("Privalomas laukas");
}
} catch (IOException e) {
e.printStackTrace();
}
}
Upload method:
private void UploadImage() {
if(photoFile != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/"+ staticSpinner.getSelectedItem().toString().trim()+"_"+ mEditText.getText().toString());
ref.putFile(Uri.fromFile(photoFile))
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
mImageView.setImageResource(0);
mImageView.setVisibility(View.GONE);
mEditText.setText("");
mEditText.setVisibility(View.GONE);
staticSpinner.setVisibility(View.GONE);
mCapture.setVisibility(View.VISIBLE);
mChoose.setVisibility(View.VISIBLE);
//mUpload.setVisibility(View.GONE);
photoFile = new File(String.valueOf(photoFile));
photoFile.delete();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
mImageView.setImageResource(0);
mImageView.setVisibility(View.GONE);
mEditText.setText("");
mEditText.setVisibility(View.GONE);
staticSpinner.setVisibility(View.GONE);
mCapture.setVisibility(View.VISIBLE);
mChoose.setVisibility(View.VISIBLE);
//mUpload.setVisibility(View.GONE);
photoFile = new File(String.valueOf(photoFile));
photoFile.delete();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
Added an else if statement. Stupid me
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("video/*");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
// Get a reference to store file at chat_photos/<FILENAME>
StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
// Upload file to Firebase Storage
photoRef.putFile(selectedImageUri)
.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
// progressBar.setVisibility(View.VISIBLE);
Uri downloadUrl = taskSnapshot.getDownloadUrl();
// Set the download URL to the message box, so that the user can send it to the database
Video video = new Video(downloadUrl.toString());
mMessagesDatabaseReference.push().setValue(video);
}
});
}
}
I want to show progress on seekbar when image is uploading as a notification. How do I do that? I have created an object of Seekbar in my onCreate. How to get duration of the video which I am uploading and show the seekbar in notification and the user should not be able to swipe notification when upload starts? Please help.
you can do that by using addOnProgressListener
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
int progress = (int) ((100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount());
try {
yourSeekBar.setProgress(progress);
} catch (Exception e) {
e.printStackTrace();
}
}
})
I have not use authentication yet, in the screen i can see the progress dialog working but its not getting stop. I think there is a problem.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==GALLERY_INTENT&&resultCode==RESULT_OK){
progressDialog.setMessage("Uploading Image...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filepath = mStorageRef;
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Uploading Finished",Toast.LENGTH_LONG).show();
}
});
}
}
//firebase storage rule
service firebase.storage {
match /b/csapplication-b6e5e.appspot.com/o {
match /{allPaths=**} {
allow read, write: if request.auth == null;
}
}
}
Its because of if your file upload to firebase was successful means your ProgressDialog will be dismissed ,if not in the case of failure you have to dismiss (ProgressDialog) in the OnFailure method in the code below .
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Uploading Finished",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads - Dismiss the ProgressDialog here
progressDialog.dismiss();
Toast.makeText(Profile.this, "Unable to Uploaded Error in Firebase",Toast.LENGTH_LONG).show();
}});