StorageException has occurred. Object does not exist at location - android

Im' using FirebaseUI with Recycler View and load images from Firebase Storage. I got an error above when I'm trying to replace the image with another one.
When I exit the fragment and back again, the image shows up, the error occurs in the same fragment where I'm changing the image.
I tried to use adapter.wait() and adapter.notifyDataSetChanged() but still get that error. The full error is this:
E/StorageException: StorageException has occurred.
Object does not exist at location.
Code: -13010 HttpResult: 404
E/StorageException: { "error": { "code": 404, "message": "Not Found. Could not get object" }}
java.io.IOException: { "error": { "code": 404, "message": "Not Found. Could not get object" }}
at bvk.a(:com.google.android.gms.DynamiteModulesC:424)
at bvk.a(:com.google.android.gms.DynamiteModulesC:1404)
at bve.onTransact(:com.google.android.gms.DynamiteModulesC:53)
at android.os.Binder.transact(Binder.java:380)
at com.google.android.gms.internal.zzans$zza$zza.zzuj(Unknown Source)
at com.google.android.gms.internal.zzanv.zza(Unknown Source)
at com.google.android.gms.internal.zzanm.zza(Unknown Source)
at com.google.android.gms.internal.zzanm.zzd(Unknown Source)
at com.google.firebase.storage.zzb.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
And my code is this:
protected void populateViewHolder(final ReportViewHolder viewHolder, final Report report, final int position) {
viewHolder.txtTitle.setText(report.title);
viewHolder.txtMessage.setText(report.message);
viewHolder.txtDate.setText(report.date);
viewHolder.txtuserName.setText(report.userName);
viewHolder.btnImg.setImageBitmap(null);
mStorage.child("Images/" + report.key + "/" + report.imageName).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.with(getContext()).load(uri).into(viewHolder.btnImg);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String Title=title.getText().toString();//get text from EditText
final String msg= message.getText().toString();
Query query= mDatabaseReference.child("user-reports/"+userID).orderByKey().equalTo(report.key);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot snapshot: dataSnapshot.getChildren())
{
snapshot.getRef().setValue(new Report(report.userName,report.date, Title, msg, report.key,
targetUri.getLastPathSegment()));
update_img(report.key, report.imageName);
mDatabaseReference.child("reports/"+ report.key).setValue(new Report(report.userName,report.date, Title, msg, report.key,
targetUri.getLastPathSegment()));
dialog.dismiss();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
And the function to update is this:
public void update_img(String key, String imageName)
{
// Get the data from an ImageView as bytes
imgView.setDrawingCacheEnabled(true);
imgView.buildDrawingCache();
Bitmap bitmap = imgView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data2 = baos.toByteArray();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setCancelable(false);
final View view = inflater.inflate(R.layout.progbar, null);
builder.setView(view);
TextView progTitle = (TextView) view.findViewById(R.id.progTitle);
progTitle.setText("wait to update");
final Dialog progDialog = builder.create();
progDialog.show();
if(targetUri != null) {
mStorage.child("Images/" + key + "/" + imageName).delete(); // Delete the old image of the user
StorageReference filepathRef = mStorage.child("Images/"+ key).child(targetUri.getLastPathSegment()); // Add the new image of the user
UploadTask uploadTask = filepathRef.putBytes(data2);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progDialog.cancel();
Toast.makeText(getContext(), "success", Toast.LENGTH_SHORT).show();
}
});
}
}
Hope you know what to do, because I really don't know what else I can do.

Related

Trying to get image from firebase so that user can set profile image but its blank

