Get images from firebase storage and realtime database - java

So, I wanna make the user upload multiple images at the same time to firebase storage. I have done that part successfully but now I want to retrieve the images back. At first, I was uploading one image per user and save the image id to the realtime database so it was very easy to retrieve the image back by the image id. But now how can I save more than one image to the realtime database per user I can't use the same child name because it will be replaced with the old one. Any ideas??
Uploding images and setting the id on realtime database:
private void Fileuploader() throws FileNotFoundException {
String imageid;
progress.showProgress(profuctadd.this,"Loading...",false);
DatabaseHelper databaseHelper = new DatabaseHelper(profuctadd.this);
Cursor getimage = databaseHelper.GetPath();
int count = 0;
while (getimage.moveToNext()){
Bitmap bm = BitmapFactory.decodeFile(getimage.getString(0));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 35, out);
imageid = arabic.getText().toString()+"-"+System.currentTimeMillis()+"_"+(count++)+"."+getExtension(uri);
System.out.println("IMAGES UPLOADEDDDD: "+ imageid);
String id = getIntent().getStringExtra("storeid");
member.setImageid(imageid);
reference.child(id).child(arname).setValue(member);
byte[] data = out.toByteArray();
StorageReference Ref = mStorageRef.child(imageid);
Ref.putBytes(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
//Toast.makeText(profuctadd.this,"Image uploaded",Toast.LENGTH_LONG).show();
progress.hideProgress();
Intent intent = new Intent(profuctadd.this,showProducts.class);
intent.putExtra("spec",getIntent().getStringExtra("spec"));
intent.putExtra("storeid",getIntent().getStringExtra("storeid"));
startActivity(intent);
DatabaseHelper mDatabaseHelper = new DatabaseHelper(profuctadd.this);
Cursor cursor2 = mDatabaseHelper.DeleteDataOfTableImagesAr();
cursor2.moveToNext();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(profuctadd.this,"Failed",Toast.LENGTH_LONG).show();
}
});
}
}
My firebase db:

you can save more than one image of specific user in images node like that.
DatabaseReference dr = FirebaseDatabase.getInstance().getReference("tL131);
dr.child("images").push().setValue(String.ValueOf(taskSnapshot.getDownloadUrl()));

Related

Add multiple pictures into firebase [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I know this question has been asked a lot. But literally non of the answers work for me.
My problem is the images appeared to be saved but on firebase but unfortunately they are the same name so firebase deletes the old one and a inserts a new one. I have done everything i can do to change the name but I can't find a way.
Here is my code for uploading!
private void Fileuploader() throws FileNotFoundException {
String imageid;
imageid = arabic.getText().toString()+"-"+System.currentTimeMillis()+"."+"jpg";
String id = getIntent().getStringExtra("storeid");
member.setImageid(imageid);
reference.child(id).child(arname).setValue(member);
progress.showProgress(profuctadd.this,"Loading...",false);
DatabaseHelper databaseHelper = new DatabaseHelper(profuctadd.this);
Cursor getimage = databaseHelper.GetPath();
while (getimage.moveToNext()){
Bitmap bm = BitmapFactory.decodeFile(getimage.getString(0));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 35, out);
byte[] data = out.toByteArray();
System.out.println("IMAGES UPLOADEDDDD: "+ data);
StorageReference Ref = mStorageRef.child(imageid);
Ref.putBytes(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
//Toast.makeText(profuctadd.this,"Image uploaded",Toast.LENGTH_LONG).show();
progress.hideProgress();
Intent intent = new Intent(profuctadd.this,showProducts.class);
intent.putExtra("spec",getIntent().getStringExtra("spec"));
intent.putExtra("storeid",getIntent().getStringExtra("storeid"));
startActivity(intent);
DatabaseHelper mDatabaseHelper = new DatabaseHelper(profuctadd.this);
Cursor cursor2 = mDatabaseHelper.DeleteDataOfTableImagesAr();
cursor2.moveToNext();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(profuctadd.this,"Failed",Toast.LENGTH_LONG).show();
}
});
}
}
Any ideas?
You're only calculating imageid once across all images, so each image will have the same name. You'll want to calculate a new value for each image, and probably also throw in a counter just to make sure they're all unique:
private void Fileuploader() throws FileNotFoundException {
String id = getIntent().getStringExtra("storeid");
member.setImageid(imageid);
reference.child(id).child(arname).setValue(member);
progress.showProgress(profuctadd.this,"Loading...",false);
DatabaseHelper databaseHelper = new DatabaseHelper(profuctadd.this);
Cursor getimage = databaseHelper.GetPath();
int count = 0;
while (getimage.moveToNext()){
Bitmap bm = BitmapFactory.decodeFile(getimage.getString(0));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 35, out);
byte[] data = out.toByteArray();
System.out.println("IMAGES UPLOADEDDDD: "+ data);
StorageReference Ref = mStorageRef.child(imageid);
String imageid = arabic.getText().toString()+"-"+System.currentTimeMillis()+"_"+(count++)+"."+"jpg";
Ref.putBytes(data)
...

Retrieve user image from cloud firestorage into Imageview

I'm using java to develop an android application, I'm using cloud firestore and firebase storage to store the user's profile picture.
When a user logs in, he/she can upload a profile picture and it will be loaded into an imageView,
The images are successfully uploaded to the storage and successfully loaded into the imageView.
However, when I re-run the application and log into the account I uploaded the picture from, the picture can't be loaded into the imageView like before.
Here's my code for uploading the picture:
if (mImageUri != null){
file = mStorageRef.child(userId+".png");
UploadTask = file.putFile(mImageUri).addOnSuccessListener(newOnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(EditDonatorProfile.this,"Image uploaded successfully",Toast.LENGTH_SHORT).show();
String Link = mImageUri.toString();
Upload upload = new Upload(userId,Link);
db.collection("profilePicture").document(userId).set(upload);
}
});
}
else
{
Toast.makeText(this,"Choose a file first",Toast.LENGTH_SHORT).show();
}
and here's my retrieve code:
DocumentReference documentReference1 =db.collection("profilePicture").document(userId);
documentReference1.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
String uri = documentSnapshot.getString("link");
StorageReference storageReference = StorageReference.getReference("Images/"+userId+".png");
if(uri == null)
return;
Uri link = Uri.parse(String.valueOf(uri));
Picasso.with(DonatorProfile.this).load(link).into(Photo);
}
});
getCurrentUser().updateProfile(new UserProfileChangeRequest.Builder()
.setPhotoUri().build());

