Android uploading profile picture for a Firebase authenticated user - android

I'm trying to add an image to the Firebase storage, where each user can upload his profile picture from his files or camera, and it should be stored in his own folder that has his uid as name. I have the following code, however pressing on the ImageView doesn't do anything:
public class ProfileFragment extends Fragment {
CircleImageView profileImage;
TextView email;
public StorageReference storageRef;
FirebaseStorage storage;
public static ProfileFragment newInstance() {
ProfileFragment profileFragment = new ProfileFragment();
return profileFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container, false);
profileImage = view.findViewById(R.id.profile_image);
email = view.findViewById(R.id.email);
String user = FirebaseAuth.getInstance().getCurrentUser().getEmail();
email.setText(user);
storageRef = storage.getReference();
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
final String userUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
final Uri contentURI = data.getData();
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(contentURI != null) {
StorageReference childRef = storageRef.child("/images/"+ userUid +".jpg");
UploadTask uploadTask = childRef.putFile(contentURI);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getActivity(), "Upload successful", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), "Upload Failed" + e, Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(getActivity(), "Select an image", Toast.LENGTH_SHORT).show();
}
}
});
}
}
From what I've read, onActivityResult doesn't work with fragments, however I can't think or find any topics of how it should be done to work. Could somebody please help me with making this work, and also, how do I fetch the profile picture of each user after I've uploaded it? I'm using the built in Firebase Authentication system with Email, Google and Facebook authentication, and I'm trying to make it work without storing users additionally in the database.
Thanks in advance!

Try this below snippet :
Step 1:- Add the firebase storage dependency in build.gradle (Module:app)file. Latest Dependency for firebase storage is:
implementation 'com.google.firebase:firebase-storage:19.1.0'
Step 2:-Setting up the activity_main.xml layout file
Step 3:-Setting up the MainActivity.java file
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageReference = storage.getReference();
private void uploadImage()
{
if (filePath != null) {
// Code for showing progressDialog while uploading
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
// Defining the child of storageReference
StorageReferenceref=storageReference.child("images/"+UUID.randomUUID().toString();
// adding listeners on upload
// or failure of image
ref.putFile(filePath)
.addOnSuccessListener(
new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(
UploadTask.TaskSnapshot taskSnapshot)
{
// Image uploaded successfully
// Dismiss dialog
progressDialog.dismiss();
Toast
.makeText(MainActivity.this,
"Image Uploaded!!",
Toast.LENGTH_SHORT)
.show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e)
{
// Error, Image not uploaded
progressDialog.dismiss();
Toast
.makeText(MainActivity.this,
"Failed " + e.getMessage(),
Toast.LENGTH_SHORT)
.show();
}
})
.addOnProgressListener(
new OnProgressListener<UploadTask.TaskSnapshot>() {
// Progress Listener for loading
// percentage on the dialog box
#Override
public void onProgress(
UploadTask.TaskSnapshot taskSnapshot)
{
double progress
= (100.0
* taskSnapshot.getBytesTransferred()
/ taskSnapshot.getTotalByteCount());
progressDialog.setMessage(
"Uploaded "
+ (int)progress + "%");
}
});
}
}

Related

How do I set download URL for an image to firestore database and realtime Database

