get data from Arraylist with index 0 - android

I would like to get first data inside Arraylist but my code getting issue that String img contain null data. here is my code :
private List<String> imagedUploaded = new ArrayList<>();
....
private void uploadImageFile(List<Uri> imgUrl) {
for (Uri uri : imgUrl) {
StorageReference fileToUpload = storageRef.child(productID).child(getFileName(uri));
fileToUpload.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
listImageSelectedAdapter.notifyDataSetChanged();
imagedUploaded.add(taskSnapshot.getDownloadUrl().toString()); // get image downloadurl
**defImg = imagedUploaded.get(0);**
productImage = product_Ref.child("product_image").child(productID);
productImage.setValue(imagedUploaded);
selectedImages.clear();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), "Upload Image Failed", Toast.LENGTH_SHORT).show();
}
});
}
}
here when i want to call index result
uploadProduct() {
product = product_Ref.child(path1).child(path2).child(path3).child(productID);
DataUploadProduct data = new DataUploadProduct();
data.setName(etProductName.getText().toString());
data.setPrice(etPrice.getText().toString());
**data.setDef_image(defImg);**
data.setWeight(etWeight.getText().toString());
data.setDescription(etDescription.getText().toString());
product.setValue(data);
}
in this case imagedUploaded contain :
0 = http://www.url.com1
1 = http://www.url.com2
2 = http://www.url.com3
3 = http://www.url.com4
i want to get data only index 0, how i can do that?

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 "No content provider" error for imageview

I am working on an app where I have uploaded images to Firebase, then I use a query to look for an image based on its name, I display it in an imageview, then I try to upload this image to a different table in the same firebase database.
My problem is that when I try to upload the image to the other table, I get a No content provider error, and in front of it is a fully working link to my image (I click on it and my image is displayed in the browser).
Here is the code that I have tried :
private void addToMenu(){
final Query query = mDatabaseRef.orderByChild("name").equalTo(EditTextName.getText().toString());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot NamedImage : dataSnapshot.getChildren()) {
SliderUtils sliderUtils = NamedImage.getValue(SliderUtils.class);
Uri uriFile = Uri.parse(sliderUtils.getImageUrl());
StorageReference Ref= menuStorageRef.child(System.currentTimeMillis()+"."+getPath(uriFile));
mStorageTask = Ref.putFile(uriFile)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setProgress(0);
}
}, 500);
Toast.makeText(MainActivity.this, "Image uploaded successfully.",
Toast.LENGTH_LONG).show();
SliderUtils sliderUtils = new SliderUtils(EditTextName.getText().toString().trim(),
taskSnapshot.getDownloadUrl().toString());
String uploadId = menuDatabaseRef.push().getKey();
menuDatabaseRef.child(uploadId).setValue(sliderUtils);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(MainActivity.this,"Image upload failed.",Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressBar.setProgress((int) progress);
}
});
}
}
}
the getPath() function is the following:
private String getPath(Uri uri){
ContentResolver cr = getContentResolver();
MimeTypeMap mimeTypeMap= MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(cr.getType(uri));
}
The error I get is :
/StorageException: StorageException has occurred.
An unknown error occurred, please check the HTTP result code and inner exception for server response.
Code: -13000 HttpResult: 0
E/StorageException: No content provider: https://firebase...
Do you have any idea where the problem is please?
for anyone in the same situation and looking for a solution:
A big mistake that I had is that I was trying to turn an URL into a URI which is simply impossible
So I decided to change the way that I was uploading my image altogether. Here is the code:
private void addToMenu(){
final Query query =
mDatabaseRef.orderByChild("name").equalTo(EditTextName.getText().toString());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot NamedImage : dataSnapshot.getChildren()) {
SliderUtils sliderUtils = NamedImage.getValue(SliderUtils.class);
StorageReference Ref= menuStorageRef.child("filename" + new Date().getTime());
image.setDrawingCacheEnabled(true);
image.buildDrawingCache();
Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = Ref.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(MainActivity.this,"Image upload failed.",Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Image uploaded successfully.", Toast.LENGTH_LONG).show();
SliderUtils sliderUtils = new SliderUtils(EditTextName.getText().toString().trim(),
taskSnapshot.getDownloadUrl().toString());
String uploadId = menuDatabaseRef.push().getKey();
menuDatabaseRef.child(uploadId).setValue(sliderUtils);
}
});
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

