This is the my code ( check this file full code on GitHub) for Uploading an image to Firebase Storage.
// ImagePickerButton shows an image picker to upload a image for a message
mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
i.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(i, "Complete action using"), RC_PHOTO_PICKER);
}
});
This is the OnActivityResult Method:
#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 the reference to stored file at database
StorageReference selectedImageFilePath = mStorageReference.child(selectedImageUri.getLastPathSegment());
//upload file to firebase
selectedImageFilePath.putFile(selectedImageUri).addOnSuccessListener(MainActivity.this, new OnSuccessListener < UploadTask.TaskSnapshot > () {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
#SuppressWarnings("VisibleForTests")
String downloadUrl = taskSnapshot.getDownloadUrl().toString();
Message message = new Message(null, userName, downloadUrl);
messagesDatabaseReference.push().setValue(message);
}
});
}
}
}
Picking an Image from the Gallery works fine but I'm not able to upload the selected Image on Firebase Storage. Correct my code If I'm wrong at any site. However, I manually entered these lines in my manifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I'm currently running the app in my own mobile device connected via USB( Moto G4 - Nougat)
data.getData() could return an URI that does not point to a File.
You should use
InputStream is = getContentResolver().openInputStream(data.getData())
and than use
selectedImageFilePath.putStream(is)
Also you could add an onFailureListener to the upload task and debug what is going wrong.
In addition, if I recall correctly, I do not think you need the storage permissions when you directly read the data in onActivityResult.
Try this for button click :
//Select Image functionality
btnselectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 2);
}
});
For saving image to fire base :
//Storing and getting image from firebase
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_INTENT && resultCode == RESULT_OK){
final Uri uri = data.getData();
StorageReference filepath = mStorageRef.child("Photos").child(name);
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUri = taskSnapshot.getDownloadUrl();
//Getting url where image is stored
saveImage(downloadUri);
Picasso.with(getActivity()).load(downloadUri).fit().centerCrop().into(profileImage);
}
});
}
This works fine for me, Hope this will help.
Instead of else if statement, I modified it by writing a seperate if statement.
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
}else if (resultCode == RESULT_CANCELED) {
}
// This was the change I made
if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
}
}
If ( //sign in)
{
If (//result ok)
{}
else if (//result cancel)
{}
}
else if (//rc photot picker && result ok)
{ //your storage code here.....}
tats works perfectly.....check out the braces carefully....
Related
I am trying to upload an image in imageview on the profile fragment. I can upload the image succesfully, but then application very slows down. This is my code:
private void checkAndRequestForPermission() {
if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_FILE);
}
else{
openGallery();
}
}
private void openGallery() {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_PICK);
startActivityForResult(galleryIntent, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode ==1 && resultCode == RESULT_OK && data!=null && data.getData() !=null) {
getProfilePictureUri = data.getData();
profile_picture.setImageURI(getProfilePictureUri);
}
}
Should I change Uri to Bitmap? Thank you for your help.
Edit: I want to upload high resolution images, If I reduce the size, won't the resolution decrease?
In my activity how can I use two select buttons in same activity to select files from internal storage and upload on database using same upload button
Yes. Just you need do on onActivityResult put upload button method when is selected file. It's gonna upload straight file when it's selected.
Look at this
public void choosefile() {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent cInt = new Intent(MediaStore.ACTION_GET_CONTENT);
cInt.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(cInt,100);
}
and on result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
upload(media_path);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getActivity(), "Cancelled front", Toast.LENGTH_LONG).show();
}
}
}
I want to upload multiple images through android application to firebase. I want to get the URL of the image which i got in my second activity(ie, B Activity) to my first activityIA activity). I have tried many answers posted but I could not solve the issue. Can anyone help me please. Here is my code
B Activity
mSelectBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), RESULT_LOAD_IMAGE);
} });
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
if(data.getClipData() != null){
totalItemsSelected = data.getClipData().getItemCount();
for(int i = 0; i < totalItemsSelected; i++){
Uri fileUri = data.getClipData().getItemAt(i).getUri();
String fileName = getFileName(fileUri);
fileNameList.add(fileName);
fileDoneList.add("uploading");
uploadListAdapter.notifyDataSetChanged();
StorageReference fileToUpload = mStorage.child("Images").child(fileName);
final int finalI = i;
fileToUpload.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileDoneList.remove(finalI);
fileDoneList.add(finalI, "done");
uploadListAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();
ImageUploadInfo imageUploadInfo = new ImageUploadInfo(taskSnapshot.getDownloadUrl().toString());
imageURL=imageUploadInfo.getImageURL();
imagesList.add(imageURL);
Intent idata = new Intent()
idata.putExtra("imageURL", imageURL);
idata.putExtra("count",totalItemsSelected);
setResult(RESULT_OK, idata);
finish();
}
});
}
A activity
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (resultCode) {
case 1:
if (requestCode == 123) {
if (resultCode == RESULT_OK) {
imageURL = data.getStringExtra("imageURL");
this.orderItem.setImageURL(imageURL);
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
break;
case 2://added24
if(requestCode==100){//added24
if (resultCode == RESULT_OK) {
imageURL = data.getStringExtra("imageURL");
newString=data.getStringExtra("count");
}
}
break;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.order_item_update, menu);
FrameLayout image_viewCount = (FrameLayout) menu.findItem(R.id.star).getActionView();
TextView image_count = (TextView) image_viewCount.findViewById(R.id.cart_badge);
image_count.setText(newString);
image_viewCount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(),MultipleActivity.class);
Order.getInstance().getOrderItems();
startActivityForResult(intent,100);
}
});
I want to set the count (ie, "total selected" in image_count) but I am not able to get the value as I am not getting the value from Bactivity to A activity
change the onActivityResult in your A activity to,
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 123:
if (resultCode == RESULT_OK) {
imageURL = data.getStringExtra("imageURL");
this.orderItem.setImageURL(imageURL);
} else if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
break;
case 100:
if (resultCode == RESULT_OK) {
imageURL = data.getStringExtra("imageURL");
newString = data.getStringExtra("count");
} else {
//Write your code if there's no result
}
break;
}
}
You were switching resultCode and the cases you used were 1 and 2. The int constant for RESULT_OK is -1.
And in your MultipleActivity activity, the condition data.getClipData() != null will only be true when there are multiple Uris to send back. When there is just one you can get it with getData. You can do it like this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK) {
if (data.getClipData() != null) {
totalItemsSelected = data.getClipData().getItemCount();
for (int i = 0; i < totalItemsSelected; i++) {
Uri fileUri = data.getClipData().getItemAt(i).getUri();
String fileName = getFileName(fileUri);
fileNameList.add(fileName);
fileDoneList.add("uploading");
uploadListAdapter.notifyDataSetChanged();
StorageReference fileToUpload = mStorage.child("Images").child(fileName);
final int finalI = i;
fileToUpload.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileDoneList.remove(finalI);
fileDoneList.add(finalI, "done");
uploadListAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();
ImageUploadInfo imageUploadInfo = new ImageUploadInfo(taskSnapshot.getDownloadUrl().toString());
imageURL = imageUploadInfo.getImageURL();
imagesList.add(imageURL);
Intent idata = new Intent();
idata.putExtra("imageURL", imageURL);
idata.putExtra("count", totalItemsSelected);
setResult(RESULT_OK, idata);
finish();
}
});
}
} else {
Uri fileUri = data.getData();
String fileName = getFileName(fileUri);
fileNameList.add(fileName);
fileDoneList.add("uploading");
uploadListAdapter.notifyDataSetChanged();
StorageReference fileToUpload = mStorage.child("Images").child(fileName);
fileToUpload.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileDoneList.remove(0);
fileDoneList.add(0, "done");
uploadListAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();
ImageUploadInfo imageUploadInfo = new ImageUploadInfo(taskSnapshot.getDownloadUrl().toString());
imageURL = imageUploadInfo.getImageURL();
imagesList.add(imageURL);
Intent idata = new Intent();
idata.putExtra("imageURL", imageURL);
idata.putExtra("count", 1);
setResult(RESULT_OK, idata);
finish();
}
});
}
}
}
Your issue is that the fileToUpload is async and you are creating them in a loop; you close the current activity when one of those tasks ends (the first one). You can simulate a semaphore, to mark the completion of each fileToUpload tasks and store the result in it, and in the onSuccess method, just check if all task instances are completed before closing the current activity and passing the result (which should be an array of objects btw).
As I understood:
Activity-A opens Activity-B using startActivityForResult.
and you want image url which you got in Activity-B to Activity-A via onActivityResult().
If so then,
you have to add your activity finish code in some action not into onActivityResult() of Activity-B.
Because adding it to onActivityResult() means you are waiting for the response of any Activity you open from Activity-B using startActivityForResult.
I am trying to capture image from camera. But it returns null Intent onActivityResult .
Here is my code
CaptureImageFromCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 7);
}
});
And onActivityResult is
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 7 && resultCode == RESULT_OK) {
try {
if(data.getData() == null) {
bitmap = (Bitmap)data.getExtras().get("data");
} else {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
}
ImageViewHolder.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am new to Android so please explain answer in detail.
Thanks in advance..!
Start Your work by passing intent through this :
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE), 100);
so after capturing the image from camera use to get data about images through intent :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri yourCapturedImage = intent.getData();
}
Make sure you have added camera permissions, write permissions in manifest and also cross verify run time permissions.
Use your Intent like below, and specify the path where captured image will be write -
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Uri outputUri = Uri.fromFile("path of your directory");
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
startActivityForResult(intent, 7);
You can also use setImageURI() in onActivityResult() instead of setImageBitmap()
First of all add the camera permissions in android manifest. If your android version is greater than lollipop then you need to add run time permissions See documentations here
<uses-permission android:name="android.permission.CAMERA"/>
and then your code will be
CaptureImageFromCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 7);
}
});
and then use setImageUrI() in your onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
case 7:
/*case 7 for image results and display image in imageview via Uri*/
if (resultCode == RESULT_OK)
{
Uri imageUri = data.getData();
ImageViewHolder.setImageURI(imageUri);
}
return;
default:
return;
}
}
Uri imageUri = data.getData() will no more work..
first get bitmap from data like this:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
val imageBitmap = data.extras.get("data") as Bitmap
imageView.setImageBitmap(imageBitmap)
}
}
then save bitmap image.. please find details here:
https://developer.android.com/training/camera/photobasics
I'm trying to upload an image from Gallery to Firebase Storage.
Picking an Image from the Gallery works fine but then the selected Image is not being uploaded to Firebase Storage.
I think the problem is with this module in my code which I'm not able to figure out.
if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
// Get a reference to store file at photos/<FILENAME>
StorageReference photoRef = mPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
//Upload file to Firebase Storage
photoRef.putFile(selectedImageUri)
.addOnSuccessListener(this, new OnSuccessListener < UploadTask.TaskSnapshot > () {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
#SuppressWarnings("VisibleForTests")
Uri downloadUrl = taskSnapshot.getDownloadUrl();
// Set the download URL to the message box, so that the user can send it to the database
Message message = new Message(null, userName, downloadUrl.toString());
messagesDatabaseReference.push().setValue(message);
}
});
I'm running my app on my mobile device Moto G4 (Android Nougat) through USB.
In my OnActivityResult, I modified the following:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
....
} else if (resultCode == RESULT_CANCELED) {
....
}
} else if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
}
}