display image from firebase database in imageview - java

There are no direct answers to this question, I have tried various methods. I need an image stored in my Firebase database to be displayed in an ImageView.
This is the current code I have, which is not working:
mUsersDB_photoUrl.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String photoUrl = dataSnapshot.child("photoUrl").getValue(String.class);
try {
Picasso.with(DisplayActivity.this).load(photoUrl).placeholder(R.mipmap.ic_launcher).into(Photo);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Method for calling in username works:
mUsersDB_name.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Name.setText(dataSnapshot.getValue(String.class));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I'm not that great at all of this, I'm teaching myself Firebase. Pointers and guidance welcomed.

You are using Picasso, so I suggest you to use getDownloadUrl() while fetching image.
StorageReference storageRef = storage.getReference().child("profiles").child(myAccount.getUID()).child("profile");//reach out to your photo file hierarchically
storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.d("URI", uri.toString()); //check path is correct or not ?
Picasso.with(DisplayActivity.this).load(uri.toString()).into(imageView);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle errors
}
});

okey .. first set Log below this code line and check if photo url is valid or not.
String photoUrl = dataSnapshot.child("photoUrl").getValue(String.class);
then use glide to set your image to ImageView
Glide.with([CONTEXT]).load([IMAGE_URL]).into([IMAGE_VIEW]);
NOTE : if you want use Picasso then you have to pass your context to with([CONTEXT])

I ended up just changing my database reference. (First line of the code)
Works perfectly.
mUsersDB.child(user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String photoUrl = dataSnapshot.child("photoUrl").getValue(String.class);
try {
Picasso.with(DisplayActivity.this).load(photoUrl).placeholder(R.mipmap.ic_launcher).into(disPhoto);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Related

Why is the method of receiving data from firebase not working?

I registered such a method of receiving from folders in firebase, first I tried it in SwipeCard, it didn’t appear there, so I did the same test in a simple imageview and the data didn’t appear either. The link opens the photo. What is wrong in my code change and how to fix it? Thanks in advance
private void getUsermenwomInfo()
{
DatabaseReference reference= FirebaseDatabase.getInstance().getReference()
.child("User");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()&&snapshot.getChildrenCount()>0)
{
String name=snapshot.child("name").getValue().toString();
nameusercard.setText(name);
if (snapshot.hasChild("image")) {
String image = snapshot.child("image").getValue().toString();
Picasso.get().load(image).into(imageosnovnoe);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}

Selecting in RecyclerView and delete from firebase in java

I want to delete my document from firebase. But first I need to determine the document id. I tried to get document id:
docId = queryDocumentSnapshots.getDocuments().get(pos).getId();
Then, I just wanted to delete my document. But firebase works async so code doesnt work in 'if' statement. When we first click the button, docId variable is null or it takes the docId which was clicked before till the async code part done.
#Override
public void onBindViewHolder(#NonNull AdvertisementHolder holder, int position) {
imgUrl = publishedAdvertisements.get(position).getImgUrl();
holder.petName.setText(publishedAdvertisements.get(position).getPetName());
holder.petCategory.setText(publishedAdvertisements.get(position).getPetCategory());
Picasso.get().load(publishedAdvertisements.get(position).getImgUrl()).into(holder.petImage);
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseFirestore.collection("Pets").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(#NonNull QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()) {
System.out.println("bos döndü");
docId = queryDocumentSnapshots.getDocuments().get(pos).getId();
}
}
});
System.out.println(docId);
if (docId != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("Pets").document(docId)
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
publishedAdvertisements.clear();
getPublishedAnimals();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
}
notifyDataSetChanged();
}
});
You should structure your code so that any logic that depends on your asynchronous operation is executed or triggered within the response callback.
You can do something like this:
#Override
public void onBindViewHolder(#NonNull AdvertisementHolder holder, int position) {
imgUrl = publishedAdvertisements.get(position).getImgUrl();
holder.petName.setText(publishedAdvertisements.get(position).getPetName());
holder.petCategory.setText(publishedAdvertisements.get(position).getPetCategory());
Picasso.get().load(publishedAdvertisements.get(position).getImgUrl()).into(holder.petImage);
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseFirestore.collection("Pets").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(#NonNull QuerySnapshot queryDocumentSnapshots) {
// The asynchronous operation has successfully completed
// and returned a value to our 'onSuccess()' callback.
if (!queryDocumentSnapshots.isEmpty()) {
System.out.println("bos döndü");
docId = queryDocumentSnapshots.getDocuments().get(pos).getId();
System.out.println(docId);
// We can now use the value of docId.
if (docId != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("Pets").document(docId)
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
publishedAdvertisements.clear();
getPublishedAnimals();
// (1)
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
}
// I'm not sure how your RecyclerView is set up
// but I'm guessing you might want to move this call
// to 'notifyDataSetChanged()' to the section marked (1)
notifyDataSetChanged();
}
}
});
}
});
}

My Firebase is not retrieving data from Firebase Database