I have implemented the code to upload the user photo to storage and retrieve it to the firestore and realtimeDB. the problem is when I set the imageuri to database :
then I'm (or user) updating a photo to firebase, the URI is successfully updated to the profile string..(firestore) and image srting (realtimeDB). but after some time/after the app closes, the photo not loading properly.(or its gone), it didn't use the firebase token as the download Uri.
its like this :
content://com.android.providers.media.documents/document/image%3A81399
then I attached another code to get the updated image URL from storage. But another problem
for now, Both Databases didn't store the URLs
I have attached the code below.
public class ProfileFragment extends Fragment {
public ProfileFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
CircleImageView profileImageView;
FragmentProfileBinding binding;
private Uri photoUri;
private String imageUrl;
FirebaseFirestore firestore;
FirebaseStorage storage;
FirebaseAuth auth;
StorageReference storageReference;
DocumentReference documentReference;
DatabaseReference DBreference;
String currentUserId;
User user; //class
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = FragmentProfileBinding.inflate(inflater, container, false);
firestore = FirebaseFirestore.getInstance();
auth = FirebaseAuth.getInstance();
storage = FirebaseStorage.getInstance();
auth = FirebaseAuth.getInstance();
FirebaseUser fUser = FirebaseAuth.getInstance().getCurrentUser();
currentUserId = fUser.getUid();
documentReference = firestore.collection("Users").document(currentUserId);
storageReference = FirebaseStorage.getInstance().getReference().child("Profile Pictures");
DBreference = FirebaseDatabase.getInstance().getReference().child("Users");
update = binding.updateBtn;
profileImageView= binding.profilePhoto;
clickListener();
return binding.getRoot();
}
private void clickListener() {
profileImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
//noinspection deprecation
startActivityForResult(intent, 3);
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog.show();
StorageReference reference = storage.getReference().child("Profile Pictures")
.child(FirebaseAuth.getInstance().getUid());
reference.putFile(photoUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
imageUrl = uri.toString();
updateUserProfileToFirestore();
updateUserProfileToDataBase();
}
});
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull #NotNull UploadTask.TaskSnapshot snapshot) {
long totalSi = snapshot.getTotalByteCount();
long transferS = snapshot.getBytesTransferred();
long totalSize = (totalSi / 1024);
long transferSize = transferS / 1024;
progressDialog.setMessage("Uploaded " + ((int) transferSize) + "KB / " + ((int) totalSize) + "KB");
}
});
}
});
}
#SuppressWarnings("deprecation")
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (data.getData() != null) {
photoUri = data.getData();
// profileImageView.setImageURI(imageUri);
}
Toast.makeText(getContext(), "Photo selected!", Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(getContext(), "Error"+e, Toast.LENGTH_SHORT).show();
}
}
private void updateUserProfileToFirestore() {
Map<String, Object> profile = new HashMap<>();
profile.put("profile", imageUrl);
final DocumentReference sDoc = firestore.collection("Users").document(FirebaseAuth.getInstance().getUid());
firestore.runTransaction(new Transaction.Function<Void>() {
#Override
public Void apply(#NonNull Transaction transaction) throws FirebaseFirestoreException {
DocumentSnapshot snapshot = transaction.get(sDoc);
transaction.update(sDoc, profile);
// transaction.update(sDoc, "name", binding.nameBox.getText() );
return null;
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
progressDialog.setMessage("updated!");
progressDialog.dismiss();
Toast.makeText(getContext(), "Photo Updated!", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.setMessage("Can't upload");
progressDialog.dismiss();
Toast.makeText(getContext(), "Failed to update, try again later", Toast.LENGTH_SHORT).show();
}
});
// final DatabaseReference
}
// Realtime database
private void updateUserProfileToDataBase() {
HashMap<String, Object> map = new HashMap<>();
map.put("image", imageUrl);
DBreference.child(FirebaseAuth.getInstance().getUid())
.updateChildren(map)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
progressDialog.dismiss();
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull #NotNull Exception e) {
Toast.makeText(getContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}
Solved! It's based on the storage reference. just changed to "reference".
because I already declared the storage reference. but I entered it twice

i want to upload video to the firebase storage inside a folder with unique names?

I want to upload video to the firebase storage inside a folder with unique names.
What i am doing current in my code is, i am trying to record a video and i want to upload it to the firebase storage.
Please review my code and help me with an appropriate answer
public class MainActivity extends AppCompatActivity {
private Uri videouri;
Button button;
private StorageReference videoRef;
private DatabaseReference ref;
private static final int REQUEST_CODE = 101;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoRef= FirebaseStorage.getInstance().getReference("videos");
ref = FirebaseDatabase.getInstance().getReference("videos");
VideoView videoView=findViewById(R.id.videoView);
button=findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
upload();
Double abc=Math.random();
Log.i("info", "onCreate: "+abc);
String filename="video";
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
videoRef =storageRef.child("/videos"+"/"+videouri+".mp4");
}
});
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
public void upload() {
if (videouri != null) {
final UploadTask uploadTask = videoRef.putFile(videouri);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Success on upload", Toast.LENGTH_SHORT).show();
}
});
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
updateProgress(taskSnapshot);
}
});
} else {
Toast.makeText(this, "Nothing to Upload", Toast.LENGTH_SHORT).show();
}
}
public void updateProgress(UploadTask.TaskSnapshot taskSnapshot) {
long fileSize = taskSnapshot.getTotalByteCount();
long UploadBytes = taskSnapshot.getBytesTransferred();
long progress = (100 * UploadBytes) / fileSize;
ProgressBar progressBar = (ProgressBar) findViewById(R.id.pbar);
progressBar.setProgress((int) progress);
}
public void record(View view) {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intent, REQUEST_CODE);
}
protected void onActivityResult(int requestCode,int resultCode,Intent data){
super.onActivityResult(requestCode, resultCode, data);
videouri=data.getData();
if(resultCode==1){
Toast.makeText(this, "Video saved to:\n"+videouri, Toast.LENGTH_LONG).show();
}else if(resultCode==RESULT_CANCELED){
Toast.makeText(this, "RECORDING CANCELLED.", Toast.LENGTH_SHORT).show();
}else{
// Toast.makeText(this, "failed to record", Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Video saved to:\n"+videouri, Toast.LENGTH_LONG).show();
}
}
}
You're setting the videoRef after you start to upload the video, which means the value is never user.
The simplest way to fix it is with something like this:
public void upload() {
if (videouri != null) {
String filename = UUID.randomUUID().toString;
videoRef = FirebaseStorage.getInstance().getReference("videos")
.child("videos").child(filename+".mp4");
final UploadTask uploadTask = videoRef.putFile(videouri);
uploadTask.addOnFailureListener(new OnFailureListener() {
...
The above will generate a unique filename every time you upload a file.
An alternative for the file name can be to base it on the current timestamp:
String filename = System.currentTimeMillis().toString;
This typically makes it easier to find new files, as they'll be at the bottom of the list. It has a small chance of not being unique, but it's not very likely in early stages.
Another alternative for the file name is to base it on the file that was selected. But in that case, uploading the same source file will end up overwriting the data on the same location on the server.

error saying "have you declared this activity" when i try ti retrieve the images from firebase

I'm making a portfolio app that stores images on firebase with navigation drawer, and when i cleck my TextView which should open get the image on firebase itcrash and says this "Unable to find explicit activity class {com.example.johan.johansteve/com.example.johan.johansteve.ImageActivity}; have you declared this activity in your AndroidManifest.xml?"
private Uri mImageUri;
//get the image and use it to upload to the database
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
private StorageTask mUploadTask;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_portfolio, container,false);
mButtonChooseImage = v.findViewById(R.id.buttonChooseImage);
mButtonUpload = v.findViewById(R.id.uploadButton);
mTextViewShowUploads = v.findViewById(R.id.Text_View_uploads);
mEditTextFileName = v.findViewById(R.id.edit_text_file_name);
mImageView = v.findViewById(R.id.imageViewAction);
mProgressBar = v.findViewById(R.id.progress_Bar);
mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
//setOnClickListener method used to put actions into our views
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
//method made to choose the type of file
}
});
mButtonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mUploadTask != null && mUploadTask.isInProgress()){
Toast.makeText(getContext(),"upload in progress", Toast.LENGTH_SHORT).show();
}else {
uploadFile();
}
}
});
mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openImagesActivity();
}
});
return v;
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*"); // declaration of the type of file to be selected
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST); //used it for identify the type of dta we are retrieving
}
// method called when the file is selected
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
//process of image selecting using comparation
mImageUri = data.getData(); //used to upload in fireBase
Picasso.get().load(mImageUri).into(mImageView);
//mImageView.setImageURI(mImageUri); native way without picasso
}
}
private String getFileExtension(Uri uri){
ContentResolver cR = getContext().getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
//this method is only used to get extension from our file eg.jpg
}
private void uploadFile(){
if (mImageUri != null){
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
private static final String TAG ="ImagesActivity ";
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
},500);
//delays the progress bar to 5 seconds so teh user gets a visual feedback
Toast.makeText(getActivity(), "Upload Successful",Toast.LENGTH_LONG).show();
/**
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
taskSnapshot.getStorage().getDownloadUrl().toString());
**/
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
Log.d(TAG, "onSuccess: fireBase download url: " + downloadUrl.toString());
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),downloadUrl.toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
//create a new entry with contents the meter data of our uploads
//recycler view will use these entries to get the data from there
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgressBar.setProgress((int) progress);
}
});
}else{
Toast.makeText(getContext(),"No File Selected",Toast.LENGTH_SHORT).show();
}
}
private void openImagesActivity(){
Intent intent = new Intent(getActivity(),ImageActivity.class);
startActivity(intent);
}}
Just add ImageActivity to AndroidManifest.xml
<application
<activity android:name="com.example.johan.johansteve.ImageActivity"/>
</application>