One one image uploading with different postkeys but i want to store all images under one postkey in Firebase Database

One one image uploading with different postkeys but i want to store all images under one postkey
This is the code where im uploading all the images to firebase storage and databse with post key but one one images are storing with different post key and i want to store all the uploaded images into one post key under blog in firebase databse. Please help me _This is th issue im facing from past few days and i want to retrieve all the uploaded images under one postkey
upload.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
UploadTask uploadTask;
if( selectedImageGridView.getChildCount()!= 0)
{
for ( int i = 0; i < selectedImages.size(); i++) {
blogimages = new ArrayList<>();
Uri uri = Uri.parse("file://"+selectedImages.get(i));
final String CurrentUser = firebaseAuth.getCurrentUser().getUid();
StorageReference reference = mstorageReference.child("Blog_pics/users").child(uri.getLastPathSegment());
uploadTask = reference.putFile(uri);
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
final Uri downloaduri = taskSnapshot.getDownloadUrl();
Log.v("DOWNLOAD URI", String.valueOf(downloaduri));
blogimages.add(downloaduri.toString());
Log.v("BLOGGIMAGES", String.valueOf(blogimages));
final String key = mdatabaseReference.push().getKey();
final String posttitle = desc.getText().toString();
final String CurrentUser = firebaseAuth.getCurrentUser().getUid();
int l = 0;
while (l < blogimages.size()){
Log.v("BLOGIMAGESSIZE", String.valueOf(blogimages.size()));
Map n = new HashMap();
int countingImage = 0;
n.put(String.valueOf("img" + countingImage), blogimages.get(l).toString());
Log.v("MapCount", String.valueOf(n));
mdatabaseReference.child(key).child("images").updateChildren(n).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(PhotoUploadActivity.this, "got download url", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(PhotoUploadActivity.this, "Failed to put in db", Toast.LENGTH_SHORT).show();
}
}
});
l++;
countingImage++;
}
}
}) .addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
}
}
}
});
you have to change this line
StorageReference reference = mstorageReference.child("Blog_pics/users").child(uri.getLastPathSegment());
to this lines: you have to put those lines befor the for loop
String userId = firebaseAuth.getCurrentUser().getUid();
StorageReference reference = mstorageReference.child("Blog_pics/users").child(userId);
then inside the loop
refrence.child(uri.getLastPathSegment());
uploadTask = reference.putFile(uri);
...

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

Firebase Storage OnSuccessListeners not successful in time