I have seen many other similar questions and also tried their method but still its not working.
My getFirebase function on a Click Listener :
private void getFirebase() {
firebaseDatabase = FirebaseDatabase.getInstance();
reference = firebaseDatabase.getReference().child("Questions/m1");
List<String> list = new ArrayList<>();
Log.d("QuizFragment", "getfirebase");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("QuizFragment", " Snapshots");
list.add(dataSnapshot.getValue().toString());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("QuizFragment", "error " + databaseError.toString());
}
});
Log.d("QuizFragment","debug");
}
My Logcat is showing getFirebase and then directly debug message.
I have seen many answer to wait for execution of SingleEvent but I have waited for many time still its not showing. Note : I am running app on emulator
addListenerForSingleValueEvent will get the data from the local disk cache.If you don't have any data in your cache you won't get any data.i believe that's why you could not get into onDataChange(). so first get data at least once like this
firebaseDatabase.getReference().child("Questions/m1")
.get()
.addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (!task.isSuccessful()) {
Log.e("firebase", "Error getting data", task.getException());
}
else {
Log.d("firebase", String.valueOf(task.getResult().getValue()));
}
}
});
//then use cache data.
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("QuizFragment", " Snapshots");
list.add(dataSnapshot.getValue().toString());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("QuizFragment", "error " + databaseError.toString());
}
});

Why does not array get updated on successful delete?

So I store a user with field called myMovies in firestore. I am able to successfully add a movie in this array but when I try to remove one it does not work and the logic behind the adding and removing is similar.
It does show me that the array is successfully updated but in firestore the element I delete is still there.
Here is my code:
#Override
public void removeMovie(Movie movie, FirebaseAddMovieListener listener) {
firebaseFirestore.collection("users").document(Objects.requireNonNull(mAuth.getCurrentUser()).getUid()).update("myMovies", FieldValue.arrayRemove(movie))
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
listener.onSuccess("SUCCESS");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
listener.onFailure(e.getMessage() + e + e.getLocalizedMessage());
}
});
}
Add Movie
#Override
public void addMovieToUserLibrary(Movie movie, FirebaseAddMovieListener
listener) {
firebaseFirestore.collection("users").document(Objects.requireNonNull(mAuth.getCurrentUser()).getUid()).update("myMovies", FieldValue.arrayUnion(movie))
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
listener.onSuccess("SUCCESS");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
listener.onFailure(e.getMessage() + e + e.getLocalizedMessage());
}
});
}
Database Structure

How to move Firebase child from one node to another in Android?

I am working on a project where user request for our valet services and on the other end valet accepts request.
I am using using Firebase as backend and on request customer uid is save on 'request' child.
When valet accepts request, customer uid should move from 'request' node to 'on progress' node.
How can i do that?
I recommend using this :
public void moveFirebaseRecord(Firebase fromPath, final Firebase toPath)
{
fromPath.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
toPath.setValue(dataSnapshot.getValue(), new Firebase.CompletionListener()
{
#Override
public void onComplete(FirebaseError firebaseError, Firebase firebase)
{
if (firebaseError != null)
{
System.out.println("Copy failed");
}
else
{
System.out.println("Success");
}
}
});
}
#Override
public void onCancelled(FirebaseError firebaseError)
{
System.out.println("Copy failed");
}
});
}
This come from this source : https://gist.github.com/katowulf/6099042 . I used it several times in my JavaEE code and also in my android app.
You pass your fromPath and toPath. This is a copy tought and not a move, so the original will remain at his original place too. If you would like to delete, you can do a set value on the fromPath just after the System.out.println("Success"); .
As of compile firebase-database:11.0.1, this is the same function with the new class references (https://firebase.google.com/support/guides/firebase-android July 05 2017)
private void moveGameRoom(final DatabaseReference fromPath, final DatabaseReference toPath) {
fromPath.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
toPath.setValue(dataSnapshot.getValue(), new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError firebaseError, DatabaseReference firebase) {
if (firebaseError != null) {
System.out.println("Copy failed");
} else {
System.out.println("Success");
}
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
If you want to perform a move which also erases the original, you might make use of the following snippet:
// In this piece of code, "fromPath" and "toPath" parameters act like directories.
private void removeFromFirebase(final DatabaseReference fromPath, final DatabaseReference toPath, final String key) {
fromPath.child(key).addListenerForSingleValueEvent(new ValueEventListener() {
// Now "DataSnapshot" holds the key and the value at the "fromPath".
// Let's move it to the "toPath". This operation duplicates the
// key/value pair at the "fromPath" to the "toPath".
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
toPath.child(dataSnapshot.getKey())
.setValue(dataSnapshot.getValue(), new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
Log.i(TAG, "onComplete: success");
// In order to complete the move, we are going to erase
// the original copy by assigning null as its value.
fromPath.child(key).setValue(null);
}
else {
Log.e(TAG, "onComplete: failure:" + databaseError.getMessage() + ": "
+ databaseError.getDetails());
}
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled: " + databaseError.getMessage() + ": "
+ databaseError.getDetails());
}
});
}
you can listen to value event on your child you want to copy it ,, and #onDataChange get reference of new child and set value dataSnapshot to this child like below sample code
FirebaseDatabase.getInstance().getReference("childYouWantToCopy")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
FirebaseDatabase.getInstance().getReference("ChildCopyTo").setValue(dataSnapshot.getValue());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

Categories