How to upload an image file to firebase firestore? - android

This is my UploadActivity. The app lets me select a file , but crashes as soon as I press upload button. the Toast message of OnFailedListener is displayed everytime.
I am choosing the correctimage file with correct naming conventions , but still facing the same problem.
I have reffered to the documentation as well as tutorials , and implemented almost the same methods.
What am I doing wrong?
public class UploadActivity extends AppCompatActivity {
Button selectfile,upload;
TextView notify;
Uri imguri;
ProgressDialog progressDialog;
FirebaseStorage storage;
FirebaseDatabase database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
storage = FirebaseStorage.getInstance();
database = FirebaseDatabase.getInstance();
selectfile = findViewById(R.id.SelectFile);
upload = findViewById(R.id.UploadFile);
notify = findViewById(R.id.notify);
selectfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ContextCompat.checkSelfPermission(UploadActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED){
selectPDF();
}
else{
ActivityCompat.requestPermissions(UploadActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},9);
}
}
});
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(imguri!=null){
uploadFile(imguri);
}
else{
Toast.makeText(UploadActivity.this, "Please Select a File", Toast.LENGTH_SHORT).show();
}
}
});
}
private void uploadFile(Uri imguri) {
final String filename = System.currentTimeMillis()+"";
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setTitle("Uploading File... ");
progressDialog.setProgress(0);
progressDialog.show();
StorageReference storageReference = storage.getReference();
storageReference.child("Uploads").child(filename).putFile(imguri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> task = taskSnapshot.getMetadata().getReference().getDownloadUrl();
task.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = uri.toString();
DatabaseReference databaseReference = database.getReference();
databaseReference.child(filename).setValue(url).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(UploadActivity.this, "Successfully Uploaded", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(UploadActivity.this, "Please Try Again", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UploadActivity.this, "File was not uploaded, please try again!", Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
int currentProgress = (int) (100*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setProgress(currentProgress);
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode==9 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
selectPDF();
}
else{
Toast.makeText(this, "Please Provide External Storage Permission", Toast.LENGTH_LONG).show();
}
}
private void selectPDF() {
Intent intent = new Intent();
intent.setType("images/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,86);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 86 && resultCode == RESULT_OK && data != null) {
imguri = data.getData();
notify.setText("File Selected : "+ data.getData().getLastPathSegment());
} else {
Toast.makeText(this, "Please Select a file", Toast.LENGTH_SHORT).show();
}
}
}

In build.gradle(module:app) , use the latest version for com.google.firebase:firebase-storage . Thanks Again #AlexMamo.

Related

adding profileimage node to firebase realtime database

I'm so new in coding and now I'm trying to write a socialnetwork app but i faced an error and I couldn't find any answer for that.
I could save my profile picture to firebase storage successfully but it I have to connect it to database so that I can use it later.
here is my code:
public class SetUpActivity extends AppCompatActivity
{
private EditText UserName, FullName , CountryName;
private Button SaveInfoButton;
private CircleImageView UserProfileImage;
private ProgressDialog loadingBar;
private FirebaseAuth mAuth;
private DatabaseReference UserRef;
private StorageReference UserProfileImageRef;
String currentUserID;
final static int Gallery_Pick = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_up);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("profile Image");
//storing profile image
UserName = (EditText) findViewById(R.id.setup_user_name);
FullName = (EditText) findViewById(R.id.setup_user_full_name);
CountryName = (EditText) findViewById(R.id.setup_user_country);
SaveInfoButton = (Button) findViewById(R.id.setup_information_button);
UserProfileImage = (CircleImageView) findViewById(R.id.set_up_profile_image);
loadingBar = new ProgressDialog( this);
SaveInfoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
SaveAccountSetupInformation();
}
});
UserProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,Gallery_Pick);
}
});
UserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot)
{
if(snapshot.exists()) {
if (snapshot.hasChild("profileimage"))
{
String image = snapshot.child("profileimage").getValue().toString();
Picasso.get().load(image).placeholder(R.drawable.profile).into(UserProfileImage);
}
else
{
Toast.makeText(SetUpActivity.this, "Plese Select Profile Image First...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// some conditions for the picture
if(requestCode==Gallery_Pick && resultCode==RESULT_OK && data!=null)
{
Uri ImageUri = data.getData();
// crop the image
CropImage.activity(ImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
// Get the cropped image
if(requestCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{ // store the cropped image into result
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK)
{
loadingBar.setTitle("Profile Image");
loadingBar.setMessage("Please wait, while we updating your profile image...");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
Uri resultUri = result.getUri();
final StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
//StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
UserRef.child("profileimage").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(SetUpActivity.this, "Image Stored", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else {
String message = task.getException().getMessage();
Toast.makeText(SetUpActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
});
}
});
}
else
{
Toast.makeText(this, "Error Occured: Image can not be cropped. Try Again.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
}
private void SaveAccountSetupInformation()
{
String username = UserName.getText().toString();
String userfullname = FullName.getText().toString();
String country = CountryName.getText().toString();
if(TextUtils.isEmpty(username))
{
Toast.makeText(this,"Please Write Your UserName", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(userfullname))
{
Toast.makeText(this,"Please Write Your Full Name", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(country))
{
Toast.makeText(this,"Please Write Your Country", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Saving Information...");
loadingBar.setMessage("Please wait for a while...");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
HashMap userMap = new HashMap();
userMap.put("username", username);
userMap.put("fullname", userfullname);
userMap.put("country", country);
userMap.put("status","Hey there, I am Using Pingoo");
userMap.put("gender", "none");
userMap.put("dob","None");
userMap.put("relationshipstatus","none");
UserRef.setValue(userMap).addOnCompleteListener(new OnCompleteListener()
{
#Override
public void onComplete(#NonNull Task task)
{
if(task.isSuccessful())
{
SendUserToMainActivity();
Toast.makeText(SetUpActivity.this,"Your Account Has Been Created Successfully :) Enjoy!", Toast.LENGTH_LONG).show();
SendUserToMainActivity();
loadingBar.dismiss();
}
else
{
String message = task.getException().getMessage();
Toast.makeText(SetUpActivity.this, "Oops!Something Went Wrong:(",Toast.LENGTH_LONG).show();
loadingBar.dismiss();
}
}
});
}
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(SetUpActivity.this,MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
I would appreciate if anyone could give me solution cause it's my school project and I really need to do it.
I've tried to find answer but i couldn't find it anywhere :(((
thank you in advance.

Hello, I have problem to upload my image to my firebase storage

I was watching YouTube for the instruction implementing storing image to firebase storage.
But, I got an error with getDownloadUrl() I do not know why, it was given codes from firebase helper.
public class SellerPage extends AppCompatActivity {
EditText Address;
EditText price;
EditText description;
Button register;
Button chooseImage;
private FirebaseAuth auth;
private FirebaseFirestore mFirestore;
private StorageReference mStorageRef;
private static final int RESULT_LOAD_IMAGE = 1;
private static final int IMAGE_PICK_CODE = 1000;
private static final int PERMISSION_CODE = 1001;
ImageView View;
public Uri imgUir;
private StorageTask uploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seller_page);
auth = FirebaseAuth.getInstance();
mFirestore= FirebaseFirestore.getInstance();
mStorageRef = FirebaseStorage.getInstance().getReference("Images"); // Storage for the image
Address = (EditText) findViewById(R.id.Address);
price = (EditText) findViewById(R.id.Price);
description = (EditText) findViewById(R.id.description);
register = (Button) findViewById(R.id.addButton);
chooseImage = (Button) findViewById(R.id.image);
View = (ImageView) findViewById(R.id.imageView);
chooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Check runtime permission
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED){
// permission not granted. then request it
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
requestPermissions(permissions, PERMISSION_CODE);
}else{
//permition already granted
pickImageFromGallay();
}
}else{
// OS is less than marshmello
pickImageFromGallay();
}
}
}
);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FileUploader();
addSellerInfo();
}
});
}
private void pickImageFromGallay(){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PICK_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == IMAGE_PICK_CODE && data != null){
imgUir = data.getData();
View.setImageURI(data.getData());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode){
case PERMISSION_CODE:{
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
pickImageFromGallay();
}else{
Toast.makeText(this,"Permission denied!", Toast.LENGTH_SHORT).show();
}
}
}
}
private String getExtension(Uri uri){
ContentResolver cr = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(cr.getType(uri));
}
private void FileUploader(){
final StorageReference Ref = mStorageRef.child(System.currentTimeMillis()+ "." + getExtension(imgUir));
Ref.putFile(imgUir)
.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(SellerPage.this, "Uploading Image Successful", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}
public void addSellerInfo(){
FirebaseUser user = auth.getCurrentUser();
String ID = user.getUid();
String addressStr = Address.getText().toString().trim();
String priceStr = price.getText().toString().trim();
String descriptionStr = description.getText().toString().trim();
CollectionReference parkspaces = mFirestore.collection("parkspaces");
sellerData parkspace = new sellerData(ID, addressStr, priceStr, descriptionStr);
parkspaces.add(parkspace);
}
}
call getDownloadUrl(), the call is asynchronous and you must subscribe on a success callback to obtain the results:
Ref.putFile(imgUir)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadPhotoUrl) {
Log.e("downloaduri", downloadPhotoUrl.toString());
Toast.makeText(SellerPage.this, "Uploading Image Successful", Toast.LENGTH_LONG).show();
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});

Firebase realtime-database don't show items displayed on

I'm beginner in android coding and I have a problem with displaying items in RT-database the items doesn't show up but only the image get uploaded in the storage
by following a tutorial I made this code first i used .getDownloadUrl() then i realized that it's deprecated now so i tried this solution and it's always the same problem the items doesn't shows up in the RT-database but only the image get uploaded in the storage
this is yhe code:
public class AddProductActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST =1;
private Button ChooseImage;
private Button AddProductButton;
private Button To_the_list;
private EditText name;
private ImageView item_image;
private ProgressBar mProgressBar;
private Uri mImageUri;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
private StorageTask mProductTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product);
ChooseImage = findViewById(R.id.choose_img);
AddProductButton= findViewById(R.id.add_new_product);
To_the_list = findViewById(R.id.to_list);
name=findViewById(R.id.product_name);
item_image=findViewById(R.id.product_image);
mProgressBar= findViewById(R.id.progress_bar2);
mStorageRef= FirebaseStorage.getInstance().getReference("Products");
mDatabaseRef= FirebaseDatabase.getInstance().getReference("Products");
ChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
AddProductButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProductFile();
}
});
To_the_list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void openFileChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode==RESULT_OK && data != null && data.getData() != null)
{
mImageUri = data.getData();
Picasso.with(this).load(mImageUri).into(item_image);
}
}
private String getFileExtension(Uri uri){
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void ProductFile() {
if (mImageUri != null) {
final StorageReference fileReference = mStorageRef.child(System.currentTimeMillis() + "." + getFileExtension(mImageUri));
mProductTask = fileReference.putFile(mImageUri);
mProductTask.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 fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
String downloadUri = task.getResult().toString();
Product submit = new Product(
name.getText().toString().trim(),
downloadUri);
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(submit);
} else {
Log.e("Upload","Upload failed");
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AddProductActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "Other details not Provided", Toast.LENGTH_SHORT).show();
}
}
No error but image shows up in storage but nothing in realtime-database