Firebase Content - How to access taskSnapshot.getDownloadUrl() from outside the onSuccess() method

I am currently using Firebase to upload an image into Firebase content in Android Studio. Once the file has successfully uploaded, I receive the url of the uploaded image using taskSnapshot.getDownloadUrl(). I want to then put this url in the Firebase Real-time database as a reference. I'm struggling to access the taskSnapshot.getDownloadUrl() from outside the onSuccess() method. Any ideas, please?
I understand that you want to put the uploaded image URL into Firebase Database.
What you can do is, Declare a global variable of type String
private String imageUrl;
Then get the url of image inside onSuccess() method and store in the string
imageUrl = taskSnapshot.getDownloadUrl().toString();
then after the image is uploaded, you have the image URL as string, so just push it to database like this
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("ImageUrl").setValue(imageUrl);
# declare variable like below:
String Storage_Path = "Image_Uploads/";
String Database_Path = "All_Image_Uploads_Database";
# declare firebase storage or real time database variable like below :
StorageReference myrefrence;
DatabaseReference databaseReference;
myrefrence = FirebaseStorage.getInstance().getReference();
databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);
public void UploadImageFileToFirebaseStorage(Uri FilePathUri) {
// Checking whether FilePathUri Is empty or not.
if (FilePathUri != null) {
// Setting progressDialog Title.
// progressDialog.setTitle("Image is Uploading...");
// Showing progressDialog.
// progressDialog.show();
// Creating second StorageReference.
StorageReference storageReference2nd = myrefrence.child(Storage_Path + System.currentTimeMillis() + "." + GetFileExtension(FilePathUri));
// Adding addOnSuccessListener to second StorageReference.
storageReference2nd.putFile(FilePathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Getting image name from EditText and store into string variable.
//String TempImageName = ImageName.getText().toString().trim();
// Hiding the progressDialog after done uploading.
// progressDialog.dismiss();
// Showing toast message after done uploading.
//Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();
#SuppressWarnings("VisibleForTests")
ImageUploadInfo imageUploadInfo = new ImageUploadInfo("",taskSnapshot.getDownloadUrl().toString());
// Getting image upload ID.
String ImageUploadId = databaseReference.push().getKey();
// Adding image upload id s child element into databaseReference.
databaseReference.child(ImageUploadId).setValue(imageUploadInfo);
}
})
// If something goes wrong .
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Hiding the progressDialog.
//progressDialog.dismiss();
// Showing exception erro message.
// Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
}
})
// On progress change upload time.
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
// Setting progressDialog Title.
//progressDialog.setTitle("Image is Uploading...");
}
});
} else {
//Toast.makeText(MainActivity.this, "Please Select Image or Add Image Name", Toast.LENGTH_LONG).show();
}
}
// Creating Method to get the selected image file Extension from File Path URI.
public String GetFileExtension(Uri uri) {
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
// Returning the file Extension.`enter code here`
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}

