Firebase app crash while uploading image - android

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());
}
});
}

Related

how to get an image path in firebaseStorage to firebaseDatabase

hi every one am making an app that use firebaseDatabase for Users info and firebaseStorage to save the image and i want to put the path of the image uploaded to firebaseStorage in firebaseDatabase under User info so i can display the image like profile pic so am using this to upload image and mainActivity to show the image . i do search for solution and got some but it didnt work or i didnt know how to make it work . am new at android
upload image
public String getExtension(Uri uri) {
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getMimeTypeFromExtension(contentResolver.getType(uri));
}
private void uploadImage() {
StorageReference reference = mStorage.child(System.currentTimeMillis()+"."+getExtension(imageUri));
uploadTask= reference.putFile(imageUri)
.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(AddImageActivity.this,"Image Uploaded",Toast.LENGTH_SHORT).show();
Intent ii = new Intent(AddImageActivity.this,MainActivity.class);
startActivity(ii);
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}
MainActvity
public class MainActivity extends AppCompatActivity {
ImageView profilePic ;
TextView nameProfile ;
DatabaseReference databaseReference ;
FirebaseUser fUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
profilePic=findViewById(R.id.imageProfile);
nameProfile = findViewById(R.id.nameProfile);
fUser=FirebaseAuth.getInstance().getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference("Users").child(fUser.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
nameProfile.setText(user.getName());
Glide.with(getApplicationContext()).load(user.getImageURL()).into(profilePic);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
that work for me
final StorageReference reference = mStorageReference.child(System.currentTimeMillis() + "." + getExtension(imageUri));
reference.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl()
.addOnSuccessListener(
new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String imageUrl = uri.toString();
}
}
);
}
});
public void uploadfile(){
if(uri!=null){
final StorageReference filereference=storageReference.child(System.currentTimeMillis()+"."+getFileExtension(uri));
filereference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
filereference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Upload upload=new Upload(editText1.getText().toString(),uri.toString());
String str=databaseReference.push().getKey();
databaseReference.child(str).setValue(upload);
progressBar.setVisibility(View.INVISIBLE);
progressBar2.setVisibility(View.VISIBLE);
final Timer timer=new Timer();
TimerTask timerTask=new TimerTask() {
#Override
public void run() {
counter++;
progressBar2.setProgress(counter);
if (counter==100){
toast.show();
progressBar2.setVisibility(View.INVISIBLE);
counter=0;
timer.cancel();
}
}
};timer.schedule(timerTask,1,15);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
else {
Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
}
}
Hello my friend please copy-paste your function like this
private void uploadImage() {
StorageReference reference = mStorage.child(System.currentTimeMillis()+"."+getExtension(imageUri));
uploadTask= reference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String uploadedImageUrl = uri.toString();
// Now you have your image in (uploadedImageUrl) variable so write your code to upload in firebaseDatabase and enjoy
}
});
Toast.makeText(AddImageActivity.this,"Image Uploaded",Toast.LENGTH_SHORT).show();
Intent ii = new Intent(AddImageActivity.this,MainActivity.class);
startActivity(ii);
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}

Why image upload failed in firebase storage? [duplicate]

