Android studio firebase how to download and show image(without uploading first!) - android

I have an script which works perfectly regarding uploading an image, and then showing it on my app. Here is my full code:
public class MainActivity extends AppCompatActivity {
private StorageReference mStorageRef;
Button btnPickImage, btnUpload, buttonDownload;
ImageView imgSource, imgDestination;
LinearLayout lv;
Uri selectedImage;
ProgressBar pbbar;
DatabaseReference databaseReference, childReference;
private static final int REQUEST_TAKE_GALLERY_PHOTO = 2;
StorageReference fireRef;
private FirebaseAuth mAuth;
FirebaseUser currentUser;
String imageURL = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
pbbar = findViewById(R.id.pbbar);
pbbar.setVisibility(View.GONE);
lv = findViewById(R.id.lv);
mStorageRef = FirebaseStorage.getInstance().getReference();
databaseReference = FirebaseDatabase.getInstance().getReference();
btnPickImage = findViewById(R.id.btnPickImage);
btnUpload = findViewById(R.id.btnUpload);
buttonDownload = findViewById(R.id.btnDownload);
buttonDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//justDownloadWithoutUploading();
}
});
imgSource = findViewById(R.id.imgSource);
imgDestination = findViewById(R.id.img);
btnPickImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)
&& !Environment.getExternalStorageState().equals(
Environment.MEDIA_CHECKING)) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_TAKE_GALLERY_PHOTO);
} else
Toast.makeText(MainActivity.this, "No gallery found.", Toast.LENGTH_SHORT).show();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UploadImages();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_GALLERY_PHOTO) {
Bitmap originBitmap = null;
selectedImage = data.getData();
InputStream imageStream;
try {
pbbar.setVisibility(View.VISIBLE);
imageStream = getContentResolver().openInputStream(
selectedImage);
originBitmap = BitmapFactory.decodeStream(imageStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (originBitmap != null) {
{
this.imgSource.setImageBitmap(originBitmap);
pbbar.setVisibility(View.GONE);
imgSource.setVisibility(View.VISIBLE);
}
} else
selectedImage = null;
}
}
}
public String GetDate() {
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String currentdate = df.format(Calendar.getInstance().getTime());
return currentdate;
}
public void UploadImages() {
try {
pbbar.setVisibility(View.VISIBLE);
lv.setVisibility(View.GONE);
String strFileName = GetDate() + "img.jpg";
Uri file = selectedImage;
fireRef = mStorageRef.child("images/" + currentUser.getUid().toString() + "/" + strFileName);
UploadTask uploadTask = fireRef.putFile(file);
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
//return fireRef.getDownloadUrl();
Toast.makeText(MainActivity.this, "Calling method!", Toast.LENGTH_LONG).show();
return downloadImage(fireRef);
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
Log.e("Image URL", downloadUri.toString());
pbbar.setVisibility(View.GONE);
selectedImage = null;
imageURL = downloadUri.toString();
} else {
Toast.makeText(MainActivity.this, "Image upload unsuccessful. Please try again.", Toast.LENGTH_LONG).show();
}
pbbar.setVisibility(View.GONE);
lv.setVisibility(View.VISIBLE);
DownloadImageFromURL downloadImageFromURL = new DownloadImageFromURL();
downloadImageFromURL.execute("");
}
});
} catch (Exception ex) {
Toast.makeText(MainActivity.this, ex.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
private class DownloadImageFromURL extends AsyncTask<String, Void, String> {
Bitmap bitmap = null;
#Override
protected void onPreExecute() {
}
protected String doInBackground(String... urls) {
try {
Log.e("imageURL is ", imageURL);
InputStream in = new java.net.URL(imageURL).openStream();
if (in != null) {
bitmap = BitmapFactory.decodeStream(in);
} else
Log.e("Empty InputStream", "InputStream is empty.");
} catch (MalformedInputException e) {
Log.e("Error URL", e.getMessage().toString());
} catch (Exception ex) {
Log.e("Input stream error", "Input stream error");
}
return "";
}
protected void onPostExecute(String result) {
if (bitmap != null) {
imgDestination.setImageBitmap(bitmap);
} else
Log.e("Empty Bitmap", "Bitmap is empty.");
}
}
public Task<Uri> downloadImage(StorageReference fireRef){
Toast.makeText(MainActivity.this, "THIS METHOD GOT CALLED.", Toast.LENGTH_LONG).show();
return fireRef.getDownloadUrl();
}}
However, I have added an extra button to just download a picture (no uploading!), but I am struggling to make this possible. I have made a method for this called "justDownloadWithoutUploading"
code:
public void justDownloadWithoutUploading(){
final StorageReference img_dest;
img_dest = mStorageRef.child("images/" + currentUser.getUid().toString() + "/" + "20200203144042img.jpg");
FirebaseStorage storage = FirebaseStorage.getInstance();
final StorageReference storageRef = storage.getReference();
final StorageReference islandRef = storageRef.child("images/20200203144042img.jpg"); //gs://viproverselvfølgeligigjen.appspot.com/images/20200203144042img.jpg
final long ONE_MEGABYTE = 1024 * 1024;
islandRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
// Data for "images/island.jpg" is returns, use this as needed
downloadImage(img_dest); // ERROR: 2020-02-04 14:48:29.272 27487-27830/com.example.admin_panel E/StorageException: StorageException has occurred?
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
}
This method will create the references into the specific image, and then call the "public Task downloadImage" at the end adding the link into the parameter, but nothing happens..
Full error:
2020-02-04 17:31:06.669 1020-1456/com.example.admin_panel E/StorageException: StorageException has occurred.
Object does not exist at location.
Code: -13010 HttpResult: 404
2020-02-04 17:31:06.671 1020-1456/com.example.admin_panel E/StorageException: Could not open resulting stream.
java.io.IOException: Could not open resulting stream.
at com.google.firebase.storage.StreamDownloadTask.createDownloadStream(com.google.firebase:firebase-storage##16.0.4:143)
at com.google.firebase.storage.StreamDownloadTask.access$000(com.google.firebase:firebase-storage##16.0.4:38)
at com.google.firebase.storage.StreamDownloadTask$1.call(com.google.firebase:firebase-storage##16.0.4:165)
at com.google.firebase.storage.StreamDownloadTask$1.call(com.google.firebase:firebase-storage##16.0.4:162)
at com.google.firebase.storage.StreamDownloadTask$StreamProgressWrapper.ensureStream(com.google.firebase:firebase-storage##16.0.4:324)
at com.google.firebase.storage.StreamDownloadTask$StreamProgressWrapper.access$100(com.google.firebase:firebase-storage##16.0.4:261)
at com.google.firebase.storage.StreamDownloadTask.run(com.google.firebase:firebase-storage##16.0.4:173)
at com.google.firebase.storage.StorageTask.lambda$getRunnable$7(com.google.firebase:firebase-storage##16.0.4:1106)
at com.google.firebase.storage.StorageTask$$Lambda$12.run(Unknown Source:2)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Could someone here plz help me?

Related

How to get download url for firebase storage and update firestore document?

I have been struggling to get download url for an image uploaded to firebase storage from my app.
I want to send this url to firestore databse (not realtime database).
I am setting itemImageUri to uri.toString() but in onCreate() method itemImageUrl is null and shows null in firestore. I cannot use CollectionRefernece addItemRef in onSuccess method as it gives error for all string variables: Variable is accessed from within inner class needs to be declared final.
public class AddItemActivity extends AppCompatActivity {
public class AddItemActivity extends AppCompatActivity {
public static final int PICK_IMAGE_REQUEST = 1;
public static final String TAG = "Error!";
public static final String UPLOAD_TAG = "Image uploaded";
private Uri imageUri = null;
private TextInputEditText textFieldTitle;
private TextInputEditText textFieldDesc;
private AutoCompleteTextView dropdownItemType;
private TextInputEditText textFieldAddress;
private TextInputEditText textFieldAvailability;
private MaterialButton buttonSubmitItem;
private MaterialButton buttonAddImage;
private ImageView imageViewItem;
private String itemImageUrl;
private Bitmap bitmap;
private Uri itemImageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
imageViewItem = findViewById(R.id.imageView_camera);
textFieldTitle = findViewById(R.id.textField_title);
textFieldDesc = findViewById(R.id.textField_description);
dropdownItemType = findViewById(R.id.dropdown_itemType);
//Select type dropdown
String[] itemTypes = new String[] {
"Food",
"Clothing",
"Footwear"
};
ArrayAdapter<String> itemsDropdownAdpater = new ArrayAdapter<>(AddItemActivity.this, R.layout.dropdown_item_type, itemTypes);
dropdownItemType.setAdapter(itemsDropdownAdpater);
textFieldAddress = findViewById(R.id.textField_address);
textFieldAvailability = findViewById(R.id.textField_availability);
buttonAddImage = findViewById(R.id.button_addImage);
buttonSubmitItem = findViewById(R.id.button_submitItem);
buttonAddImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(AddItemActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(AddItemActivity.this, "Permission Denied", Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(AddItemActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
} else {
choseImage();
}
} else {
choseImage();
}
}
});
buttonSubmitItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitItem();
}
});
}
private void choseImage() {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(AddItemActivity.this);
}
private void submitItem() {
String title = textFieldTitle.getText().toString();
String desc = textFieldDesc.getText().toString();
String type = dropdownItemType.getText().toString();
String address = textFieldAddress.getText().toString();
String availability = textFieldAvailability.getText().toString();
if (title.trim().isEmpty() ||
desc.trim().isEmpty() ||
type.trim().isEmpty() ||
availability.trim().isEmpty()) {
Toast.makeText(this, "Fields cant be empty", Toast.LENGTH_SHORT).show();
return;
}
handleUpload(bitmap);
CollectionReference addItemRef = FirebaseFirestore.getInstance()
.collection("ItemList");
addItemRef.add(new ItemListModel(title, desc, type, address, availability, itemImageUrl));
Toast.makeText(this, "Item added", Toast.LENGTH_SHORT).show();
finish();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
imageUri = result.getUri();
imageViewItem.setImageURI(imageUri);
imageViewItem.invalidate();
BitmapDrawable drawable = (BitmapDrawable) imageViewItem.getDrawable();
bitmap = drawable.getBitmap();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void handleUpload(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
final StorageReference reference = FirebaseStorage.getInstance().getReference()
.child("itemImages")
.child(System.currentTimeMillis() + ".jpeg");
reference.putBytes(baos.toByteArray())
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
getItemImageUrl(reference);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "onFailure: ", e.getCause());
}
});
}
private void getItemImageUrl(StorageReference reference) {
reference.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
itemImageUrl = uri.toString();
}
});
}
}
Determining the download URL requires a call to the servers, which means it happens asynchronously. For this reason, any code that needs the download URL needs to be inside the onSuccess of getDownloadURL() or be called from there.
So:
private void getItemImageUrl(StorageReference reference) {
reference.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
itemImageUrl = uri.toString();
... here you can write itemImageUrl to the database
}
});
}
Also see:
How to get the download url from Firebase Storage?
In NodeJS, to get a link for a document stored in Firebase Storage.
const options = {
version: 'v2', // defaults to 'v2' if missing.
action: 'read',
expires: Date.now() + 1000 * 60 * 60, // one hour
};
let url = storage
.bucket(bucketname)
.file(filename)
.getSignedUrl(options);
First upload the file to the Storage, then call your upload method to the database on the addOnCompleteListener :
final StorageReference fileReference = storageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(uriList.get(i)));
uploadTask = fileReference.putFile(uriList.get(i));
uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful() && task.getException() != null) {
throw task.getException();
}
return fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
if(downloadUri != null) {
itemImageUrl = downloadUri.toString()
// create your object
// upload your object to the database here
}
}
}
});

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