Im trying to allow users to click on the image item and choose a picture from their galley. this picture should then be pushed to firebase and added to the image view automatically but it is showing up blank after I close the application. I have tried numerous methods but cant seem to get it working. here is where i implement everything:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
ImageView imageView;
public static final int IMAGE_CODE = 1;
Uri imageUri;
private StorageReference storageReference;
private DatabaseReference databaseReference;
FirebaseUser user;
String userid;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) headerView.findViewById(R.id.profilepic);
user = FirebaseAuth.getInstance().getCurrentUser();
userid = user.getUid();
storageReference = FirebaseStorage.getInstance().getReference("Images");
databaseReference = FirebaseDatabase.getInstance().getReference("uploads").child(userid);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openimage();
}
});
profileImage();
}
private void profileImage(){
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Upload upload = dataSnapshot.getValue(Upload.class);
Glide.with(getApplicationContext()).load(upload.getUplaodUri()).into(imageView);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void openimage() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, IMAGE_CODE);
}
#TargetApi(Build.VERSION_CODES.M)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE) {
if (!Settings.canDrawOverlays(this)) {
// You don't have permission
checkPermission1();
} else {
// Do as per your logic
}
}
if (requestCode == IMAGE_CODE && resultCode == RESULT_OK && null != data && data.getData() != null) {
imageUri = data.getData();
Glide.with(this).load(imageUri).into(imageView);
fileUploader();
}
}
private String getFileExtension(Uri uri){
ContentResolver cr = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(cr.getType(uri));
}
private void fileUploader(){
if(imageUri != null){
StorageReference reference = storageReference.child(userid + ".jpeg");
reference.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Upload upload = new Upload(uri.toString());
databaseReference.setValue(upload).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
profileImage();
}
});
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
;;
}
});
}else{
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
}
Database Structure
Edit:
2020-05-03 15:55:51.232 25230-25407/com.example.carcrashdetection E/StorageException: StorageException has occurred.
Object does not exist at location.
Code: -13010 HttpResult: 404
2020-05-03 15:55:51.235 25230-25407/com.example.carcrashdetection E/StorageException: { "error": { "code": 404, "message": "Not Found. Could not get object", "status": "GET_OBJECT" }}
java.io.IOException: { "error": { "code": 404, "message": "Not Found. Could not get object", "status": "GET_OBJECT" }}
at com.google.firebase.storage.network.NetworkRequest.parseResponse(com.google.firebase:firebase-storage##19.1.1:433)
at com.google.firebase.storage.network.NetworkRequest.parseErrorResponse(com.google.firebase:firebase-storage##19.1.1:450)
at com.google.firebase.storage.network.NetworkRequest.processResponseStream(com.google.firebase:firebase-storage##19.1.1:441)
at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage##19.1.1:272)
at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage##19.1.1:286)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage##19.1.1:70)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage##19.1.1:62)
at com.google.firebase.storage.GetDownloadUrlTask.run(com.google.firebase:firebase-storage##19.1.1:76)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Also the image is in a navigation drawer and should be unique to each user. Can someone please tell me where I am going wrong?
You can do it like this:
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Upload upload = new Upload(uri.toString());
String uploadId = databaseReference.child(userid).push().getKey();
databaseReference.child(uploadId).setValue(upload);
}
});
Firebase Storage docs
And there is a problem in this line:
Glide.with(getApplicationContext()).load(upload).into(imageView);
upload is an object. You should use upload.getUploadUri()
if(dataSnapshot.exists()) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
Upload upload = ds.getValue(Upload.class);
Glide.with(getApplicationContext()).load(upload.getUplaodUri()).into(imageView);
}
}
You always see last uploaded image this way. If a user has an image you don't need to use uploadId.
Profile image:
Upload upload = new Upload(uri.toString());
databaseReference.setValue(upload);
and:
if(dataSnapshot.exists()) {
Upload upload = dataSnapshot.getValue(Upload.class);
Glide.with(getApplicationContext()).load(upload.getUplaodUri()).into(imageView);
}
more useful for you.

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) {
}
});
}

android: upload of pictures from facebook to fireabse returns 404

