Get downloadUrl from firebase - android

I developed a code to upload an image to the firebase.
In consultation the firebase storage I found that the image is well uplode.
To retrieve the downloadUrl I used a Listener but it seems to me that the Listener does not work.
mFirebaseStorage = FirebaseStorage.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
mProductStorageReference = mFirebaseStorage.getReference().child("images");
mPostsDatabaseReference = mFirebaseDatabase.getReference().child("posts");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
File f = new File(imagePath);
bitmap = BitmapFactory.decodeFile(f.getPath());
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, bytes);
String path = MediaStore.Images.Media.insertImage(PostNewProductActivity.this.getContentResolver(),
bitmap, imagePath, null);
Uri uri = Uri.parse(path);
// Upload file to Firebase Storage
final String finalAdress = adress;
final double finalMyLat = MyLat;
final double finalMyLong = MyLong;
StorageReference photoRef = mProductStorageReference.child(uri.getLastPathSegment());
photoRef.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.i("tag", "onSuccess");
// When the image has successfully uploaded, we get its download URL
Uri downloadUrl = taskSnapshot.getDownloadUrl();
// Set the download URL to the message box, so that the user can send it to the database
Product product = new Product(userName, mLastUpdateTime, finalAdress, finalMyLat, finalMyLong,
descriptionUser.getText().toString(), descriptionApi, downloadUrl.toString(), price.getText().toString());
mPostsDatabaseReference.push().setValue(product);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
Log.i("tag", "onFailure");
}
});
I consulted the log I didn't find -onSuccess tag- and -onFailure tag-, although the photo is well in firebase

Related

Why is This code set up for FireStore uploading the data to the Realtime database when not referenced

I wanted to convert my code so that it would upload the data to the Firestore database since its better for what I need.
private void uploadData(final String titl, final String description) {
// show the progress dialog box
pd.setMessage("Publishing Post");
pd.show();
final String timestamp = String.valueOf(System.currentTimeMillis());
String filepathname = "Posts/" + "post" + timestamp;
Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] data = byteArrayOutputStream.toByteArray();
// initalising the storage reference for uploading the data
StorageReference storageReference1 = FirebaseStorage.getInstance().getReference().child(filepathname);
storageReference1.putBytes(data).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// getting the url of image uploaded
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) ;
String downloadUri = uriTask.getResult().toString();
if (uriTask.isSuccessful()) {
HashMap<Object, String> hashMap = new HashMap<>();
hashMap.put("uid", uid);
hashMap.put("uname", name);
hashMap.put("uemail", email);
hashMap.put("udp", dp);
hashMap.put("title", titl);
hashMap.put("description", description);
hashMap.put("uimage", downloadUri);
hashMap.put("ptime", timestamp);
hashMap.put("plike", "0");
hashMap.put("pcomments", "0");
FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
firebaseFirestore.collection("Posts").add(data)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
pd.dismiss();
Toast.makeText(PostBlogActivity.this, "Published", Toast.LENGTH_LONG).show();
title.setText("");
des.setText("");
image.setImageURI(null);
imageuri = null;
startActivity(new Intent(PostBlogActivity.this, DashboardActivity.class));
PostBlogActivity.this.finish();
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(PostBlogActivity.this, "Failed", Toast.LENGTH_LONG).show();
}
});
}
Honestly I don't know why its doing this since it has no reason to.
I also try doing it this way as well
private void uploadData(final String titl, final String description) {
// show the progress dialog box
pd.setMessage("Publishing Post");
pd.show();
final String timestamp = String.valueOf(System.currentTimeMillis());
String filepathname = "Posts/" + "post" + timestamp;
Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] data = byteArrayOutputStream.toByteArray();
// initalising the storage reference for uploading the data
StorageReference storageReference1 = FirebaseStorage.getInstance().getReference().child(filepathname);
storageReference1.putBytes(data).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// getting the url of image uploaded
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) ;
String downloadUri = uriTask.getResult().toString();
if (uriTask.isSuccessful()) {
HashMap<Object, String> hashMap = new HashMap<>();
hashMap.put("uid", uid);
hashMap.put("uname", name);
hashMap.put("uemail", email);
hashMap.put("udp", dp);
hashMap.put("title", titl);
hashMap.put("description", description);
hashMap.put("uimage", downloadUri);
hashMap.put("ptime", timestamp);
hashMap.put("plike", "0");
hashMap.put("pcomments", "0");
FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
firebaseFirestore.collection("Posts").document(timestamp).set(data)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
pd.dismiss();
Toast.makeText(PostBlogActivity.this, "Published", Toast.LENGTH_LONG).show();
title.setText("");
des.setText("");
image.setImageURI(null);
imageuri = null;
startActivity(new Intent(PostBlogActivity.this, DashboardActivity.class));
PostBlogActivity.this.finish();
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(PostBlogActivity.this, "Failed", Toast.LENGTH_LONG).show();
}
});
}
I've copied what the tutorial says inside of android studio however that doesn't work, I am using the free version right now however that shouldn't stop me from writing to the database. It gives no errors or warnings that what I have done is wrong so that it would upload to the Realtime database instead. I have read my code to see if I have referenced the Realtime database by mistake however that piece of code is all what accesses and writes to the database. Though if my code was wrong I would expect it to crash and not upload the data to another database.