This question already has answers here:
How to use getdownloadurl in recent versions?
(5 answers)
Closed 2 years ago.
An image can be chosen by clicking the 'CHOOSE IMAGE' button and it will be shown in an imageview
and will be uploaded to firebase storage after clicking 'SAVE IMAGE'.If it succeeds then data about that image will be uploaded to realtime firebase database. But nothing happens after clicking the 'SAVE IMAGE' button. What is the problem there?
These are my code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button chooseButton,saveButton,displayButton;
private EditText imagenameEdittext;
private ImageView imageView;
private ProgressBar progressBar;
private Uri imageUri;
private StorageReference storageReference;
private DatabaseReference databaseReference;
private StorageTask uploadTask;
private static final int IMAGE_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseReference = FirebaseDatabase.getInstance().getReference("Upload");
storageReference = FirebaseStorage.getInstance().getReference("Upload");
chooseButton = findViewById(R.id.chooseImageButtonid);
saveButton = findViewById(R.id.saveImageButtonid);
displayButton = findViewById(R.id.displayImageButtonid);
progressBar = findViewById(R.id.progressbarid);
imageView = findViewById(R.id.imageviewid);
imagenameEdittext = findViewById(R.id.imagenameEdittextid);
chooseButton.setOnClickListener(this);
saveButton.setOnClickListener(this);
displayButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.chooseImageButtonid:
openFileChooser();
break;
case R.id.saveImageButtonid:
if(uploadTask!=null && uploadTask.isInProgress()){
Toast.makeText(this, "Uploading in progress", Toast.LENGTH_SHORT).show();
}
else{
saveData();
}
saveData();
break;
case R.id.displayImageButtonid:
break;
}
}
public void openFileChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==IMAGE_REQUEST && resultCode==RESULT_OK && data!=null && data.getData()!=null){
imageUri = data.getData();
Picasso.get().load(imageUri).into(imageView);
}
}
public String getFileExtension(Uri imageUri){
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(imageUri));
}
private void saveData(){
final String imageName = imagenameEdittext.getText().toString().trim();
if(imageName.isEmpty()){
imagenameEdittext.setError("Enter the image name");
imagenameEdittext.requestFocus();
return;
}
StorageReference ref = storageReference.child(System.currentTimeMillis()+"."+getFileExtension(imageUri));
ref.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
Toast.makeText(MainActivity.this, "Image is stored Successfully", Toast.LENGTH_SHORT).show();
Upload upload = new Upload(imageName,taskSnapshot.getStorage().getDownloadUrl().toString());
String uploadId = databaseReference.push().getKey();
databaseReference.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
Toast.makeText(MainActivity.this, "Image store failed", Toast.LENGTH_SHORT).show();
}
});
}
}
please can u tell me if the imageuri is not null?
try to print imageuri in log to check if it is not null.

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.

Android uploading profile picture for a Firebase authenticated user

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 + "%");
}
});
}
}

firebase storage getting downloadURL problem

when i tried to get the download URL for my image in firebase storage I got something weird i got this result
com.google.android.gms.tasks.zzu#3a6d712
and here is my code
public class MainActivity extends AppCompatActivity {
private StorageReference mStorage;
private ProgressDialog mProgressDialog;
private static final int GALLERY_REQUEST_CODE = 1;
private static final int CAMERA_REQUEST_CODE = 2;
private Button uploadButton;
private Button captureButton;
ImageView imageViewBig, imageViewSmall;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
mProgressDialog = new ProgressDialog(this);
imageViewBig = findViewById(R.id.imageViewBig);
imageViewSmall = findViewById(R.id.imageViewSmall);
captureButton = findViewById(R.id.captureButton);
uploadButton = findViewById(R.id.uploadButton);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST_CODE && resultCode == RESULT_OK) {
Uri uri = data.getData();
StorageReference filePath = mStorage.child("photos").child(uri.getLastPathSegment());
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "DONE", Toast.LENGTH_SHORT).show();
imageViewBig.setBackgroundColor(Color.GREEN);
imageViewBig.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("URL", taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
}
});
}
});
}
}
}
so how to get the right download URL to download the image into image view using picasso
UploadTask
public class UploadTask extends StorageTask<UploadTask.TaskSnapshot>
An controllable task that uploads and fires events for success, progress and failure. It also allows pause and resume to control the upload operation.
Example
final StorageReference firebaseStorage = FirebaseStorage.getInstance().getReference();
StorageReference postPhotos = firebaseStorage.child("photos/");
final StorageReference upload_Image = postPhotos.child(uri.getLastPathSegment());
//uri = uri of your file which you want to update
UploadTask uploadTask = upload_Image.putFile(uri);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
upload_Image.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
//downloadable uri
Uri path = task.getResult();
}
}
});
}
});
Use this Code to upload File on firebase and get download url for that file
Uri file = Uri.fromFile(new File(aadhaarPath));
final StorageReference riversRef = storageRef.child("documents/" + file.getLastPathSegment());
uploadTask = riversRef.putFile(file);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
progressDialog.dismiss();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// get the image Url of the file uploaded
riversRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUrl = uri;
aadharDownloadUrl = downloadUrl.toString();
uploadPanCard(panCardPath);
}
});
}
});
aadhaarPath is file path that you selected to upload
and add this in your build .gradle
implementation 'com.google.firebase:firebase-storage:16.0.3'
I save photos to Firebase storage and the image name to Firebase realtime database and than i am using Glide to load images from Firebase Storage:
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference();
StorageReference imageRef = storageRef.child(PHOTO_NAME);
GlideApp.with(mContext).load(islandRef).into(viewHolder.image);

Categories

Resources