data from firebase database is not visible into recycler view - android

I want to retrieve images frm storage to recyclerview but it is not working
mFirestore.collection("Users").whereEqualTo("special", s).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
final SpecializedDoctorNameFragment S = new SpecializedDoctorNameFragment();
final List<DoctorNameStructure> eventList = new ArrayList<>();
for (final DocumentSnapshot doc : task.getResult()) {
String id = doc.getString("id");
final DoctorNameStructure e = new DoctorNameStructure();
e.setName(doc.getString("name"));
e.setAddress(doc.getString("address"));
e.setConsultancy(doc.getString("consultancyFees"));
e.setSpecialization(doc.getString("special"));
storageReference.child("images/" + id).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
uploadImages();
e.setImage(uri.toString());
eventList.add(e);
}
});
}
NameAdapter recyclerViewAdapter = new NameAdapter(getContext(), eventList, mFirestore);
recyclerName.setAdapter(recyclerViewAdapter);
}
}
});

Listener is executing after your setAdapter. Change the logic of filling the list.

Related

Firestore RecyclerView - Variable null

When I save the value that it retrieves from firestore when exiting the function, this value is null.
#Override
protected void onBindViewHolder(#NonNull ViewDonationHolder holder, int position, #NonNull DonationsClass model) {
beneficiaryUID = model.getBeneficiaryUid();
DocumentReference docRef = db.collection("beneficiaries").document(beneficiaryUID);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
beneficiaryFirstName = document.getString("firstName");
beneficiaryLastName = document.getString("lastName");
Log.e("fullName", fullNameBeneficiary);
} else {
}
} else {
}
fullNameBeneficiary = beneficiaryFirstName + " - " + beneficiaryLastName;
}
});
holder.txtFullname.setText(fullNameBeneficiary);
holder.txtDate.setText(model.getDate());
holder.txtType.setText(model.getType());
holder.txtQuantity.setText(model.getQuantity());
holder.txtDescription.setText(model.getDescription());
}
When holder.txtFullname.setText(fullNameBeneficiary) in interface is empty
Have you tried like this -
DocumentReference docRef = db.collection("beneficiaries").document(beneficiaryUID);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
beneficiaryFirstName = document.getString("firstName");
beneficiaryLastName = document.getString("lastName");
fullNameBeneficiary = beneficiaryFirstName + " - " + beneficiaryLastName;
Log.e("fullName", fullNameBeneficiary);
}
}
}
});

Retrieve images in recyclerview from Firebase Firestore