So, I code an android app, that takes pictures from facebook and stores them in a firebase db.
I use the graph-api to get the urls of the pictures, which works fine, since I can put the urls in a browser and the pictures appear.
Now I want to use an UploadTask to upload these pictures to firebase, and I get:
E/StorageException: StorageException has occurred.
Object does not exist at location.
Code: -13010 HttpResult: 404
11-07 19:58:00.894 8612-9182/com.finder E/StorageException: { "error": { "code": 404, "message": "Not Found. Could not get object" }}
java.io.IOException: { "error": { "code": 404, "message": "Not Found. Could not get object" }}
at com.google.firebase.storage.network.NetworkRequest.parseResponse(com.google.firebase:firebase-storage##16.0.4:455)
at com.google.firebase.storage.network.NetworkRequest.parseErrorResponse(com.google.firebase:firebase-storage##16.0.4:435)
at com.google.firebase.storage.network.NetworkRequest.processResponseStream(com.google.firebase:firebase-storage##16.0.4:426)
at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage##16.0.4:280)
at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage##16.0.4:294)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage##16.0.4:65)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage##16.0.4:57)
at com.google.firebase.storage.GetDownloadUrlTask.run(com.google.firebase:firebase-storage##16.0.4:71)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Here is my upload method:
static class UploadPicAsyncWrapperTask extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... strings) {
String picsFolder = strings[0];
String id = strings[1];
final String url = strings[2];
final String profilepicNodeName = strings[3];
final String picsNodeName = strings[4];
final StorageReference filePathRoot = FirebaseStorage.getInstance().getReference().child(picsFolder).child(FirebaseAuth.getInstance().getCurrentUser().getUid());
final StorageReference filePath;
filePath = filePathRoot.child(id);
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// File already exists
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
final UploadTask uploadTask;
try (InputStream is = new URL(Uri.encode(url)).openStream()) {
uploadTask = filePath.putStream(is); //Uri.fromFile(new File(url)); //Uri.parse(url) new ByteArrayInputStream()
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
if (profilePicName == null) {
mUserDatabase.child(profilepicNodeName).setValue(uri.toString());
profilePicName = uri.toString();
} else {
mUserDatabase.child(picsNodeName).child(Helper.imageUrlToFirebasePath(uri.toString())).setValue(uri.toString());
}
--picsRemaining;
}
});
}
});
} catch (MalformedURLException e) {
// TODO or not todo whatever
} catch (IOException e) {
// TODO or not todo whatever
}
}
});
return null;
}
}
And this is how the asyncTask is called:
new UploadPicAsyncWrapperTask().execute(getString(R.string.firebase_storage_pics_folder), id, url, getString(R.string.firebase_database_profilepic_node_name), getString(R.string.firebase_database_pics_node_name));
Anybody any idea why firebase can't catch the pictures?
So, there is nothing wrong with my code above. Since I can't ask Firebase if a picture was already uploaded to the database, I ask firebase to give me the downloadUrl of that picture and in onFailureListener, I upload the picture.
What I didn't know is, that onFailureListener implicit logs the error message above.

Firebase database download chat data

I'm trying to download data for my chat from Firebase database(structure of data is bellow and It is recommended structure from official Firebase web).
"chats": {
"one": {
"lastMessage": "ghopper: Relay malfunction found. Cause: moth.",
"timestamp": 1459361875666
},
"two": { ... }
},
"members": {
"one": {
"member1": "cxgF3EddyMWiYybXdMsYwu5YQsn1",
"member2": "jdxBDm5MXBdX4zfGoEp9hgHqscn2"
};
"two": {
"member1": "cxgF3EddyMWiYybXdMsYwu5YQsn1",
"member2": "yGpTEPDfChVmUeEkzvCCY6IjQnA2"
};
},
"messages": {
"one": {
"m1": {
"name": "cxgF3EddyMWiYybXdMsYwu5YQsn1",
"message": "The relay seems to be malfunctioning.",
"timestamp": 1459361875337
},
"m2": {
"name": "jdxBDm5MXBdX4zfGoEp9hgHqscn2",
"message": "Yes.",
"timestamp": 1459361875689
},
},
"two": { ... }
}
Now I'm trying just to check if I(as logged user) am involved in the conversation and download just the last message under chats/and particular chat number. Also I have to download a profile picture of another user that is involved in this chat and then add last message and this picture to PrefenceScreen.
Here is code:
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("members");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final ArrayList<String> arrayList = new ArrayList<>();
for (final DataSnapshot snapshot : dataSnapshot.getChildren()) {
GenericTypeIndicator<Map<String, Object>> m = new GenericTypeIndicator<Map<String, Object>>() {
};
Map<String, Object> map = snapshot.getValue(m);
if (map.get("member1").equals(myUID)) {
arrayList.add(snapshot.getKey());
arrayList.add(map.get("member2").toString());
} else if (map.get("member2").equals(myUID)) {
arrayList.add(snapshot.getKey());
arrayList.add(map.get("member1").toString());
}
}
mStorage = FirebaseStorage.getInstance().getReference();
for (int i=0, y=1; y<arrayList.size(); i+=2, y+=2) {
Log.i("Chat", arrayList.get(i));
StorageReference storageReference = mStorage.child("photos").child(arrayList.get(y));
try {
final File localFile = File.createTempFile("images", "jpg");
final int finalI = i;
StorageTask<FileDownloadTask.TaskSnapshot> taskSnapshotStorageTask = storageReference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Bitmap bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath());
Resources res = getResources();
final RoundedBitmapDrawable dr =
RoundedBitmapDrawableFactory.create(res, Bitmap.createScaledBitmap(bitmap, 150, 150, false));
dr.setCornerRadius(500);
DatabaseReference myRef2 = database.getReference("chats").child(arrayList.get(finalI)).child("lastMessage");
myRef2.addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String message = dataSnapshot.getValue(String.class);
Log.d("TAG", "Value is: " + message);
PreferenceScreen screen = getPreferenceManager().createPreferenceScreen(getActivity());
Preference preference = new Preference(getActivity());
preference.setTitle(message);
preference.setKey("Hej celkom v pohode");
preference.setIcon(dr);
preference.setSelectable(true);
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(getActivity(), ScrollingActivity.class);
startActivity(intent);
return false;
}
});
screen.addPreference(preference);
setPreferenceScreen(screen);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("TAG", "Failed to read value.", error.toException());
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
} catch (IOException e ) {
}
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("TAG", "Failed to read value.", error.toException());
}
});
The code is almost doing what It should. The problem is that it all the time adds just one Prefence because the screen.addPreference(preference); and setPreferenceScreen(screen); methods are inside onDataChange. Is there a way how to use methods after files are downloaded?
And also I think this code is messy and there must by simplier way to download all the data. You would be very thankful if you can help me with this. Thanks.