FireBase Storage Image Upload Android

I have created an app running with Firebase Storage. The idea is that you select an Image from your Photo Gallery and then Upload it to Firebase Storage. The connection with Firebase seems to work fine, I can select an Image. The problem arises when I push the Submit Button to upload it to Firebase.
When I click it one time, nothing happens.
When I click it a few times, I get the message "an unknown error occurred, please check the HTTP result code and inner exception"..
What should I do, looking for advice..
From the Manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
From the Activity:
public class PostActivity extends AppCompatActivity {
private static final int GALLERY_REQUEST = 2;
private Uri uri = null;
private ImageButton imageButton;
private EditText editName;
private EditText editDescription;
private StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
//reference the two edittext Views, initialize them
editName = (EditText) findViewById(R.id.editName);
editDescription = (EditText) findViewById(R.id.editDescription);
//add the reference to the storagereference, initialize it
storageReference = FirebaseStorage.getInstance().getReference();
}
public void ImageButtonClicked (View view){
Intent galleryintent = new Intent (Intent.ACTION_GET_CONTENT);
galleryintent.setType("Image/*");
startActivityForResult(galleryintent, GALLERY_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
uri = data.getData();
imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setImageURI(uri);
}
}
public void submitButtonClicked (View view){
String titleValue = editName.getText().toString().trim();
String titleDescription = editDescription.getText().toString().trim();
if (!TextUtils.isEmpty(titleValue) && !TextUtils.isEmpty(titleDescription)){
StorageReference filePath = storageReference.child("PostImage").child(uri.getLastPathSegment());
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadurl = taskSnapshot.getDownloadUrl();
Toast.makeText(PostActivity.this,"uploadcomplete",Toast.LENGTH_LONG).show();
}
});
filePath.putFile(uri).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
Try this method for image upload to firebase storage:
private void uploadMethod() {
progressDialog();
FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
StorageReference storageReferenceProfilePic = firebaseStorage.getReference();
StorageReference imageRef = storageReferenceProfilePic.child("Your Path" + "/" + "Image Name" + ".jpg");
imageRef.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//if the upload is successful
//hiding the progress dialog
//and displaying a success toast
dismissDialog();
String profilePicUrl = taskSnapshot.getDownloadUrl().toString();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
//if the upload is not successful
//hiding the progress dialog
dismissDialog();
//and displaying error message
Toast.makeText(getActivity(), exception.getCause().getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
//calculating progress percentage
// double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
// //displaying percentage in progress dialog
// progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
}
I have found an answer through the code of Rahul Chandrabhan.
What I have changed is to remove the last part of the following method:
StorageReference filePath =
storageReference.child("PostImage").child(uri.getLastPathSegment());
TO
StorageReference filePath = storageReference.child("PostImage");
To perform image upload on firebase use below method:
void uploadFile(String pathToFile, String fileName, String serverFolder, String contentType) {
if (pathToFile != null && !pathToFile.isEmpty()) {
File file = new File(pathToFile);
if (file.exists()) {
Uri uri = Uri.fromFile(new File(pathToFile));
// Create a storage reference from our app
mStorageRef = mFirebaseStorage.getReference();
// Create a reference to "mountains.jpg"
//StorageReference mountainsRef = storageRef.child(fileName);
// Create a reference to 'images/mountains.jpg'
StorageReference mountainImagesRef = mStorageRef.child(serverFolder+"/" + fileName);
StorageMetadata metadata = null;
if (contentType != null && !contentType.isEmpty()) {
// Create file metadata including the content type
metadata = new StorageMetadata.Builder()
.setContentType(contentType)
.build();
}
if (metadata != null) {
uploadFileTask = mountainImagesRef.putFile(uri, metadata);
} else {
uploadFileTask = mountainImagesRef.putFile(uri);
}
uploadFileTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
hideProgressDialog();
exception.printStackTrace();
Log.e(TAG,exception.getMessage());
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadFailure(exception.getMessage());
}
}
});
uploadFileTask.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.
hideProgressDialog();
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Log.e(TAG, "Upload is success "+ downloadUrl);
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadSuccess("Upload is success "+ downloadUrl.toString(), downloadUrl.toString());
}
}
});
// Observe state change events such as progress, pause, and resume
uploadFileTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
hideProgressDialog();
double progressPercent = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
progressPercent = Double.parseDouble(FirebaseUtil.formatDecimal(progressPercent,2));
Log.e(TAG, "File Upload is " + progressPercent + "% done");
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadProgress(progressPercent);
}
}
});
uploadFileTask.addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
#Override
public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
hideProgressDialog();
Log.e(TAG, "Upload is paused");
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadPaused("Upload is paused");
}
}
});
}
else
{
hideProgressDialog();
Log.e(TAG, "Upload file does not exists");
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadFailure("Upload file does not exists");
}
}
}else
{
hideProgressDialog();
Log.e(TAG,"pathToFile cannot be null or empty");
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadFailure("pathToFile cannot be null or empty");
}
}
}
Make a call this method as below:
public void uploadDummyPicture(String email, String imagePath){
if (imagePath == null) {
return;
}
if (!isValidEmail(email)) {
return;
}
String serverFolder = "dummy_images/" + email; //path of your choice on firebase storage server
String fileName = "DummyPhoto.png";
uploadFile(imagePath, fileName, serverFolder, "image/png");
showProgressDialog();
}
Make sure to check the firebase storage rules before using above code as explained here. If the rules have firebase authentication required, then first complete firebase authentication of the current user and then start uploading the file.
I hope this answer will you solve your problem.
In my case, the URI which I was fetching on the onActivityResult function was just not in the right format.
Previously I was parsing like this
uri=Uri.parse(your image path)
but after changing to this it worked
uri=Uri.fromFile(new File(your image path))
the upload function
public void upload()
{
if(uri!=null)
{
progressBar.setVisibility(View.VISIBLE);
progressBar_tv.setVisibility(View.VISIBLE);
Log.i("URI",uri.getPath());
UploadTask uploadTask=sRef.putFile(uri);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(VideoEditAndUploadActivity.this, "Upload Failed:"+e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
e.printStackTrace();;
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(VideoEditAndUploadActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
progressBar_tv.setVisibility(View.INVISIBLE);
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
updateUploadProgress(snapshot);
}
});
}
else{
Toast.makeText(this, "Video Uri is null: please choose a video first!", Toast.LENGTH_SHORT).show();
}
}
the update progress bar function
#SuppressLint("DefaultLocale")
private void updateUploadProgress(UploadTask.TaskSnapshot snapshot) {
long fileSize=snapshot.getTotalByteCount();
long uploadBytes=snapshot.getBytesTransferred();
long progress=(100*uploadBytes)/fileSize;
progressBar.setProgress((int) progress);
progressBar_tv.setText(String.format("%d%%", progress));
}
If you are using rxjava then you could use the following snippet
public Observable<FirebaseFile> uploadImageToFirebase(#NonNull Uri file) {
return Observable.create(emitter -> {
try {
final StorageReference conversationReference = reference.child("some-identifier");
final File localFile = new File(file.getPath());
final StorageReference fileReference = conversationReference
.child(UUID.randomUUID().toString().toLowerCase(Locale.ROOT) + "-" + localFile.getName());
final UploadTask uploadTask = fileReference.putFile(file);
uploadTask.continueWithTask(task -> {
if (task.isSuccessful()) {
return fileReference.getDownloadUrl();
} else {
if (task.getException() != null) {
throw task.getException();
} else {
throw new RuntimeException("Error uploading file to firebase storage");
}
}
}).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
final Uri downloadUri = task.getResult();
if (downloadUri != null) {
emitter.onNext(new FirebaseFile(file.getPath(), downloadUri.toString(), 100));
emitter.onComplete();
} else {
if (!emitter.isDisposed()) {
emitter.onError(new RuntimeException("Error uploading stream to firebase storage"));
}
}
} else {
if (!emitter.isDisposed()) {
emitter.onError(new RuntimeException("Error uploading file to firebase storage"));
}
}
});
uploadTask.addOnProgressListener(taskSnapshot -> {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
emitter.onNext(new FirebaseFile(file.getPath(), null, (int) progress));
});
} catch (Exception e) {
if (!emitter.isDisposed()) {
emitter.onError(e);
}
}
});
}
Where
FirebaseStorage fs = FirebaseStorage.getInstance()
and
StorageReference StorageReference = firebaseStorage.getReference("some-identifier-if-any");```

Firebase app crash while uploading image

My app needs to upload image to firebase storage and display it in a recyclerView. My first two images displays well on the list. But, as I try to upload the third image, the app crashes and also can't store the image on firebase. Each image size varies from 500KB to 700KB. I also have used android:largeHeap="true" in my manifest. What to do?
//Here's the code:
public class PostActivity extends Activity {
private EditText postTitle;
private EditText postDescription;
private Button submitButton;
private Uri imageUri=null;
private StorageReference storage;
private ProgressDialog progressDialogue;
private DatabaseReference database;
public String titleVal;
public String descriptionVal;
private ImageView mImageView;
private static final int GALLERY_REQUEST=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
storage= FirebaseStorage.getInstance().getReference();
database= FirebaseDatabase.getInstance().getReference().child("Posts");
mImageView=(ImageView) findViewById(R.id.imageView);
postTitle=(EditText) findViewById(R.id.titleField);
postDescription=(EditText)findViewById(R.id.descriptionField);
submitButton=(Button) findViewById(R.id.submitPost);
progressDialogue=new ProgressDialog(this);
imageUri = Uri.parse(getIntent().getStringExtra("imageUri"));
ImageView img = (ImageView) findViewById(R.id.imageView);
img.setImageURI(imageUri);
//What happens after post is SUBMITED.
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startPosting();
}
});
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("titleVal", titleVal);
outState.putString("descriptionVal",descriptionVal );
}
private void startPosting() {
titleVal=postTitle.getText().toString().trim();
descriptionVal=postDescription.getText().toString().trim();
if(!TextUtils.isEmpty(titleVal) && !TextUtils.isEmpty(descriptionVal) && imageUri!=null){
progressDialogue.setMessage("আপলোড হচ্ছে......");
progressDialogue.show();
StorageReference filePath=storage.child("post_images").child(imageUri.getLastPathSegment());
filePath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl=taskSnapshot.getDownloadUrl();
Picasso.with(PostActivity.this).load(downloadUrl).into(mImageView);
DatabaseReference newPost=database.push();
newPost.child("title").setValue(titleVal);
newPost.child("description").setValue(descriptionVal);
newPost.child("image").setValue(downloadUrl.toString());
progressDialogue.dismiss();
Toast.makeText(getApplicationContext(), "Successfully Uploaded", Toast.LENGTH_LONG).show();
startActivity(new Intent(PostActivity.this,HomeActivity.class));
}
});
}else{
Toast.makeText(getApplicationContext(), "Please provide a Title", Toast.LENGTH_LONG).show();
}
}
}
try below code, I am using this code to upload image to firebase storage and let me know if you find any issue or have any queries
See below image , you can see image has been uploaded successfully
1 - In your Java file, put these code
private SimpleDraweeView imgProfile;
private FirebaseStorage storage;
private Uri file, resultUri;
private StorageMetadata metadata;
private UploadTask uploadTask;
private StorageReference storageRef;
private final String MY_BUCKET_PATH = "YOUR BUCKET PATH OF YOUR STORAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
storage = FirebaseStorage.getInstance();
storageRef = storage.getReferenceFromUrl(MY_BUCKET_PATH);
}
2 - After getting Uri of your image in onActivityResult upload image to firebase storage, also make sure you are getting proper image Uri
private void UploadImage() {
file = Uri.fromFile(new File(resultUri.getPath()));
// Create the file metadata
metadata = new StorageMetadata.Builder().setContentType("image/jpg").build();
// Upload file and metadata to the path 'images/mountains.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();
showUploadProgress(progress);
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) {
Log.e("Uploading image==", "onSuccess");
// Handle successful uploads on complete
Uri downloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
imgProfile.setImageURI(Uri.parse(downloadUrl.toString())); // Here image will be reflected after uploading
mDialog.dismiss();
Log.e("DownloadUrl getPath==>>", taskSnapshot.getDownloadUrl().getPath());
Log.e("Metadata getPath==>>", taskSnapshot.getMetadata().getPath()); // this line will give you path to download Image from Firebase storage omitting child storage reference
Log.e("Metadata dwndUrl getpath", taskSnapshot.getMetadata().getDownloadUrl().getPath());
Log.e("storageRef path==>>", taskSnapshot.getMetadata().getReference().getPath());
mSessionManager.storeStringValues("profile_photo", downloadUrl.toString());
mSessionManager.storeStringValues("profile_photo_path", taskSnapshot.getMetadata().getPath());
}
});
}

Categories

Resources