Firebase Won't create new user data in database

I wrote a code that lets people sign up to my up, but when I press the button the new user isn't created in the database (it stays null) what can i do?
here is the SignUpActivity.java:
public class SignUpActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private EditText userEmail, userPassword1, userPassword2, userCode, userName, userDescription;
private ImageView image;
private ProgressDialog pDialog;
private boolean imagePressed = false;
private Uri filePath;
private FirebaseStorage storage;
private StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
userCode = findViewById(R.id.userCode);
userDescription = findViewById(R.id.userDescription);
userEmail = findViewById(R.id.userEmail);
userName = findViewById(R.id.userName);
userPassword1 = findViewById(R.id.userPassword1);
userPassword2 = findViewById(R.id.userPassword2);
image = findViewById(R.id.userImageAdd);
mAuth = FirebaseAuth.getInstance();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imagePressed = true;
chooseImage();
}
});
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), Finals.PICK_IMAGE_REQUEST);
}
public void back(View view) {
finish();
}
public void submit(View view) {
pDialog = new ProgressDialog(this);
if (TextUtils.isEmpty(userEmail.getText().toString())) {
Toast.makeText(SignUpActivity.this, "Please enter email.", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(userPassword1.getText().toString())) {
Toast.makeText(SignUpActivity.this, "Please enter password.", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(userPassword2.getText().toString())) {
Toast.makeText(SignUpActivity.this, "Please repeat password.", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(userName.getText().toString())) {
Toast.makeText(SignUpActivity.this, "Please enter user name", Toast.LENGTH_SHORT).show();
} else if (!userPassword1.getText().toString().equals(userPassword2.getText().toString())) {
pDialog.dismiss();
Toast.makeText(SignUpActivity.this, "The passwords don't match.", Toast.LENGTH_SHORT).show();
} else {
pDialog.setMessage("Creating account...");
pDialog.show();
pDialog.setCanceledOnTouchOutside(false);
if (imagePressed && filePath != null) {
final StorageReference ref = storageReference.child("users/" + UUID.randomUUID().toString());
ref.putFile(filePath).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downUri = task.getResult();
boolean isTrainer = trainer();
register(userEmail.getText().toString(), userPassword1.getText().toString(), userName.getText().toString(), userDescription.getText().toString(),
downUri.toString(), isTrainer);
}
}
});
} else {
boolean isTrainer = trainer();
register(userEmail.getText().toString(), userPassword1.getText().toString(), userName.getText().toString(), userDescription.getText().toString(),
Finals.DEFAULT_USER_IMAGE_URL, isTrainer);
finish();
}
}
}
private boolean trainer() {
boolean trainer = false;
if (!TextUtils.isEmpty(userCode.getText())) {
if (userCode.getText().toString().equals(Finals.T_CODE))
trainer = true;
else if (!userCode.getText().toString().equals(Finals.T_CODE)) {
pDialog.dismiss();
Toast.makeText(this, "Not a real trainer code!", Toast.LENGTH_SHORT).show();
}
}
return trainer;
}
private void register(final String regEmail, final String regPassword,
final String regName, final String regDesc, final String url, final boolean trainer) {
mAuth.createUserWithEmailAndPassword(regEmail, regPassword).addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser firebaseUser = mAuth.getCurrentUser();
String userId = firebaseUser.getUid();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("id", mAuth.getCurrentUser().getUid());
hashMap.put("name", regName);
hashMap.put("description", regDesc);
hashMap.put("isTrainer", trainer);
hashMap.put("imageUrl", url);
FirebaseDatabase.getInstance().getReference().child("users").child(userId).setValue(hashMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
pDialog.dismiss();
Toast.makeText(SignUpActivity.this, "Created user", Toast.LENGTH_SHORT).show();
startActivity(new Intent(SignUpActivity.this, MainActivity.class));
} else {
pDialog.dismiss();
Toast.makeText(SignUpActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
}
});
} else {
pDialog.dismiss();
Toast.makeText(SignUpActivity.this, "Creation failed :" + task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Finals.PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
filePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
this used to work on my previous phone but now it doesn't work on the new phone.
what could cause this bug?
Also the progress dialog wont show either.
when I try to access the code (say in this line - DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("users").child(id);) it returns null.
I don't get the "Something went wrong" either, it just goes to the LoginActivity (not the main Activity for whatever reason) who called it , and then I can login using the new user i created but can't access the data(it's null).
These are the database rules:
{
"rules": {
".read": true,
".write": true
}
}
Somehow, rewriting the code differently fixed the bug
new code -
private Context mContext;
private String email, username, password1, password2, trainerCode, description, imageUrl = Finals.DEFAULT_USER_IMAGE_URL;
private EditText mEmail, mPassword1, mPassword2, mUsername, mTrainerCode, mDescription;
private Button btnSubmit, btnBack;
private ImageView imageView;
private ProgressDialog pDialog;
private String userID;
private boolean isTrainer, imagePressed = false;
private Uri filePath;
//firebase
private FirebaseAuth mAuth;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private FirebaseStorage storage;
private StorageReference storageReference;
private View.OnClickListener imageClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
imagePressed = true;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), Finals.PICK_IMAGE_REQUEST);
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
mContext = SignUpActivity.this;
pDialog = new ProgressDialog(this);
mEmail = findViewById(R.id.userEmail);
mUsername = findViewById(R.id.userName);
btnSubmit = findViewById(R.id.btn_submit);
mPassword1 = findViewById(R.id.userPassword1);
mPassword2 = findViewById(R.id.userPassword2);
mTrainerCode = findViewById(R.id.userCode);
mDescription = findViewById(R.id.userDescription);
imageView = findViewById(R.id.userImageAdd);
btnBack = findViewById(R.id.backBtn);
btnSubmit.setOnClickListener(btnSubmitListener);
imageView.setOnClickListener(imageClickListener);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
}
private View.OnClickListener btnSubmitListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
email = mEmail.getText().toString();
username = mUsername.getText().toString();
password1 = mPassword1.getText().toString();
password2 = mPassword2.getText().toString();
trainerCode = mTrainerCode.getText().toString();
description = mDescription.getText().toString();
isTrainer = false;
if (checkInputs(email, username, password1, password2, trainerCode)) {
pDialog.setMessage("Creating User...");
pDialog.show();
if (imagePressed && filePath != null)
uploadImage();
else
registerNewUser();
}
}
};
private void uploadImage() {
final StorageReference ref = storageReference.child("users/" + UUID.randomUUID().toString());
ref.putFile(filePath).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()){
throw task.getException();
}
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
Uri downUri = task.getResult();
imageUrl = downUri.toString();
registerNewUser();
}
});
}
public void registerNewUser() {
mAuth.createUserWithEmailAndPassword(email, password1)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(SignUpActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
} else {
userID = mAuth.getCurrentUser().getUid();
addNewUser();
}
}
});
}
private boolean checkInputs(String email, String name, String password1, String password2, String trainerCode) {
if (email.equals("")) {
Toast.makeText(mContext, "Please enter email", Toast.LENGTH_SHORT).show();
return false;
}
if (name.equals("")) {
Toast.makeText(mContext, "Please enter name", Toast.LENGTH_SHORT).show();
return false;
}
if (password1.equals("")) {
Toast.makeText(mContext, "Please enter password", Toast.LENGTH_SHORT).show();
return false;
}
if (password2.equals("")) {
Toast.makeText(mContext, "Please repeat password", Toast.LENGTH_SHORT).show();
return false;
}
if (!password1.equals(password2)) {
Toast.makeText(mContext, "Passwords don't natch", Toast.LENGTH_SHORT).show();
return false;
}
if (!trainerCode.equals("")) {
if (trainerCode.equals(Finals.T_CODE)) {
isTrainer = true;
return true;
} else {
Toast.makeText(mContext, "Not a real trainer code!", Toast.LENGTH_SHORT).show();
return false;
}
}
return true;
}
public void addNewUser() {
UserClass user = new UserClass(description, email, userID, imageUrl, isTrainer, username, password1);
myRef.child("users").child(userID).setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
pDialog.dismiss();
Toast.makeText(mContext, "Created new User", Toast.LENGTH_SHORT).show();
startActivity(new Intent(SignUpActivity.this, MainActivity.class));
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Finals.PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
filePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks a lot to all of you who have tried to help!

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");```

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