I have an app which allows the users to upload the images to a Firebase bucket,then I get the download URL of the image file and add it to a firebase database.The URL is in the form :- https://firebasestorage.googleapis.com/v0/b/bucket_name.appspot.com/o/filename?alt=media&token=token
Then I try to load the images into an RecyclerView using Glide but I am unable to do so and It fails to display the image.
How can I get an absolute Image URL which ends in .png or .jpeg etc which can be easily used to load the image.As far as I know the problem is with the url
To get Images form Camera
Intent i = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 3);
To get the filepath of an Image
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FILE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
String path=String.valueOf(data.getData());
file = Uri.fromFile(new File(path));
Create the file metadata
metadata = new StorageMetadata.Builder()
.setContentType("image/jpeg")
.build();
Upload file and metadata to the path 'images/avator.jpg'
uploadTask = storageRef.child("images/"+file.getLastPathSegment()).putFile(file, metadata);
Listen for state changes, errors, and completion of the upload.
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
System.out.println("Upload is " + progress + "% done");
}
}).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
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Handle successful uploads on complete
Uri downloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
}
});
To load the Image using Glide Library
Glide.with(getActivity())
.load(new File(downloadUrl)) // Uri of the picture
.into(Imageview);
With Picasso you can load a simple image using:
Picasso.with(Activity.this).load("your url image").into(imageView);
Need add in Glade:
compile 'com.squareup.picasso:picasso:2.5.2'
Related
I am trying to add an image to the user information in the real time database(firebase) for android. I have uploaded the image on the firebase storage but how will I be able to add the image in the database for that user?
Code Below:
//inside onCreate() method
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(i,request_code);
}
});
Here I am clicking on the imageview, so I will be able to change it and get an image from the gallery.
Here I authenticate the user and send data to the database:
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(StudentSignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(getApplicationContext(), "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(StudentSignUpActivity.this, HomeActivity.class));
finish();
}
}
});
mCurrentUser=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference newStudent=mDatabase.push();
newStudent.child("email").setValue(email);
newStudent.child("password").setValue(password);
newStudent.child("name").setValue(name);
newStudent.child("date").setValue(dates);
newStudent.child("phone").setValue(number);
newStudent.child("uid").setValue(mCurrentUser.getUid());
//outside of onCreate()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==request_code&&resultCode==RESULT_OK){
Uri uri=data.getData();
StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}
}
In the above code I have uploaded the image to the firebase storage. Now how will i be able to add that image as a child for a specific user.
I think I need to do something like this:
newStudent.child("image").setValue(uri_here);
But I am unable to figure how to get the uri of the image and how to add that uri in the setValue() since its in another method.
You can use the method getDownloadUrl() in the success listener to access the download URL:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==request_code&&resultCode==RESULT_OK){
Uri uri=data.getData();
StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
newStudent.child("image").setValue(downloadUrl);
}
});
}
}
As an aside, instead of using push(), I recommend storing the user's data with the uid as the key. This will make your data easier to find.
private DatabaseReference newStudent;
mCurrentUser=FirebaseAuth.getInstance().getCurrentUser();
newStudent=mDatabase.child(mCurrentUser.getUid());
newStudent.child("email").setValue(email);
// etc
Just to update because I spent sometime to find this answer, getDownloadUrl() is NOT a function of taskSnapshot anymore. So in order to get the image URL from Firebase Storage you need to add a listener to
taskSnapshot.getMetadata().getReference().getDownloadUrl()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==request_code&&resultCode==RESULT_OK){
Uri uri=data.getData();
StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getMetadata().getReference().getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
newStudent.child("image").setValue(uri);
}
});
}
});
}
}
Now it's safe to use uri to whatever you want
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("video/*");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
}
});
#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 a reference to store file at chat_photos/<FILENAME>
StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
// Upload file to Firebase Storage
photoRef.putFile(selectedImageUri)
.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
// progressBar.setVisibility(View.VISIBLE);
Uri downloadUrl = taskSnapshot.getDownloadUrl();
// Set the download URL to the message box, so that the user can send it to the database
Video video = new Video(downloadUrl.toString());
mMessagesDatabaseReference.push().setValue(video);
}
});
}
}
I want to show progress on seekbar when image is uploading as a notification. How do I do that? I have created an object of Seekbar in my onCreate. How to get duration of the video which I am uploading and show the seekbar in notification and the user should not be able to swipe notification when upload starts? Please help.
you can do that by using addOnProgressListener
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
int progress = (int) ((100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount());
try {
yourSeekBar.setProgress(progress);
} catch (Exception e) {
e.printStackTrace();
}
}
})
I have not use authentication yet, in the screen i can see the progress dialog working but its not getting stop. I think there is a problem.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==GALLERY_INTENT&&resultCode==RESULT_OK){
progressDialog.setMessage("Uploading Image...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filepath = mStorageRef;
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Uploading Finished",Toast.LENGTH_LONG).show();
}
});
}
}
//firebase storage rule
service firebase.storage {
match /b/csapplication-b6e5e.appspot.com/o {
match /{allPaths=**} {
allow read, write: if request.auth == null;
}
}
}
Its because of if your file upload to firebase was successful means your ProgressDialog will be dismissed ,if not in the case of failure you have to dismiss (ProgressDialog) in the OnFailure method in the code below .
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Uploading Finished",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads - Dismiss the ProgressDialog here
progressDialog.dismiss();
Toast.makeText(Profile.this, "Unable to Uploaded Error in Firebase",Toast.LENGTH_LONG).show();
}});
I created a simple application which crop the image . Now I want to save this image to the Fire base .
photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent imageDownload = new
Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent imageDownload=new Intent();
imageDownload.setAction(Intent.ACTION_GET_CONTENT);
imageDownload.setType("image/*");
imageDownload.putExtra("crop", "true");
imageDownload.putExtra("aspectX", 1);
imageDownload.putExtra("aspectY", 1);
imageDownload.putExtra("outputX", 200);
imageDownload.putExtra("outputY", 200);
imageDownload.putExtra("return-data", true);
startActivityForResult(imageDownload, GALLERY_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_REQUEST_CODE && resultCode == RESULT_OK &&
data != null) {
Bundle extras = data.getExtras();
image = extras.getParcelable("data");
photo.setImageBitmap(image);
}
}
How to save this image to the Firebase . I tried many tutorial but could not succeed . Please verify with simple code .
you must first add the dependencies for Firebase Storage to your build.gradle file:
compile 'com.google.firebase:firebase-storage:10.0.1'
compile 'com.google.firebase:firebase-auth:10.0.1'
then create an instance of FirebaseStorage:
FirebaseStorage storage = FirebaseStorage.getInstance();
To upload a file to Firebase Storage, you first create a reference to the full path of the file, including the file name.
// Create a storage reference from our app
StorageReference storageRef = storage.getReferenceFromUrl("gs://<your-bucket-name>");
// Create a reference to "mountains.jpg"
StorageReference mountainsRef = storageRef.child("mountains.jpg");
// Create a reference to 'images/mountains.jpg'
StorageReference mountainImagesRef = storageRef.child("images/mountains.jpg");
// While the file names are the same, the references point to different files
mountainsRef.getName().equals(mountainImagesRef.getName()); // true
mountainsRef.getPath().equals(mountainImagesRef.getPath()); // false
Once you've created an appropriate reference, you then call the putBytes(), putFile(), or putStream() method to upload the file to Firebase Storage.
The putBytes() method is the simplest way to upload a file to Firebase Storage. putBytes() takes a byte[] and returns an UploadTask that you can use to manage and monitor the status of the upload.
// 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();
}
});
Firebase does not support binary data, so you need to convert the image data to base64 or use Firebase Storage
Method 1 ( Recommended )
sref = FirebaseStorage.getInstance().getReference(); // please go to above link and setup firebase storage for android
public void uploadFile(Uri imagUri) {
if (imagUri != null) {
final StorageReference imageRef = sref.child("android/media") // folder path in firebase storage
.child(imagUri.getLastPathSegment());
photoRef.putFile(imagUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot snapshot) {
// Get the download URL
Uri downloadUri = snapshot.getMetadata().getDownloadUrl();
// use this download url with imageview for viewing & store this linke to firebase message data
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// show message on failure may be network/disk ?
}
});
}
}
Method 2
for small images we can still go with this solution, there is firebase field value
limitations(1MB field value)
check official doc for details
public void getImageData(Bitmap bmp) {
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bao); // bmp is bitmap from user image file
bmp.recycle();
byte[] byteArray = bao.toByteArray();
String imageB64 = Base64.encodeToString(byteArray, Base64.URL_SAFE);
// store & retrieve this string which is URL safe(can be used to store in FBDB) to firebase
// Use either Realtime Database or Firestore
}
"firebase-storage 16.0.1"
task.getDowloadUrl() not defined. You can use this i check , working perfectly.
private void firebaseUploadBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] data = stream.toByteArray();
StorageReference imageStorage = storage.getReference();
StorageReference imageRef = imageStorage.child("images/" + "imageName");
Task<Uri> urlTask = imageRef.putBytes(data).continueWithTask(task -> {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return imageRef.getDownloadUrl();
}).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
String uri = downloadUri.toString();
sendMessageWithFile(uri);
} else {
// Handle failures
// ...
}
progressBar.setVisibility(View.GONE);
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {
// Bitmap imageBitmap = data.getData() ;
Bitmap photo = (Bitmap) data.getExtras().get("data");
if (photo != null)
firebaseUploadBitmap(photo);
} else if (requestCode == SELECT_IMAGE && resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
if (uri != null)
firebaseUploadImage(uri);
}
}
Does Google's Firebase support video storage ? Am planning to upload video and want to download on-demand. I started with Firebase. Are there any other APIs or services that give a similar functionality ?
Of course you can upload video or any files on firebase.
btnupload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Intent.ACTION_GET_CONTENT);
myIntent.setType("*/*");
startActivityForResult(Intent.createChooser(myIntent,"Select File:-"),101);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode==RESULT_CANCELED)
{
// action cancelled
}
if(resultCode==RESULT_OK)
{
// Create a storage reference from our app
StorageReference storageRef = storage.getReferenceFromUrl("gs://<<Your App Bucket Address>>");
Uri uri = data.getData();
StorageReference riversRef = storageRef.child("files/"+uri.getLastPathSegment());
UploadTask uploadTask = riversRef.putFile(uri);
// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
Toast.makeText(MainActivity.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
}).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.
Toast.makeText(MainActivity.this, "Upload Success", Toast.LENGTH_SHORT).show();
}
});
}
}
Firebase has a Firebase Storage offering that allows you to store any arbitrary files.
It doesn't offer any video-specific features or functionality, but it will work if you simply want to have a place to store and retrieve your video files.