FirebaseStorage wont upload image - android

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"/>

Related

Images of firebase not showing in recycleView

enter image description here
In the above images the last one is not appearing in the recycle View what is the reason.
My main activity code is given below and you can check what is wrong with this. All the first images are uploaded by the IOS app and are appearing in the recycle View. But when I upload the images from my phone it is not showing in the recyclceView.
personPicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chooseProfilePictureFromGallery = new Intent(Intent.ACTION_GET_CONTENT);
chooseProfilePictureFromGallery.setType("image/*");
if (chooseProfilePictureFromGallery.resolveActivity(getApplicationContext().getPackageManager()) != null) {
startActivityForResult(Intent.createChooser(chooseProfilePictureFromGallery, "Select Picture"), PICK_IMAGE);
}
}
});
UButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkValidity()==true)
{
detailInfoUpload();
}
}
});
}
private boolean checkValidity() {
String name = pName.getText().toString();
String age = pAge.getText().toString().trim();
String contactNumber = pNumber.getText().toString().trim();
String address = pFullAddress.getText().toString();
if(name.isEmpty())
{
Toast.makeText(getApplicationContext(),"Please give a name",Toast.LENGTH_SHORT).show();
return false;
}
else if(age.isEmpty())
{
Toast.makeText(getApplicationContext(),"Please give proper age",Toast.LENGTH_SHORT).show();
return false;
}
else if(contactNumber.isEmpty() || contactNumber.length()<11)
{
Toast.makeText(getApplicationContext(),"Please give contact number",Toast.LENGTH_SHORT).show();
return false;
}
else if(address.isEmpty())
{
Toast.makeText(getApplicationContext(),"Please give a name",Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private void showToast() {
Toast.makeText(getApplicationContext(), "Information Uploaded Successfully ", Toast.LENGTH_SHORT).show();
}
private void detailInfoUpload() {
if (FilePathUri != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading");
progressDialog.show();
String uName = pName.getText().toString().trim();
String uAge = pAge.getText().toString();
String uBelong = pBelong.getText().toString().trim();
String uDC = pDisappearedCity.getText().toString().trim();
String uDD = pDisappearedDate.getText().toString().trim();
String uAdd = pFullAddress.getText().toString();
String uPh = pNumber.getText().toString().trim();
String uId = firebaseAuth.getInstance().getCurrentUser().getUid();
databaseReference = FirebaseDatabase.getInstance().getReference();
String postid = databaseReference.child("missing_requests").push().getKey();
StorageReference storageReference2 = storageReference.child(postid+ "." + GetFileExtension(FilePathUri));
storageReference2.putFile(FilePathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressDialog.setProgress(0);
}
}, 500);
PostMissingModel postMissingModel = new PostMissingModel(uAdd,uAge, uBelong,
uDD,uDC,genderT,taskSnapshot.getUploadSessionUri().toString(),postid,uName,statusT,uPh,uId);
//String ImageUploadId = databaseReference.push().getKey();
Log.d("mes","we are in just above uploading method");
databaseReference.child("missing_requests").push().setValue(postMissingModel);
showToast();
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
//displaying the upload progress
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
}
else {
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
FilePathUri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);
personPicture.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String GetFileExtension(Uri uri) {
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri)) ;
}
}
use its a jpeg image so, user a library called Picasso. link
get dependency from that URL and add it to your Gradle file and use that code:
Picasso.get().load("YOUR IMAGE URL HERE").into(imageView);
if it does not work can you please share code with us?

How to upload an image file to firebase firestore?

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.

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

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?

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

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

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

Categories

Resources