Getting 'StorageException' even after setting my rules as public. Please see details

I have stored some images on Firebase and when I am trying to download them, I'm getting following error: E/StorageException: StorageException has occurred. User does not have permission to access this object. Code: -13021 HttpResult: 403. I am using Google Authentication too.
Here's how I am uploading image:
StorageReference storageReference = firebaseStorage.getReferenceFromUrl("gs://appname-e2a32.appspot.com").child("hImage");
UploadTask uploadTask = storageReference.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(getBaseContext(), exception.getMessage(), Toast.LENGTH_SHORT).show();
// Handle unsuccessful uploads
}
}).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.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
savingHelpRequest.dismiss();
Toast.makeText(getBaseContext(), "image uploaded", Toast.LENGTH_SHORT).show();
}
});
Here's how I am trying to download it:
FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
storageReference = firebaseStorage.getReferenceFromUrl("gs://appname-e2a32.appspot.com").child("hImage");
storageReference.getBytes(Long.MAX_VALUE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
// Use the bytes to display the image
ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
bytes = baoStream.toByteArray();
bmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
Toast.makeText(getBaseContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
});
Here's the security rules:
service firebase.storage {
match /b/appname-e2a32.appspot.com/o {
match /{allPaths=**} {
allow read, write;
}
}
}
Please let me know how can I get rid of this error and download the images successfully?
In Android 6.0 or API 23 we have to get runtime permission from user only declaring permission in manifest is not enough.
public class SampleActivity extends AppCompatActivity {
private static final int REQUEST_RUNTIME_PERMISSION = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
checkPremission();
//SomeTask(); which need permission will become like below in API 23
}
void checkPremission() {
//select which permission you want
final String permission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
if (ContextCompat.checkSelfPermission(SampleActivity.this, permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(SampleActivity.this, permission)) {
} else {
ActivityCompat.requestPermissions(SampleActivity.this, new String[]{permission}, REQUEST_RUNTIME_PERMISSION);
}
} else {
// you have permission go ahead launch service
SomeTask();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_RUNTIME_PERMISSION:
final int numOfRequest = grantResults.length;
final boolean isGranted = numOfRequest == 1
&& PackageManager.PERMISSION_GRANTED == grantResults[numOfRequest - 1];
if (isGranted) {
// you have permission go ahead
SomeTask();
} else {
// you dont have permission show toast
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
void SomeTask() {
FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
storageReference = firebaseStorage.getReferenceFromUrl("gs://appname-e2a32.appspot.com");
storageReference.getBytes(Long.MAX_VALUE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
// Use the bytes to display the image
ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
bytes = baoStream.toByteArray();
bmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
Toast.makeText(getBaseContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}

Categories

Resources