how to get url of an uploaded image in firebase storage v16.0.1 [duplicate]

This question already has answers here:
How to use getdownloadurl in recent versions?
(5 answers)
Closed 3 years ago.
I am already successful in posting images to Firebase Storage but I am wondering if it is possible to have a link/url in Firebase Database from which I can click to redirect me to Firebase Storage to see that image.
I want this function so that along with user inputs such as Title, Date, Remarks, the end-user would be able to see the "image" child with the link along with other inputs
I have tried searching StackOverflow and Youtube for answers but most of them are old and seem outdated. There is a command getDownloadUrl, but I believe it has been deprecated.
This is the code from my class that uploads my image to Firebase Storage. where to add storagerefernce.downloadUrl().
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
btnChoose = (ImageButton) findViewById(R.id.btnChoose);
imageView = (ImageView) findViewById(R.id.imgView);
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
chooseImage();
}
});
}
public void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),PICK_IMAGE_REQUEST);
}
#Override
protected 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 )
{
filePath = data.getData();
imgname = filePath.getLastPathSegment();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
uploadImage();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private void uploadImage()
{
if(filePath != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/"+ imgname);
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Failed "+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());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
}
You can try this way.
val ref = mStorageReference?.child("images/mMobileNumber.jpg")
val uploadTask = ref?.putFile(Uri.fromFile(File(mImagePath)))
uploadTask?.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>>
{ task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
return#Continuation ref.downloadUrl
})?.addOnCompleteListener { task ->
if (task.isSuccessful) {
val downloadUri = task.result
mTempDatabaseReference?.child("image")?.setValue(downloadUri.toString())
} else {
// Handle failures
// ...
}
}

FirebaseStorage wont upload image

I want to upload a image to my Firebase Storage bucket, but it always returns a value from OnFailureListener.
Here's the code:
public class AddProductFragment extends Fragment {
private static final int IMAGE_REQUEST = 1;
private ProgressDialog progressDialog;
private Uri uri;
private EditText mTitle,mPrice;
private Button mBtn,mUpload;
private ImageView mImage;
private FirebaseStorage mStorageRef;
private StorageReference mRef;
public AddProductFragment() {
mStorageRef = FirebaseStorage.getInstance();
mRef = mStorageRef.getReference().child("images");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.add_product_fragment,container,false);
find(v);
onClick();
return v;
}
private void find(View v) {
mTitle = (EditText)v.findViewById(R.id.singleProductTitle);
mPrice = (EditText)v.findViewById(R.id.singleProductPrice);
mBtn = (Button) v.findViewById(R.id.addProductSelectImageBtn);
mImage = (ImageView)v.findViewById(R.id.addProductImage);
mUpload = (Button)v.findViewById(R.id.uploadBtn);
}
private void onClick() {
mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent,"Select Picture"), IMAGE_REQUEST);
}
});
mUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMax(100);
progressDialog.setMessage("Uploading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
progressDialog.setCancelable(false);
String title = mTitle.getText().toString();
String price = mPrice.getText().toString();
if (!title.isEmpty() && !price.isEmpty()) {
Product product = new Product();
Uri file = Uri.fromFile(new File(getRealPathFromURI(uri)));
mRef.child("original").child(product.getStringId());
mRef.putFile(file).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
//sets and increments value of progressbar
progressDialog.incrementProgressBy((int) progress);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), "Error uploading....", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Toast.makeText(getActivity(),"Upload successful",Toast.LENGTH_SHORT).show();
//TODO: redirect to the uploaded product;
progressDialog.dismiss();
}
});
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == IMAGE_REQUEST && resultCode == RESULT_OK) {
try {
uri = data.getData();
Bitmap bitmap = null;
if(uri != null) {
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
mImage.setImageBitmap(bitmap);
} else {
Toast.makeText(getActivity(), "Uri not found...", Toast.LENGTH_SHORT).show();
}
} catch (NullPointerException e) {
e.getMessage();
}
}
}
private String getRealPathFromURI(Uri contentURI) {
String thePath = "no-path-found";
String[] filePathColumn = {MediaStore.Images.Media.DISPLAY_NAME};
Cursor cursor = getActivity().getContentResolver().query(contentURI, filePathColumn, null, null, null);
if(cursor.moveToFirst()){
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
thePath = cursor.getString(columnIndex);
}
cursor.close();
return thePath;
}
}
Here is the exception:
/com.example.cmd.pop E/StorageException:
/image-0-02-05-64dcdbd29d607a4421b258b2adbfb848cf3262ee096a8b0ab2dbecd22631feea-V.jpg:
open failed: ENOENT (No such file or directory)
java.io.FileNotFoundException:
/image-0-02-05-64dcdbd29d607a4421b258b2adbfb848cf3262ee096a8b0ab2dbecd22631feea-V.jpg:
open failed: ENOENT (No such file or directory)
Anyway i found the solution, the reference path was wrong
Changes in constructor
public AddProductFragment() {
mStorageRef = FirebaseStorage.getInstance();
mRef = mStorageRef.getReference().child("images/original/");
mThumbRef = mStorageRef.getReference().child("images/thumb");
}
And OnActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK) {
uri = data.getData();
String title = mTitle.getText().toString();
String price = mPrice.getText().toString();
if (!title.isEmpty() && !price.isEmpty()) {
Product product = new Product();
StorageReference thumbRef = mRef.child(product.getStringId()).child(uri.getLastPathSegment());
StorageReference imageRef = mRef.child(product.getStringId()).child(uri.getLastPathSegment());
imageRef.putFile(uri).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
Log.d(TAG, e.getMessage());
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Toast.makeText(getActivity(), "Upload successful", Toast.LENGTH_SHORT).show();
//TODO: redirect to the uploaded product;
}
});
thumbRef.putFile(uri).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
Log.d(TAG, e.getMessage());
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Toast.makeText(getActivity(), "Upload successful", Toast.LENGTH_SHORT).show();
//TODO: redirect to the uploaded product;
}
});
}
}
}
And added permission to manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Categories

Resources