Firebase Storage and Image View - java

I want to get image from Firebase Storage and than show at Image View. I trying this code but not working. Always I getting my "ERROR" toast message.
App is opening but I dont see my JPEG.
** I found one way but it is not enough for me.
If I delete 'com.google.firebase:firebase-auth:19.3.2' from build gradle, this code working.
I need FirebaseAuth because I have User login and logout page.
Do you know another way for Firebase storage and image ?
Thank you for help.
enter image description here
private StorageReference mStorageReference;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vardiya);
mStorageReference=FirebaseStorage.getInstance().getReference().child("vardiyaandroid.jpeg");
final File localfile;
try {
localfile = File.createTempFile("vardiyaandroid","jpeg");
mStorageReference.getFile(localfile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(vardiya.this,"Resim Hazır",Toast.LENGTH_LONG).show();
Bitmap bitmap = BitmapFactory.decodeFile(localfile.getAbsolutePath());
(imageView=findViewById(R.id.imageView)).setImageBitmap(bitmap);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(vardiya.this,"ERROR",Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
}

I found my false.
You will change this code
mStorageReference=FirebaseStorage.getInstance().getReference().child("vardiyaandroid.jpeg");
with
mStorageReference=FirebaseStorage.getInstance().getReferenceFromUrl("gs://YOURAPPID.appspot.com/vardiyaandroid.jpeg");
StorageReference pathreferance =mStorageReference.child("vardiyaandroid.jpeg");
and the storege rules must be this:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, writ, auth: if true;
}
}
}

Related

Downloading image from Firebase storage into imageview on android studio java

I am trying to download an image from Firebase storage into imageView on an android studio app using Java. I have looked through stackoverflow for over 6 hours so I have most likely read any "similiar" questions. I have tried various methods but the most suggested and what appeared to be the most simplest is using glide. I can't get it to work and I can't find the error. I even put in a regular google images link to try and it still shows blank.
the dependencies I have added
implementation'com.firebaseui:firebase-ui-storage:6.4.0'
implementation'com.github.bumptech.glide:glide:4.12.0'
annotationProcessor'com.github.bumptech.glide:compiler:4.12.0'
The code I have used
ImageView imageView = findViewById(R.id.resultImage);
Glide.with(this).load("string of image").into(imageView);
I also tried this code
StorageReference ref = storage.getReferenceFromUrl("urlforimage");
// ImageView in your Activity
ImageView imageView = findViewById(R.id.uploadedImage);
// Download directly from StorageReference using Glide
Glide.with(this /* context */)
.load(ref)
.into(imageView);
And this code
public class Breed_Search_Page1Activity extends AppCompatActivity {
ImageView rImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_breed__search__page1);
rImage = findViewById(R.id.rImage);
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = firebaseDatabase.getReference();
DatabaseReference getImage = databaseReference.child("image");
getImage.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String link = dataSnapshot.getValue(String.class);
Picasso.get().load(link).into(rImage);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// we are showing that error message in toast
Toast.makeText(Breed_Search_Page1Activity.this, "Error Loading Image", Toast.LENGTH_SHORT).show();
}
});
}
}
Update - I have it working with the code below but wondering is there a way to display it from Firebase Storage using just the name of the file? As I am uploading an image from my laptop that I want to display in the app as quickly as possible so if I could code it so that it has the file name that I am going to use when uploading it would display once uploaded without having to manually change anything
ImageView image = (ImageView) findViewById(R.id.rImage);
String url = "https//...";
Glide.with(getApplicationContext()).load(url).into(image);
My logcat after adding listeners
2021-04-27 10:35:01.780 14347-14576/com.example.woofsapp E/StorageException:
StorageException has occurred.
Object does not exist at location.
Code: -13010 HttpResult: 404
2021-04-27 10:35:01.781 14347-14576/com.example.woofsapp 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(NetworkRequest.java:434)
at com.google.firebase.storage.network.NetworkRequest.parseErrorResponse(NetworkRequest.java:451)
at com.google.firebase.storage.network.NetworkRequest.processResponseStream(NetworkRequest.java:442)
at com.google.firebase.storage.network.NetworkRequest.performRequest(NetworkRequest.java:272)
at com.google.firebase.storage.network.NetworkRequest.performRequest(NetworkRequest.java:286)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(ExponentialBackoffSender.java:70)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(ExponentialBackoffSender.java:62)
at com.google.firebase.storage.GetDownloadUrlTask.run(GetDownloadUrlTask.java: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:764)
The code that gives the logcat errors - note I do have the MyAppGlideModule copied directly from documentation
ImageView image = findViewById(R.id.rImage);
StorageReference storageReference =
FirebaseStorage.getInstance().getReference("Images/dogs.jpg");
storageReference.child("dogs.jpg").getDownloadUrl().addOnSuccessListener(new
OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Got the download URL for 'users/me/profile.png'
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
In my app, I've something like this:
StorageReference storageReference = FirebaseStorage.getInstance().getReference("FolderName/photoName.format");
I'm using the path with file's name.
For reference, check the official documentation - Download files with Cloud Storage on Android.

Recycler view mixing up the contents of its items

I'm using a recycler view to load a list of posts made by and organization. I've used firestore as the backend.
For loading the image I'm first getting the download Url from storage reference and then using Glide to load image in to the image view.
The issue i'm facing is that since a call to the storage reference is an asynchronous one, by the time it gets the download uri from the server the position of the adapter in OnBindviewHolder is already changed Therefore image gets mixed up.
I've provided the OnBindViewHolder code and the method where i get the download url
#Override
public void onBindViewHolder(#NonNull final studentFavouriteUniversityPosts.MyViewHolder holder, int position) {
if(postsList.get(holder.getAdapterPosition()).getImageUrl()!=null &&
!postsList.get(holder.getAdapterPosition()).getImageUrl().isEmpty()){
holder.setPostImage(holder.getAdapterPosition());
}
}
public void setPostImage(int position) {
postImage.setVisibility(View.VISIBLE);
placeholder.placeholder(R.color.white);
//Getting the download uri from the Fire store storage and displaying it using glide.
storageReference.child(postsList.get(position).getImageUrl())
.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Log.d("URI",uri.toString());
Glide.with(context).applyDefaultRequestOptions(placeholder).load(uri).into(postImage);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("ERROR","err loading image file");
}
});
}
Can anyone of you help me out on this?
EDIT
I changed the structure a bit. So instead of running the storage reference task in adapter, i'm storing the dowload url in the object. Thus the setPostImage method only has the Glide part.
So the method looks like this
public void setPostImage(String downloadURL) {
postImage.setVisibility(View.VISIBLE);
Glide.with(context).applyDefaultRequestOptions(placeholder).load(downloadURL).into(postImage);
}
Still i'm getting this issue. I dont know how to resolve it
First get the list of urls from firestore from the activity or fragment where you are
setting the adapter
1. public void getImages() { storageReference.child("the child name")
.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Log.d("URI",uri.toString());
adapter.imagesRetrieved();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("ERROR","err loading image file");
}
});
}
2. Then inside on success listener pass the group of values to the adapter method from the success listener and define the method inside the adapter
public void imagesRetreived() {
notifyDataChanged(images);
}
private void notifyDataChanged(Images images) {
this.images = images;
notifydatasetchanged(); //this one is recycler view inbuilt method
}