Firebase: get getReferenceFromUrl()

imageView=(ImageView)findViewById(R.id.dd);
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://MyProject.appspot.com/");
storageRef.child("MyFolder/MyPict.jpg").getDownloadUrl().addOnSuccessListener(MainActivity.this, new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Glide.with(MainActivity.this).load(uri).into(imageView);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
But.. "Unfortunately YourApp has stoped" is displayed..
Can you help me please
I hope you give rules in firebase storage as reading and write true.
on button click used below method ..
private void uploadImage() {
// Start by getting our StorageReference
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference rootRef = storage.getReference();
StorageReference bearRef = rootRef.child("images/bear.jpg");
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading");
progressDialog.show();
// Get the data from the image as bytes
ImageView bearImage = getSelectedBearImage();
bearImage.setDrawingCacheEnabled(true);
bearImage.buildDrawingCache();
Bitmap bitmap = bearImage.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
// Upload it to our reference
UploadTask uploadTask = bearRef.putBytes(data);
buttonDownload.setEnabled(false);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
progressDialog.dismiss();
Log.w(LOG_TAG, "Upload failed: " + exception.getMessage());
}
}).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();
progressDialog.dismiss();
Log.d(LOG_TAG, "Download Url: " + downloadUrl);
buttonDownload.setEnabled(true);
}
});
}
and I hope you add internet permission on android manifest file...
<uses-permission android:name="android.permission.INTERNET"/>
for information you can refer this link..
More Information For Storage :
https://firebase.google.com/docs/storage/
For Upload & Download :
https://www.simplifiedcoding.net/firebase-storage-tutorial-android/
use storage.getStorage().getReferenceFromUrl("gs://MyProject.appspot.com/");

How to Get Image URL after uploading an image form android to Firebase?