After thorough debugging, I have concluded that the reason my GridView is not displaying any of my Images is because both of my OnSuccessListeners in getData() and getImage() from when I get the thumbnail and title from Firebase Storage are not successful yet.
I do all of this in my getData() method, which I call after the user selects their Google Place in onActivityResult. The method should instantiate a new ImageItem(Bitmap, String) but is returning a null ImageItem due to the onSucessListeners not being successful yet. Any ideas?
private void getData() {
imageItems = new ArrayList<>();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child((String) p.getName()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> iter = dataSnapshot.getChildren().iterator();
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference httpsReference = storage.getReferenceFromUrl(myUrl);
while (iter.hasNext()) {
hasImage = false;
hasTitle = false;
HashMap<String, String> m = (HashMap<String, String>) iter.next().getValue();
String v = m.get("url");
Log.d("url", v);
String bu = m.get("bucket");
Log.d("bucket", bu);
b = getImage(bu, v);
StorageReference iR = httpsReference.child(bu).child("thumb");
httpsReference.child(bu).getMetadata().addOnSuccessListener(new OnSuccessListener<StorageMetadata>() {
#Override
public void onSuccess(StorageMetadata storageMetadata) {
// Metadata now contains the metadata for 'images/forest.jpg'
t = storageMetadata.getCustomMetadata("title");
hasTitle = true;
Log.d("title", t);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.d("error", "ERROr");
// Uh-oh, an error occurred!
}
});
gridAdapter.data.add(new ImageItem(b, t, bu, v));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public Bitmap getImage(String bx, String vu) {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference httpsReference = storage.getReferenceFromUrl(myUrl);
String v = vu;
Log.d("url", v);
String bu = bx;
Log.d("bucket", bu);
StorageReference iR = httpsReference.child(bu).child("thumb");
final long ONE_MEGABYTE = 1024 * 1024;
iR.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
// Data for "images/island.jpg" is returns, use this as needed
b = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
hasImage = true;
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
return b;
}
}
****************UPDATE 1/7/2017*********************
private void getData() {
imageItems = new ArrayList<>();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child((String) p.getName()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> iter = dataSnapshot.getChildren().iterator();
FirebaseStorage storage = FirebaseStorage.getInstance();
final StorageReference httpsReference = storage.getReferenceFromUrl("gs://socialnetwork-4b0c9.appspot.com");
while (iter.hasNext()) {
hasImage = false;
hasTitle = false;
HashMap<String, String> m = (HashMap<String, String>) iter.next().getValue();
final String v = m.get("url");
Log.d("url", v);
final String bu = m.get("bucket");
Log.d("bucket", bu);
StorageReference iR = httpsReference.child(bu).child("thumb");
final long ONE_MEGABYTE = 1024 * 1024;
iR.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
// Data for "images/island.jpg" is returns, use this as needed
b = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
httpsReference.child(bu).getMetadata().addOnSuccessListener(new OnSuccessListener<StorageMetadata>() {
#Override
public void onSuccess(StorageMetadata storageMetadata) {
// Metadata now contains the metadata for 'images/forest.jpg'
t = storageMetadata.getCustomMetadata("title");
hasTitle = true;
gridAdapter.data.add(new ImageItem(b, t, bu, v));
Log.d("title", t);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.d("error", "ERROr");
// Uh-oh, an error occurred!
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
************************METHOD PERTAINING TO GRIDVIEW AND GRIDADAPTER*********
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(this, data);
p = place;
gridView = (GridView) findViewById(R.id.grid_View);
gridAdapter = new GridViewAdapter(this, R.layout.grid_item_layout);
getData();
gridView.setAdapter(gridAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ImageItem item = (ImageItem) parent.getItemAtPosition(position);
//Create intent
Intent intent = new Intent(PlaceActivity.this, VideoActivity.class);
intent.putExtra("bucket", item.getBucket());
intent.putExtra("dUrl", item.getdUrl());
//Start details activity
startActivity(intent);
}
});
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
// TODO: Handle the error.
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
}
}
This is a classic asynchronous programming issue:
var a = 1;
incrementAsync(function() {
a = 2;
});
console.log(a); // prints 1 because the function hasn't returned yet
You need to instead perform the action in the async function:
var a = 1;
incrementAsync(function() {
a = 2;
console.log(a); // prints 2 now
});
So I'd re-write your function as:
FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
FirebaseStorage mStorage = FirebaseStorage.getInstance();
mDatabase.getReference("...").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
ModelObject modelObject = storage.getValue(ModelObject.class);
// Or just download the object here...
mStorage.getReferenceFromUrl(modelObject.getUrl()).getMetadata().addOnSuccessListener(new OnSuccessListener<StorageMetadata>() {
#Override
public void onSuccess(StorageMetadata storageMetadata) {
String title = storageMetadata.getCustomMetadata("title");
gridAdapter.data.add(...);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
}
});
}
...
});

Categories

Resources