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?
Related
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
}
}
}
});
please help me, I success to pick an image with a gallery and camera. but image not showing in image view or firebase storage.
this is my manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA"/>
this is my code to show or upload images
FirebaseAuth firebaseAuth;
FirebaseUser user;
ImageView ava,cover2;
TextView nametv,biotv;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
FloatingActionButton floatingActionButton;
ProgressDialog progressDialog;
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 200;
private static final int IMAGE_PICK_CAMERA_CODE = 300;
private static final int IMAGE_PICK_GALLERY_CODE = 400;
String cameraPermissions[];
String storagePermissions[];
Uri image_uri;
String profilorcover;
StorageReference storageReference;
String storagePath = "Users_Profile_Cover_Imgs/";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_prof, container, false);
firebaseAuth = FirebaseAuth.getInstance();
user = firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
progressDialog = new ProgressDialog(getActivity());
ava = view.findViewById(R.id.avaim);
nametv = view.findViewById(R.id.namatv);
biotv = view.findViewById(R.id.biotv);
cover2 = view.findViewById(R.id.rela);
floatingActionButton = view.findViewById(R.id.editbtn);
storageReference = getInstance().getReference();
camera permissions
cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
String name = ""+ ds.child("name").getValue();
String email = ""+ ds.child("email").getValue();
String bio = ""+ ds.child("bio").getValue();
String image = ""+ ds.child("image").getValue();
String cover = ""+ds.child("cover").getValue();
nametv.setText(name);
biotv.setText(bio);
try {
Picasso.get().load(image).into(ava);
}
catch (Exception e){
Picasso.get().load(R.drawable.ic_cam_name).into(ava);
}
try {
Picasso.get().load(cover).into(cover2);
}
catch (Exception e){
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editprofil();
}
});
return view;
}
private boolean checkstorage(){
boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result;
}
private void reqstorage(){
requestPermissions(storagePermissions, STORAGE_REQUEST_CODE);
}
private boolean checkcam(){
boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
== (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
private void reqcam(){
requestPermissions(cameraPermissions, CAMERA_REQUEST_CODE);
}
private void editprofil() {
String pengaturan[] = {"Edit Foto Profil", "Edit Foto Sampul", "Edit Nama", "Edit Bio"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Edit Profil");
builder.setItems(pengaturan, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0){
progressDialog.setMessage("Mengubah Profil");
profilorcover = "image";
showimage();
}
else if (i == 1){
progressDialog.setMessage("Mengubah Profil");
profilorcover = "cover";
showimage();
}
else if (i == 2){
progressDialog.setMessage("Mengubah Profil");
shownamebio("name");
}
else if (i == 3){
progressDialog.setMessage("Mengubah Profil");
shownamebio("bio");
}
}
});
builder.create().show();
}
private void showimage() {
String pengaturan[] = {"Camera", "Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Edit Profil");
builder.setItems(pengaturan, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0){
if (!checkcam()){
reqcam();
}
else{
memilih();
}
}
else if (i == 1){
if (!checkstorage()){
reqstorage();
}
else{
memilihgal();
}
}
}
});
builder.create().show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if (grantResults.length >0){
boolean cameraacc = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writestor = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(cameraacc && writestor){
memilih();
}
else {
Toast.makeText(getActivity(), "Setujui Kamera dan File Manager", Toast.LENGTH_SHORT).show();
}
}
}
break;
case STORAGE_REQUEST_CODE:{
if (grantResults.length >0){
boolean writestor = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if(writestor){
memilihgal();
}
else {
Toast.makeText(getActivity(), "Setujui File Manager", Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == RESULT_OK){
if(requestCode == IMAGE_PICK_GALLERY_CODE){
image_uri = data.getData();
uploadprofile(image_uri);
}
if (requestCode == IMAGE_PICK_CAMERA_CODE){
uploadprofile(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadprofile(Uri uri) {
progressDialog.show();
String file = storagePath+ ""+ profilorcover +"_"+ user.getUid();
StorageReference storageReference2 = storageReference.child(file);
storageReference2.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloaduri = uriTask.getResult();
if (uriTask.isSuccessful()){
HashMap<String, Object> results = new HashMap<>();
results.put(profilorcover, downloaduri.toString());
databaseReference.child(user.getUid()).updateChildren(results)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "Mengubah Gambar...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "Tidak dapat mengubah gambar...", Toast.LENGTH_SHORT).show();
}
});
}
else{
progressDialog.dismiss();
Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void memilih() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Temp Pic");
values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");
image_uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent camerai = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
camerai.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(camerai, IMAGE_PICK_CAMERA_CODE);
}
private void memilihgal() {
Intent gall = new Intent(Intent.ACTION_PICK);
gall.setType("image/*");
startActivityForResult(gall, IMAGE_PICK_GALLERY_CODE);
}
}
database
rule database
The way you're getting the download URL looks fishy. Having any sort of while (!uriTask.isSuccessful()); in your Android code is unlikely to ever give the desired result.
This is how I'd normalize it:
String file = storagePath+ ""+ profilorcover +"_"+ user.getUid();
StorageReference storageReference2 = storageReference.child(file);
storageReference2.putFile(uri).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();
}
// Continue with the task to get the download URL
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
HashMap<String, Object> results = new HashMap<>();
results.put(profilorcover, downloaduri.toString());
databaseReference.child(user.getUid()).updateChildren(results)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "Mengubah Gambar...", Toast.LENGTH_SHORT).show();
}
}
});
} else {
progressDialog.dismiss();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
This is a pretty direct merge of your code with the flow from the Firebase documentation on getting a download URL after uploading an image.
That problem in the code requestcode == result_ok. That must change like resultcode==result_ok. That's why my problem solved.
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == RESULT_OK){
requestCode replace wirh resultCode.
if(requestCode == IMAGE_PICK_GALLERY_CODE){
image_uri = data.getData();
uploadprofile(image_uri);
}
if (requestCode == IMAGE_PICK_CAMERA_CODE){
uploadprofile(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
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>
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");```
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"/>