i am trying to use firebase storage but i keep getting a fatal error when i upload and want to send it to my database. the upload is successful but i try to get the download url to my database and i get this error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.apps.ayodkay.services, PID: 10693
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)' on a null object reference
at com.apps.ayodkay.services.Profile$9.onComplete(Profile.java:550)
at com.google.android.gms.tasks.zzj.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5753)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
this is code i used from the documentation in firebase storage
if (mImageUri != null) {
Date date = new Date();
long time = date.getTime();
Uri file = Uri.fromFile(new File("path/to/images/" + time));
final StorageReference fileReference = mStorageRef.child("images/" + file.getLastPathSegment());
mUploadTask = fileReference.putFile(mImageUri);
// Register observers to listen for when the download is done or if it fails
mUploadTask.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, etc.
// ...
}
});
Task<Uri> urlTask = mUploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw Objects.requireNonNull(task.getException());
}
// Continue with the task to get the download URL
return fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
String uri = downloadUri.toString();
mUsernameDatabase.child("image").setValue(uri);
Toast.makeText(Profile.this, "upload Done", Toast.LENGTH_SHORT).show();
mprogress.setVisibility(View.GONE);
} else {
Toast.makeText(Profile.this, "Error uploaing", Toast.LENGTH_SHORT).show();
}
}
});
// [END upload_get_download_url]
}
i tried to use another method and it worked perfectly. i used the UserProfileChangeRequest method instend of send it to my database, i set a new user photo url
Task<Uri> urlTask = mUploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw Objects.requireNonNull(task.getException());
}
// Continue with the task to get the download URL
return fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
FirebaseUser user = mAuth.getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setPhotoUri(downloadUri)
.build();
user.updateProfile(profileUpdates).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(Profile.this, "upload Done", Toast.LENGTH_SHORT).show();
mprogress.setVisibility(View.GONE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
} else {
Toast.makeText(Profile.this, "Error uploaing", Toast.LENGTH_SHORT).show();
}
}
});
Related
Whenever I'm trying to upload a file to firebase storage, and then retrieve the download URL for it, I'm getting the same URL even when different files are uploaded. The files do get uploaded, but the URL received is similar for every upload
downloadURL = new Uri[1];
UploadTask uploadTask = mChatPhotosStorageReference
.child(selectedImageUri.getLastPathSegment())
.putFile(selectedImageUri);
Log.v("SelectedImage: ", selectedImageUri.getLastPathSegment());
uploadTask
.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful())
throw task.getException();
return mChatPhotosStorageReference.getDownloadUrl();
}
})
.addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
downloadURL[0] = task.getResult();
//passing downloadUri to database to store with chat messages
ShutUpMessages shutUpMessages = new ShutUpMessages(null, mUsername, downloadURL[0].toString());
mMessagesDatabaseReference.push().setValue(shutUpMessages);
mProgressbar.setVisibility(ProgressBar.INVISIBLE);
Toast.makeText(MainActivity.this, "File Uploaded", Toast.LENGTH_SHORT).show();
} else
Toast.makeText(MainActivity.this, "File Upload failed", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_SHORT).show();
mProgressbar.setVisibility(ProgressBar.INVISIBLE);
}
});
I am trying to upload and retrieve the image and follow all the results available at Stack and tutorials but none of example help me.
how to upload an image on button click in latest firebase storage
I am following this tutorial
https://www.simplifiedcoding.net/firebase-storage-example/
StorageReference reference= storageReference.child(System.currentTimeMillis()+ "."+getFileExtension(filePath));
mUploadTask= reference.putFile(filePath);
Task<Uri> urlTask = mUploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return storageReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
} else {
// Handle failures
// ...
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
});
You are doing it right to upload the image, after you return the storageReference.getDownloadUrl(), just set that value into your firebase database.
StorageReference reference= storageReference.child(System.currentTimeMillis()+ "."+getFileExtension(filePath));
mUploadTask= reference.putFile(filePath);
Task<Uri> urlTask = mUploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return storageReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
mDatabaseRef.child("images").child("imageUrl").setValue(downloadUri.toString());
} else {
// Handle failures
// ...
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
});
You will need to request that image url String from firebase and after that, to show the image in any ImageView use Picasso or Glide to load it.
This is my approach to upload an image file and getting the download link
UploadTask uploadTask = profileImageRef.putBytes(data);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String fileUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
Toast.makeText(UserProfile.this, "Uploaded Successfully!", Toast.LENGTH_SHORT).show();
}});
When I logged fileUrl it displays a String like this
com.google.android.gms.tasks.zzu#6ee8ba8
Someone please give me a solution to get the download url.
you can use this,
UploadTask uploadTask = profileImageRef.putBytes(data);
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return profileImageRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
} else {
// Handle failures
// ...
}
}
});
In my project, I am able to getDownloadUrl() after uploading a file
ref.putFile(imgUri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
if(task.getException() != null) {
throw task.getException();
}
}
return ref.getDownloadUrl();
}
}) ...
However, since I am resizing the image with a cloud function and re-uploading it to the bucket, the download url will change, so the only way to know the location of the image is through a StorageReference. How can I getDownloadUrl() from StorageReference? I've tried ref.getDownloadUrl().addOnSuccessListener which doesn't get fired and ref.getDownloadUrl().addOnCompleteListener and the task.getResult() throws an error.
Try using this :
I was trying to store images
You can get the download URL from task.getResult().toString()
final StorageReference ref = FirebaseStorage.getInstance().getReference().child("images").child(imageName)
uploadTask = ref.putBytes(data);
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
String URL = task.getResult().toString();
} else {
// Handle failures
// ...
}
}
});
This is my code to upload image to firebase storage. it works well. but I cannot get download url after upload
ref.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
URL url = taskSnapshot.getDownloadUrl()
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
});
In firebase 'com.google.firebase:firebase-storage:16.0.1', it cannot resolve getDownloadUrl().
Try this implementation. Use continueWithTask to get the downloaded url.
final UploadTask uploadTask = filepath.putFile(uri);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return filepath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
thumb_download_url = task.getResult().toString();
}
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
Task<Uri> urlTask = ref.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
// Downloadable uri
} else {
// Handle failures
}
}
});