Storage, FireBase, Android - StorageException has occurred. Object does not exist at location [duplicate]

I already tried using Glide.with(opDetails.this).using(new FirebaseImageLoader()).load(uri).into(imgPhoto1); but had some problems with .using().
I am now trying to use picasso. Althougt the compiler shows no error, no image is displayed to the ImageView and i cant understand why.
storage = FirebaseStorage.getInstance();
storageRef = storage.getReference();
storageRef.child("images/4736af35-608d-4b97-95ba-029ef471c5eb.png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.with(opDetails.this).load(uri).into(imgPhoto1);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
}
Update:
Firebase Storage Image
Storage Rules
Thanks in advance.
Try this:-
storageRef.child("images/4736af35-608d-4b97-95ba-029ef471c5eb").getDownloadUrl().addOnSuccessListener....

Correct way to check internet connection with AsyncTask and output WebView content?

My app is based on a fullscreen WebView and I wanted to show a local file if there is no internet connection, otherwise load my website. I never used AsyncTask before and tried the following:
MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Check Internet Connection
mWebView = (WebView) findViewById(R.id.activity_main_webview);
HostAvailabilityTask hostAvailable = new HostAvailabilityTask(this);
boolean online = hostAvailable.isOnline();
if (!online) {
// Loading local html file into web view
mWebView.loadUrl("file:///android_asset/sample.html");
} else {
// load my website here
HostAvailabilityTask:
public class HostAvailabilityTask extends AsyncTask<String, Void, Boolean> {
private MainActivity main;
public HostAvailabilityTask(MainActivity main) {
this.main = main;
}
protected Boolean doInBackground(String... params) {
return isOnline(); // Correct way using AsyncTask?
}
protected void onPostExecute(Boolean... result) {
if(!result[0]) {
return; // What to return?
}
}
public boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
}
catch (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }
return false;
}
}
As you can see I'm just calling the method isOnline(); inside the MainActivity and think this is the wrong way to use a AsyncTask? I just want to make sure to do it "the right way". I also don't know what would be logical to return in onPostExecute in that case?
As stated before I never used AsyncTask, so I hope someone could help me out. I also commented some lines in my code to make my confusion clear.
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error){
//Your code to do
Toast.makeText(getActivity(), "Your Internet Connection May not be active Or " + error , Toast.LENGTH_LONG).show();
}

what is effective way to send media like images,.. using my android application

i am new in android java programming and i need to create an activity which will help a user to send media like image,video, audio,.. to another user or to the group of users so that the action of sending would be super fast like whatsapp does , but i don't know which way i can follow and what i am required to know and to have . i am using android studio 2.if there is some tutorials or source codes please share with me the link. thanks for yr highest consideration to my question.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText MyText=(EditText) findViewById(R.id.text);
Button send=(Button) findViewById(R.id.button1);
ImageView attach =(ImageView) findViewById(R.id.attach);
button.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String txt =MyText.getText().toString();
...
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
...
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Try Firebase https://firebase.google.com/
Use Firebase Storage and also Firebase Realtime Database
See https://firebase.google.com/docs/storage/android/upload-files
Small sample code from above link
Upload from a local file
You can upload local files on the device, such as photos and videos from the camera, with the putFile() method. putFile() takes a File and returns an UploadTask which you can use to manage and monitor the status of the upload.
Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = storageRef.child("images/"+file.getLastPathSegment());
uploadTask = riversRef.putFile(file);
// Register observers to listen for when the download is done or if it fails
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) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
}
});

Categories

Resources