How to make image upload not just from camera? - android

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

Related

Upload image to firebase failed when clicking anything in comfirmation page and the app crash

I have a question about upload image to firebase and it works before and after I done other activity...It failed...Can your guys help me...
The main error was when user click OK or CANCEL in confirmation page, the app crash. App will crash too when user select from gallery...
Here is the logcat...
2021-03-30 22:56:16.853 12576-12576/? E/in.firebasetes: Unknown bits set in runtime_flags: 0x8000
And here is the code for activity...
user = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("Users");
userID = user.getUid();
storageReference = FirebaseStorage.getInstance().getReference();
UserPic = (ImageView) findViewById(R.id.UserPic);
UserPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
VerifyPermission();
}
if (user != null){
if (user.getPhotoUrl() != null) {
Glide.with(this).load(user.getPhotoUrl()).into(UserPic);
}
}
}
private void VerifyPermission() {
if (ContextCompat.checkSelfPermission(UserProfile.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UserProfile.this, new String[] {Manifest.permission.CAMERA}, CAMERA_PERMISSION_CODE);
}else {
Toast.makeText(this, "OK", Toast.LENGTH_SHORT).show();
selectOptionList();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == CAMERA_PERMISSION_CODE){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
selectOptionList();
}else {
Toast.makeText(UserProfile.this, "Camera Permissions is required", Toast.LENGTH_LONG).show();
}
}
}
private void selectOptionList(){
selectList = getResources().getStringArray(R.array.selectList);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select an option");
builder.setItems(selectList, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
dispatchTakePictureIntent();
break;
case 1:
Intent pickPhoto = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, GALLERY_REQUEST_CODE);
break;
case 2:
dialog.dismiss();
break;
}
}
});
alertDialog = builder.create();
builder.show();
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this, "interpayment.main.firebasetest.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + userID + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
//File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
currentPhotoPath = image.getAbsolutePath();
Toast.makeText(UserProfile.this, "Opening Camera", Toast.LENGTH_SHORT).show();
return image;
}
private void uploadImageToFirebase(String name, Uri contentUri) {
final StorageReference img = storageReference.child("pictures/" + name);
img.putFile(contentUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
img.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.d("100", "onSuccess: Upload Image URL is " + uri);
Toast.makeText(UserProfile.this, "Uploaded", Toast.LENGTH_SHORT).show();
setUserProfileUrl(uri);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UserProfile.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
});
}
private void setUserProfileUrl(Uri uri) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest request = new UserProfileChangeRequest.Builder().setPhotoUri(uri).build();
user.updateProfile(request).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(UserProfile.this, "Updated", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UserProfile.this, "Failed set Profile", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
if (requestCode == CAMERA_REQUEST_CODE) {
File f = new File(currentPhotoPath);
UserPic.setImageURI(Uri.fromFile(f));
Log.d("tag", "Absolute Url of Image is " + Uri.fromFile(f));
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
uploadImageToFirebase(f.getName(), contentUri);
}else if(requestCode == GALLERY_REQUEST_CODE && data != null){
Uri img = data.getData();
Log.d("tag", "onActivityResult: Gallery Image Uri: " + img);
UserPic.setImageURI(img);
uploadImageToFirebase(currentPhotoPath, img);
}
}
}
I appreciate for your guys helping and thanks a lot for taking time to help me. Logcat was like this...
Logcat
----------------------------------------------------------------------
Update
My question is solved. The problem was the onStop function, I removed it. This is because the system set the [open camera] and [take photo from gallery] as new actitvity. So, if you have the onStop function, system close the apps when you open camera or others. This cause the apps automatically close and no any error in logcat.

video thumbnail of selected video while uploading on firebase storage