I am making an App that user uploaded images on Firebase storage. After Uploading the image i want to upload the Images's URL and other details to my own API. How can i get the Uri of that image which the user just uploaded.
This tutorial teaches how to do the uploading but doesn't show how to get the image URL. I tried all the tutorials but none shows the thing that i want.
According to the documentation, you can call .getDownloadUrl in the .onSuccessListener to get the image URL.
Here is the example from the documentation:
// Get the data from an ImageView as bytes
imageView.setDrawingCacheEnabled(true);
imageView.buildDrawingCache();
Bitmap bitmap = imageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = mountainsRef.putBytes(data);
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();
}
});
You will get the download URL on the onSuccess callback. Check the following code
public static void storeInFirebase(Context context, Uri uri, String type) {
StorageReference riversRef = null;
mStorageRef = FirebaseStorage.getInstance().getReference();
//to create a separate folder with all the pictures uploaded
riversRef = mStorageRef.child("pictures/" + "unique_value");
UploadTask uploadTask = riversRef.putFile(uri);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
DialogUtils.dismissProgressDialog();
// 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.
downloadUrl = taskSnapshot.getDownloadUrl();
Log.d("downloadUrl", "" + downloadUrl);
}
});
}
imagename.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
insertDataFirebase_with_image(UID, String.valueOf(uri));
insertData_with__Image(UID, String.valueOf(uri));
}
});
//here imagename is the StoragePreference that lead to the image location
//nad insert data are function that i have used to store the image URL to my Realtime database

Firebase storage not working Android

I'am trying to update a photo on Firebase Storage.
Rules for Storage are public and all libraries are up to date.
For bucket I'm using the one from my firebase console.
Fatal Exception:
java.lang.IllegalArgumentException: The supplied bucketname is not
available to this project. at
com.moose.android.AddPostActivity.onClick(AddPostActivity.java:163)
Bitmap bitmap = imageBitmap;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
byte[] data = baos.toByteArray();
FirebaseStorage mFirebaseStorage = FirebaseStorage.getInstance();
***StorageReference mStorageRef = mFirebaseStorage.getReferenceFromUrl("gs://bucketname.appspot.com"); //line 163***
final StorageReference photoRef = mStorageRef.child("posts_images/mooseImg" + getCurrentDateTime() + ".jpg");
UploadTask uploadTask = photoRef.putBytes(data);
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();
Firebase createNewPost = new Firebase(FirebaseURL);
Firebase alanRef = createNewPost.push();
Map<String, Object> nickname = new HashMap<String, Object>();
nickname.put("createdAt", getCurrentDateTime());
nickname.put("imageURL", downloadUrl.toString());
/*nickname.put("latitude", 20.1814);
nickname.put("longitude", 72.1781);*/
nickname.put("latitude", prefs.getLatitude());
nickname.put("longitude", prefs.getLongitude());
nickname.put("objectId", alanRef.getKey());
nickname.put("ownerId", prefs.getUserUId());
nickname.put("postText", editTextNewPostMsg.getText().toString());
nickname.put("replies", 0);
nickname.put("reportCount", 0);
nickname.put("score", 0);
nickname.put("updatedAt", getCurrentDateTime());
alanRef.setValue(nickname, new Firebase.CompletionListener() {
#Override
public void onComplete(FirebaseError firebaseError, Firebase firebase) {
dismissProgressDialog();
Toast.makeText(getApplicationContext(), "your post have been added.", Toast.LENGTH_LONG).show();
finish();
}
});
// LogUtil.debug("StorageRef = " + mStorageRef);
}
});
It should be in your google-services.json file with tag "storage_bucket"
"project_info": {
"project_number": "816275527980",
"firebase_url": "https://project-8693710910123456789.firebaseio.com",
"project_id": "project-8693710910123456789",
"storage_bucket": "project-8693710910123456789.appspot.com"
},

retrieve firebase storage image and display it in the UI

I need some guidance on downloading an image from firebase and then displaying it on the UI. I believe from what i can find downloaded the file correctly and firebase notices that it has sent data. I cant for the life of me get it to display though. Any help is greatly appreciated.
mAuth = FirebaseAuth.getInstance();
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference jobRef = storage.getReferenceFromUrl("gs://********************.appspot.com/bd67a3b962538b24-0.jpg");
final File localFile = File.createTempFile("jobNumbers","png");
jobRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
// Local temp file has been created
StorageReference temp = taskSnapshot.getStorage();
Bitmap img = BitmapFactory.decodeFile(temp.getPath());
ImageView iv = (ImageView) findViewById(R.id.imageView);
iv.setImageBitmap(img);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});

Categories

Resources