Firebase Duplicates New Uploads On Storage

Whenever I make a continuous upload to Firebase, the latest photo that I upload will replace all the other link. it's a weird error and hard to believe.
get result image
String filePath = Environment.getExternalStorageDirectory() + "/image2.jpg";
selectedImageUri = Uri.parse(filePath);
imageView.setImageURI(selectedImageUri);
ImageCompression imageCompression = new ImageCompression(this);
String oath = imageCompression.compressImage(filePath);
uriN = Uri.fromFile(new File(oath));
upload the image
private void fabSend(){
if (uriN!=null){
final StorageReference photoRef = storageRef.child(selectedImageUri.getLastPathSegment() + ".jpg");
photoRef.putFile(uriN).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
image = (downloadUrl.toString());
postRef.push().setValue(new myAdapter(image,
description ,
user.getDisplayName())).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
progress.setVisibility(View.GONE);
imageView.setImageBitmap(null);
uriN = null;
fab.setVisibility(View.VISIBLE);
}
});
}
});}
The fact is if I quit the activity and relaunch it again, this does not happen. I have tried using reCreate() but the same happens.
All links are different ie different upload tokens and different images
but the last picture that is uploaded is the one shown for all links.
That's because you're stating that all images must have the same name (image2.jpg) in this line:
String filePath = Environment.getExternalStorageDirectory() + "/image2.jpg";
What you should do instead is get the Uri from the data parameter in onActivityResult() (I assume that's were you're getting the image result:
selectedImageUri = data.getData();
imageView.setImageURI(selectedImageUri);
ImageCompression imageCompression = new ImageCompression(this);
String oath = imageCompression.compressImage(filePath);
uriN = Uri.fromFile(new File(oath));
Edit: You can change the name before sending it to Firebase Storage, maybe adding date and time. Like this:
String newName = new SimpleDateFormat("yyyy-MM-dd-HHmm").format(new Date());
final StorageReference photoRef = storageRef.child("IMG-"+newName+ ".jpg");

Upload Image with a Text (connected) to Firebase Storage

I upload an image to Firebase Storage with Android. I have an app which send image immediately after captured a photo.
But I would like to create an app which show a photo in ImageView before sending. I'd like to write some text under the photo and next, upload both of them.
Which tools should I use to do this?
I've Picasso to download from Storage. But I can't manage how to show an ImageView after capturing a photo, next write some text(like name or description) and send it to Firebase.
The second challenge is how to show particular text with this image?
IMAGE <-> TEXT.
In Firebase Storage I don't see some field to store image with a text.
MainActivity.java:
private ProgressDialog mProgress;
private Bitmap bitmap;
private Button mUploadBtn;
private Button mSendBtn;
private EditText mEditText;
private ImageView mImageView;
Uri picUri;
private StorageReference mStorage;
private static final int CAMERA_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
mEditText = (EditText) findViewById(R.id.editText);
mSendBtn = (Button) findViewById(R.id.sendBtn);
mUploadBtn = (Button) findViewById(R.id.uploadBtn);
mImageView = (ImageView) findViewById(R.id.imageView);
mProgress = new ProgressDialog(this);
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File file=getOutputMediaFile(1);
picUri = Uri.fromFile(file); // create
i.putExtra(MediaStore.EXTRA_OUTPUT,picUri); // set the image file
startActivityForResult(i, CAMERA_REQUEST_CODE);
}
});
}
public void UploadWithText(){
String name = mEditText.getText().toString().trim();
}
/** Create a File for saving an image */
private File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyApplication");
/**Create the storage directory if it does not exist*/
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
/**Create a media file name*/
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == 1){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".png");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK ) {
mProgress.setMessage("Uploading Image...");
mProgress.show();
Uri uri = picUri;
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView);
Toast.makeText(MainActivity.this, "Uploaded Successfully.", Toast.LENGTH_LONG).show();
}
});
}
}
Maybe there is a way that I can send the image to Firebase Storage but a Text(description) is sending to Database with a Name field(from Firebase Storage) and with this I can recognize which Text belongs to a particular image?
Could somebody help me to resolve this challenge?
Regards
I can only answer broadly, since there's a bit too much code to answer specifically without doing it for you. In general, there are few ways to do this:
Add text to the image file itself, upload the new image with changes made
Store text as an image attribute, upload the file and save attributes elsewhere
You can either store the data in the Realtime Database, or
You can store the data in Storage file metadata (assuming pairs)

Categories