I am trying to retrieve images from Firebase Firestore. I am able to retrieve text in RecyclerView successfully however I'm not sure how to retrieve the images.
I had a look at similar questions unfortunately none helped.
ListActivity :
//initialize firestore
db = FirebaseFirestore.getInstance();
//initialize views
mRecyclerView = findViewById(R.id.resultRecycle);
//set recycler view properties
mRecyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
//show data in recycler view
showData();
}
private void showData() {
db.collection("Item")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
//called when data is retrieved
//show data
for(DocumentSnapshot doc: task.getResult()){
Model model = new
Model(doc.getString("id"),
doc.getString("Title"),
doc.getString("Location"),
//STUCK HERE
);
modelList.add(model);
}
//adapter
adapter = new CustomAdapter(ListActivity.this, modelList);
//set adapter to recycler view
mRecyclerView.setAdapter(adapter);
}
});
CustomAdapter :
public void onItemClick(View view, int position) {
//this will be called when user clicks an item
//show data on toast when clicking
String title = modelList.get(position).getTitle();
String location = modelList.get(position).getLocation();
String url = modelList.get(position).getUrl();
}
#Override
public void onItemLongClick(View view, int position) {
//this will be called when user clicks long item
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int i) {
//bind views /set data
holder.mTitle.setText(modelList.get(i).getTitle());
holder.mLocation.setText(modelList.get(i).getLocation());
Picasso.get().load(modelList.get(i).getUrl()).into(holder.mUrl);
}
Please see the image below link, thank you
Use fileuploader code to upload the image in Firebase Database.
But make sure you put the Fileuploader run on the click of any button. Or it will throw nullpointer Exception if your edittext are empty.
private void Fileuploader(){
if(imguri != null ) {
StorageReference ref = mStorageRef.child("Item");
Toast.makeText(UploadActivity.this, "Upload in progress", Toast.LENGTH_LONG).show();
ref.putFile(imguri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(UploadActivity.this, "Image uploaded successfully!", Toast.LENGTH_LONG).show();
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
saveData(downloadUrl);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
The function will automatically start when file upload successfully done.
private void saveData(Uri imguri) {
Map<String, String> data = new HashMap<>();
EditText title = findViewById(R.id.etv_1);
EditText shortDesc = findViewById(R.id.etv_2);
TextView location = findViewById(R.id.etv_3);
String eTitle = title.getText().toString();
String eShortDesc = shortDesc.getText().toString();
String eLocation = location.getText().toString();
String eUrl = imguri.toString();
userid = FirebaseAuth.getInstance().getUid();
getCate();
data.put("Img", eUrl);
data.put("Title", eTitle);
data.put("Location", eLocation);
data.put("Short Description", eShortDesc);
data.put("Category", cate );
data.put("id", userid);
db.collection("Item").add(data);
Toast.makeText(this, "Successfully saved your item", Toast.LENGTH_SHORT).show();
Intent i = new Intent(this, Home.class);
startActivity(i);
}
I have an best example of Retrieve images in recyclerview from Firebase Firestore ..link is here ...
https://www.simplifiedcoding.net/firebase-storage-example/
in this website given best hint and tutorial here.. please do follow step by step ...
Hey I think this may hep using Picasso
Picasso.with(context).load(ImageURL).into(imageView);

How can I retrieve images from Firebase Storage rather than Firestore, to create an image slider in Android studio?

My code to display images in an image slider(slideshow) is working when I retrieve images from Firestore, HOWEVER I am trying to retrieve it from Firebase storage instead and it's giving me a hard time.
This is my working code for retrieving from Firestore.
public void update(View view) {
DocumentReference user=db.collection("FILES").document("images");
user.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful())
{
DocumentSnapshot doc=task.getResult();
//For Image1
StringBuilder img1=new StringBuilder("");
img1.append(doc.get("image1"));
image1.setText(img1.toString());
String image1url=image1.getText().toString();
Picasso.get().load(image1url).into(imageView1);
//For Image2
StringBuilder img2=new StringBuilder("");
img2.append(doc.get("image2"));
image2.setText(img2.toString());
Stringimage2url=image2.getText().toString();
Picasso.get().load(image2url).into(imageView2);
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ImageSlider.this, "Falied", Toast.LENGTH_SHORT).show();
}
});
}
I tried this to get it from firebase storage but 'get()' is showing up as an error in
get().addOnCompleteListener(new OnCompleteListener
Any ideas?
get() is not working when I try the following:
public void update(View view) {
DatabaseReference mDatabaseRef = FirebaseDatabase.getInstance().getReference().child("uploads").child("uploads");
mDatabaseRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
private void getData () {
DatabaseReference reference;
reference.child("whatever").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Model model = dataSnapshot.getValue(Model.class);
imageURL = model.getUrl();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Change addListenerForSingleValueEventif you need to read value more than once and values with your values..

ArrayList<String> method return an empty array getting data from firebase

I have a problem with my return..since the data required a few second to get downloaded, when the method return the ArrayList, it's still empty. In fact if I put that lines of code Log.v("array", String.valueOf(partecipantsArrayList));
first it print 0 and then it print the array filled. So I have to wait before the return statement..is there any way to achieve this?
public ArrayList<String> getPartecipantsList(){
String email = getEmail();
String groupTitle = getTitleBar();
DocumentReference docRef = db.collection("users").document(email).collection("Group").document(groupTitle);
docRef.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
DocumentSnapshot document = task.getResult();
//Extracting participants ArrayList from the document
for(Object item : task.getResult().getData().values()) {
String[] values = String.valueOf(item).replace("[", "").replace("]", "").split(",");
for (String value : values){
partecipantsArrayList.add(value);
}
}
partecipantsArrayList.remove(String.valueOf("["));
partecipantsArrayList.remove(partecipantsArrayList.size() - 1);
Log.v("array", String.valueOf(partecipantsArrayList));
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
return partecipantsArrayList;
}
It is async task you can adjust this code like below.
change the signature of that method to return void
public void getPartecipantsList();
do next action after the on complete
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
...............
partecipantsArrayList.remove(String.valueOf("["));
partecipantsArrayList.remove(partecipantsArrayList.size() - 1);
Log.v("array", String.valueOf(partecipantsArrayList));
// do your action by calling next method from here
//eg: setResultFromArray(partecipantsArrayList);
}
do fail action or call method when failures in side the onFailure.
#Override
public void onFailure(#NonNull Exception e) {
//......
}

How to make an ArrayList with two Firestore collection?

I would like to load RecyclerView from my firestone db. My firestore structure is like this:
users(collection) -> user_id(document) -> books(collection)
books(collection) -> book_id(document)
Added: Database structure images
enter image description here
enter image description here
enter image description here
What I want to do is getting the book_ids of current_user into an ArrayList<String> then with this arraylist and for each loop, I want to load books into another ArrayList<Book>. I am getting the “ArrayList book_ids” of the current user. (I want to show the books which were added by current user)
The problem is with this array list I can not manage to get ArrayList<Book>books. I will send this array list to recycler view adapter.
public void getBookIdsFromDb(){
final ArrayList<String> myBookIds = new ArrayList<String>();
CollectionReference bookIdRef = db.collection(getString(R.string.collection_users)).document(userId)
.collection(getString(R.string.colleciton_books));
bookIdRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull com.google.android.gms.tasks.Task<QuerySnapshot> task) {
if (task.isSuccessful()){
for (DocumentSnapshot ds : task.getResult()){
myBookIds.add(ds.getString("book_id"));
myBookIds.size());
}
Log.d(TAG, "onComplete: myBookIds.size" + myBookIds.size());
if (myBookIds.size()>0){
getMyBooksFromDb(myBookIds);
//this works
}
}
}
});
}
public void getMyBooksFromDb(ArrayList<String> bookIds){
final ArrayList<String> myBooksIds =bookIds;
final ArrayList<Book> myBooks = new ArrayList<Book>();
CollectionReference dbRef = db.collection(getString(R.string.colleciton_books));
for (int i =0; i<myBooksIds.size();i++){
Log.d(TAG, "getMyBooksFromDb: myBookIds in for " + myBooksIds.size());
dbRef.document(myBooksIds.get(i)).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot != null){
Book myBook = documentSnapshot.toObject(Book.class);
myBooks.add(myBook);
//Can not get out of this array from for loop
}
}
});
}
}
//I tried to make a nested query below but no result :(
public void getBookListFromDb(){
final ArrayList<String> myBookIds = new ArrayList<String>();
CollectionReference bookIdRef = db.collection(getString(R.string.collection_users)).document(userId)
.collection(getString(R.string.colleciton_books));
bookIdRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull com.google.android.gms.tasks.Task<QuerySnapshot> task) {
final ArrayList<Book> myBooks = new ArrayList<Book>();
if (task.isSuccessful()){
for (DocumentSnapshot ds : task.getResult()){
myBookIds.add(ds.getString("book_id"));
myBookIds.size();
}
Log.d(TAG, "onComplete: myBookIds.size" + myBookIds.size());
if (myBookIds.size()>0){
CollectionReference colRef = db.collection(getString(R.string.colleciton_books));
for (int i=0; i< myBookIds.size(); i++){
colRef.document(myBookIds.get(i)).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull com.google.android.gms.tasks.Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
DocumentSnapshot ds = task.getResult();
Book myBook = ds.toObject(Book.class);
myBooks.add(myBook);
}
Log.d(TAG, "onComplete: myBooks.size(i) "+ myBooks.size());
}
});
Log.d(TAG, "onComplete: myBooks.size() in for "+ myBooks.size());
}
Log.d(TAG, "onComplete: myBooks.size() "+ myBooks.size());
}
}
}
});
}'
You cannot achieve what you want in this way because both methods, onComplete() and onSuccess() have an asynchronous behaviour. This means that by the time you are calling getMyBooksFromDb() method, you haven't finished getting the data from the database. So to solve this, you need to move all your logic from your getMyBooksFromDb() method inside onComplete() method. This is the flow:
add a complete listener on your bookIdRef
get all the book_id you have in your database by iteration using the foor loop
inside onComplete() method use the book_id to create your CollectionReference for finding the books.
Move the declaration of your ArrayList<Book> inside onSuccess() method.
Do what you want to do with your list or with your Book objects.
So the solution is to use nested queries as explained above. So please use the following code:
CollectionReference bookIdRef = db.collection(getString(R.string.collection_users))
.document(userId)
.collection(getString(R.string.colleciton_books));
bookIdRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull com.google.android.gms.tasks.Task<QuerySnapshot> task) {
if (task.isSuccessful()){
for (DocumentSnapshot ds : task.getResult()) {
String bookId = myBookIds.add(ds.getString("book_id"));
dbRef.document(bookId).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot != null){
Book myBook = documentSnapshot.toObject(Book.class);
Log.d("TAG", myBoog.getBookName());
}
}
});
}
}
}
});
Step -1:
Create a Model Class of Userbook.java and Book.java
Userbook.Java
String book_id;
Book book;
//create getter and setter for that.
As per you code set value:
UserBook userbook = new UserBook();
final ArrayList<UserBook> books = new ArrayList<String>();
public void getBookIdsFromDb(){
CollectionReference bookIdRef = db.collection(getString(R.string.collection_users)).document(userId)
.collection(getString(R.string.colleciton_books));
bookIdRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull com.google.android.gms.tasks.Task<QuerySnapshot> task) {
if (task.isSuccessful()){
for (DocumentSnapshot ds : task.getResult()){
userbook.setBook_id(ds.getString("book_id"));
}
Log.d(TAG, "onComplete: myBookIds.size" + myBookIds.size());
if (myBookIds.size()>0){
getMyBooksFromDb(myBookIds);
//this works
}
}
}
});
}
public void getMyBooksFromDb(ArrayList<String> bookIds){
CollectionReference dbRef = db.collection(getString(R.string.colleciton_books));
for (int i =0; i<myBooksIds.size();i++){
Log.d(TAG, "getMyBooksFromDb: myBookIds in for " + myBooksIds.size());
dbRef.document(myBooksIds.get(i)).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot != null){
Book myBook = documentSnapshot.toObject(Book.class);
userbook.setBook_id(myBook);
//Can not get out of this array from for loop
}
}
});
}
}
//after all this add obj to list
books.add(userbook);
I hope you will get the result. or else ping here.

Categories

Resources