i am uploading video to firebase storage. i want to show the thumbnail of selected video on app screen
i have tried uploading image with the same code and it gives me the image preview of selected image, but it doesnot show any preview or thumbnail of selected video
moreover i want to know hoe to give the path of selected video as well..
main activity
public class MainActivity extends AppCompatActivity {
private static final int PICK_VIDEO_REQUEST = 3;
Button chooseImg, uploadImg;
ImageView imgView;
int PICK_IMAGE_REQUEST = 111;
Uri filePath;
ProgressDialog pd;
//creating reference to firebase storage
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://<<ur app url>>"); //change the url according to your firebase app
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chooseImg = (Button)findViewById(R.id.chooseImg);
uploadImg = (Button)findViewById(R.id.uploadImg);
imgView = (ImageView)findViewById(R.id.imgView);
pd = new ProgressDialog(this);
pd.setMessage("Uploading....");
chooseImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Video"), PICK_VIDEO_REQUEST);
}
});
uploadImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(filePath != null) {
pd.show();
StorageReference childRef = storageRef.child("vide.mp4");
//uploading the image
UploadTask uploadTask = childRef.putFile(filePath);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload Failed -> " + e, Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(MainActivity.this, "Select a video", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
//getting image from gallery
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting image to ImageView
imgView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

Firebase Image Upload - Android

I am trying to upload Image to firebase storage but I am neither seeing the progress dialog nor the toast message.
The debug breakpoint is not even stopping at those lines.
Please help.
ib_profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent_modifyImage = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(intent_modifyImage);
}
});
}
//Image Capture Activity Result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
progressDialog.setMessage("Uploading Image...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filepath = storageReference_image.child("profile_photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(UserProfileActivity.this,"Upload Complete",Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
}
try this
public class MainActivity extends AppCompatActivity {
Button chooseImg, uploadImg;
ImageView imgView;
int PICK_IMAGE_REQUEST = 111;
Uri filePath;
ProgressDialog pd;
//creating reference to firebase storage
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://fir-example-c4312.appspot.com"); //change the url according to your firebase app
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chooseImg = (Button)findViewById(R.id.chooseImg);
uploadImg = (Button)findViewById(R.id.uploadImg);
imgView = (ImageView)findViewById(R.id.imgView);
pd = new ProgressDialog(this);
pd.setMessage("Uploading....");
chooseImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
}
});
uploadImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(filePath != null) {
pd.show();
StorageReference childRef = storageRef.child("image.jpg");
//uploading the image
UploadTask uploadTask = childRef.putFile(filePath);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload Failed -> " + e, Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(MainActivity.this, "Select an image", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
//getting image from gallery
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting image to ImageView
imgView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
don't forget to Change Rules in firebase console
By default we are not allowed to access firebase storage without authentication. To change it go to firebase console using any web browser. Open the firebase project that you have used in above steps and go to Storage and then Rules tab. Now change read and write rules to true as shown in below image.
try this method,its worked for me
Inside onActivityResult,
StorageReference storageRef = storage.getReferenceFromUrl(---STORAGE_BUCKET---);
StorageReference imagePathReference = storageRef.child("image");
final Uri uri = data.getData();
Bitmap bmp = null;
try {
bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
// convert bitmap to byte array to save image in firebase storage
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if (bmp != null) {
bmp.compress(Bitmap.CompressFormat.JPEG, 60, bos);
}
byte[] dataNew = bos.toByteArray();
uploadTask = imagePathReference.putBytes(dataNew);
try {
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// success
}
});
}catch (Exception e){
}

how to upload to firebase a file with firebase storage

i try to upload to firebase a picture and when i upload its show me that the size of the file is 0 bytes and dont show the content picture
everything seems fine, then whay its happen???
StorageReference storageRef = storage.getReferenceFromUrl("gs://<your-bucket-name>");
if (inputStream!=null) {
String pic = "BathroomImage" + +rand.nextInt(1000) + ".jpg";
mountainsRef = storageRef.child(pic);
uploadTask = mountainsRef.putStream(inputStream);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("this is the faiure:","hey im here");
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getMetadata();
Uri downloadUri = taskSnapshot.getDownloadUrl();
bitmap.recycle();
bitmap=null;
System.gc();
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
here i upload the picture from the data to inputsream.
void TakePickphoto(){
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); // Create intent to Open Image applications like Gallery, Google Photos
startActivityForResult( galleryIntent, RESULT_LOAD_IMAGE);// Start the Intent
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode ==getActivity().RESULT_OK && null != data) {
selectedImage = data.getData(); // Get the URI Image from data
handler= new Handler();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
inputStream = context.getContentResolver().openInputStream(data.getData());
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize =4;
bitmap = BitmapFactory.decodeStream(inputStream, new Rect(40,40,40,40),options);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
ImageView imageView;
imageView = (ImageView) view.findViewById(R.id.imageView2);
imageView.setImageBitmap(bitmap);
}
});
}
};
new Thread(runnable).start();
}
}
}
please help, everything look fine to me.
** This will not save the image in full resolution **
To save a picture in full resolution, research how to do that when you start the TakePictureIntent.
I had the same error and solved it by setting up my picture taking and uploading like this:
//takes the picture
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(takePictureIntent, 1);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
//saves the pic locally
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] dataBAOS = baos.toByteArray();
/***************** UPLOADS THE PIC TO FIREBASE*****************/
// Points to the root reference
StorageReference storageRef = FirebaseStorage.getInstance().getReferenceFromUrl("your-root-storage-ref");
StorageReference imagesRef = storageRef.child("image");
UploadTask uploadTask = imagesRef.putBytes(dataBAOS);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
}
});
}
}
This way it will compress and save your image in your Firebase Storage with this file struct:
root -> image
You can pass the InputStream directly from the Uri to the putStream method. You may want to resize the image yourself before uploading it, which would require a bit more work, but this way uses very little memory on the client side.
if (requestCode == IMAGE_PICKER_SELECT && resultCode == Activity.RESULT_OK) {
Uri imageUri = data.getData();
try {
ContentResolver contentResolver = getActivity().getContentResolver();
StorageMetadata storageMetadata = new StorageMetadata.Builder()
.setContentType(contentResolver.getType(imageUri))
.build();
FirebaseStorage.getInstance().getReference()
.child("users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(UUID.randomUUID().toString())
.putStream(contentResolver.openInputStream(imageUri), storageMetadata)
.addOnSuccessListener(getActivity(), new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot task) {
Uri downloadUrl = task.getDownloadUrl();
Toast.makeText(getActivity(), R.string.image_successfully_uploaded, Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(getActivity(), new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), R.string.error_uploading_image, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}

App stops responding when startActivityForResults is called second time

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!!!

Categories

Resources