Firestore RecyclerView - Variable null - android

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

Related

Get array from Firestore Kotlin [duplicate]

I am using Cloud Firestore and there is a array data in field. So how can I get data from array individually?
To get the values within ip_range array, please use the following lines of code:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
rootRef.collection("aic").document("ceo").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Map<String, Object> map = document.getData();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getKey().equals("ip_range")) {
Log.d("TAG", entry.getValue().toString());
}
}
}
}
}
});
Another approach would be:
rootRef.collection("products").document("06cRbnkO1yqyzOyKP570").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
ArrayList<String> list = (ArrayList<String>) document.get("ip_range");
Log.d(TAG, list.toString());
}
}
}
});
In both cases, the output in your logcat will be:
[172.16.11.1, 172.16.11.2]

Android Sequence (Skipping method)

i have some problem understanding whats wrong with android code about calling function
as show below, I have 2 private void
cekSaved(place.getName());
addUserInfo(place.getName(),"");
i expect the android run ceksaved method first then addUserInfo but android running adduser first then run ceksaved function
i need help understanding this
code is :
private void cekSaved(String param1){
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference newUserInfo = db.collection("trip").document();
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
db.collection("trip")
.whereEqualTo("user_id", userID )
.whereEqualTo("city", param1)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful())
{
for (QueryDocumentSnapshot document : task.getResult()) {
status = "ada";
Log.i(TAG, "onComplete: "+status);
}
}
else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
}
private void addUserInfo(String city, String tittle){
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference newUserInfo = db.collection("trip").document();
place_id = newUserInfo.getId();
Log.i(TAG, "addUserInfo: "+status);
if(!status.equals("ada")) {
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
userTrip usertrip = new userTrip();
usertrip.setCity(city);
usertrip.setTittle("My Trip To " + city);
usertrip.setTrip_id(newUserInfo.getId());
usertrip.setUser_id(userID);
Log.i(TAG, "addUserInfo: trip baru telah di buat");
newUserInfo.set(usertrip).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
ToastMessage("OK");
} else {
ToastMessage("fail to register");
}
}
});
}else{ToastMessage("sudah ada");}
}
You're getting values from Firebase, it's an async call, so you don't really know which one will be completed first. You can see that either calls have an onCompleteListener, if you want to run addUserInfo after cekSaved you have to call addUserInfo inside onCompleteListener of cekSaved method.

How to use Firebase Cloud Firestore references with clean code?

So, I'm using Firebase Cloud and I have three references that I go through until I get my data.
this issue made me create 3 anonymous nested classes- which looks horrible, hard to follow and probably hard code to maintain.
I've added that code, I hope for your advice - how should I clean it up?
db.collection("users").document(mAuth.getUid())
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
((DocumentReference)document.get("Users_Project")).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
((DocumentReference) document.get("Project_Schedule")).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
//we got the data!!!!
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
} else {
Log.d(TAG, "No such document as projectschedule ref");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
} else {
Log.d(TAG, "No such document as projectschedule");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
} else {
Log.d(TAG, "No such document as userproj");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
Thanks in advance!
you can try something like this :
db.collection("users").document(mAuth.getUid())
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
callback1(document);
} else {
Log.d(TAG, "No such document as userproj");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
private void callback1(DocumentSnapshot document)
{
((DocumentReference)document.get("Users_Project")).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
callback2();
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
}
private void callback2(DocumentSnapshot document)
{
DocumentSnapshot document = task.getResult();
if (document.exists()) {
((DocumentReference) document.get("Project_Schedule")).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
callback3();
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
} else {
Log.d(TAG, "No such document as projectschedule");
}
}
private void callback3(DocumentSnapshot document)
{
DocumentSnapshot document = task.getResult();
if (document.exists()) {
//we got the data!!!!
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
} else {
Log.d(TAG, "No such document as projectschedule ref");
}
}

Firestore adapter to get all users documents but just not current user document to display in RecyclerView

I am using Cloud Firestore as my database to save all users as documents in 'users' collection. I want to display all the users in 'users' collection into my RecyclerView except the current user who is currently using the app. I searched a lot to find a solution all over the internet but could not find any. So please help me out guys and thanks in advance. I'm a beginner, so really need your help. And thanks again.
This is my Firestore adapter:
mQuery = FirebaseFirestore.getInstance().collection("users");
FirestoreRecyclerOptions<NearbyUserRecyclerModel> options = new FirestoreRecyclerOptions.Builder<NearbyUserRecyclerModel>()
.setQuery(mQuery,NearbyUserRecyclerModel.class)
.setLifecycleOwner(getActivity())
.build();
FirestoreRecyclerAdapter adapter = new FirestoreRecyclerAdapter<NearbyUserRecyclerModel,NearbyProfilesViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final NearbyProfilesViewHolder holder, int position, #NonNull final NearbyUserRecyclerModel model) {
holder.itemBuddyState.setText("0");
Glide.with(getActivity()).load(model.getThumb_pictures()).into(holder.itemImage);
holder.itemDisplayName.setText(model.getFirst_name());
holder.itemOnline.setVisibility(View.VISIBLE);
DocumentSnapshot snapshot = getSnapshots().getSnapshot(position);
if (snapshot.contains("online")){
Boolean onlineState = snapshot.getBoolean("online");
if (onlineState == true){
holder.itemOnline.setVisibility(View.VISIBLE);
}
else {
holder.itemOnline.setVisibility(View.INVISIBLE);
}
}
final String user_id = snapshot.getId();
mChatRequestCollection.document(current_user_id).collection("request_received")
.document(user_id).get().addOnCompleteListener(getActivity(),
new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if (document.contains("received_time")){
holder.itemBuddyState.setText("3");
}else {
Log.d("REQUEST RECEIVED", "onComplete: received field doest exist, "+task.getException());
}
}else {
Log.d("REQUEST RECEIVED", "onComplete: Document doesn't exist, "+ task.getException());
}
}
});
mChatRequestCollection.document(current_user_id).collection("request_sent")
.document(user_id).get().addOnCompleteListener(getActivity(),
new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if (document.contains("sent_time")){
holder.itemBuddyState.setText("2");
}else {
Log.d("REQUEST SENT", "onComplete: sent field doesn't exist, "+ task.getException());
}
}else {
Log.d("REQUEST SENT", "onComplete: Document doesn't exist,");
}
}
});
mChatHolderCollection.document(current_user_id+"/user_chats/"+user_id)
.get().addOnCompleteListener(getActivity(),
new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if (document.contains("timestamp")){
holder.itemBuddyState.setText("1");
}else {
Log.d("CHAT_HOLDERDOC", "onComplete: timeStamp field doesn't exist, "+task.getException());
}
}else {
Log.d("CHAT_HOLDERDOC", "onComplete: chat buddy doesn't exist, "+task.getException());
}
}
});
holder.itemImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userPopupDialog(model, user_id);
// popupIntent(user_id);
}
});
holder.itemButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
String message = holder.itemEditText.getText().toString();
if (holder.itemBuddyState.getText().equals("0")){
if (!TextUtils.isEmpty(message)) {
WriteBatch request_batch = mRootStore.batch();
Map<String, Object> sentMap = new HashMap<>();
sentMap.put("sent_time", FieldValue.serverTimestamp());
sentMap.put("message", message);
Map<String, Object> receivedMap = new HashMap<>();
receivedMap.put("received_time", FieldValue.serverTimestamp());
receivedMap.put("message", message);
Map<String, Object> notificationMap = new HashMap<>();
notificationMap.put("from", current_user_id);
notificationMap.put("type", "request");
DocumentReference sentRef = mRootStore.collection("chat_requests").document(current_user_id + "/request_sent/" + user_id);
request_batch.set(sentRef, sentMap, SetOptions.merge());
DocumentReference receivedRef = mRootStore.collection("chat_requests").document(user_id + "/request_received/" + current_user_id);
request_batch.set(receivedRef, receivedMap, SetOptions.merge());
DocumentReference notificationRef = mRootStore.collection("users/" + user_id + "/notifications").document();
request_batch.set(notificationRef, notificationMap, SetOptions.merge());
request_batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
//------------Request Sent------------//
holder.itemEditText.setText("");
holder.itemBuddyState.setText("2");
Log.d("REQUEST_LOG", "onComplete: Request sent Successfully");
Log.d("REQUEST_LOG", "onComplete: Notification sent Successfully");
Snackbar.make(v, "Request sent Successfully", Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(v, "Failed Sending Request", Snackbar.LENGTH_LONG).show();
Log.d("REQUEST_LOG", "onComplete: Failed sending request" + task.getException());
}
}
});
}
}
if (holder.itemBuddyState.getText().equals("3")){
holder.itemEditText.setText("");
Snackbar.make(v, "Request already received by user", Snackbar.LENGTH_LONG).show();
}
if (holder.itemBuddyState.getText().equals("2")){
holder.itemEditText.setText("");
Snackbar.make(v, "Request already sent", Snackbar.LENGTH_LONG).show();
}
if (holder.itemBuddyState.getText().equals("1")){
holder.itemEditText.setText("");
Snackbar.make(v,"User already chat buddy", Snackbar.LENGTH_LONG).show();
}
}
});
}
#NonNull
#Override
public NearbyProfilesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.nearby_profiles_recycler_items, parent, false);
final AppCompatImageButton button_send = view.findViewById(R.id.itemSendButton_id);
final AppCompatEditText editText_message = view.findViewById(R.id.itemEditText_id);
Drawable drawable = getResources().getDrawable(R.drawable.ic_send_new);
drawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(drawable, getResources().getColor(R.color.colorTabUnselected));
button_send.setImageDrawable(drawable);
button_send.setEnabled(false);
editText_message.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String message = editText_message.getText().toString();
if (TextUtils.isEmpty(message)){
Drawable drawable = getResources().getDrawable(R.drawable.ic_send_new);
drawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(drawable, getResources().getColor(R.color.colorTabUnselected));
button_send.setImageDrawable(drawable);
button_send.setEnabled(false);
}
else {
Drawable drawable = getResources().getDrawable(R.drawable.ic_send_new);
drawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(drawable, getResources().getColor(R.color.colorTabSelected));
button_send.setImageDrawable(drawable);
button_send.setEnabled(true);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
return new NearbyProfilesViewHolder(view);
}
};
nearbyRecycler.setAdapter(adapter);
Change the IF condition in the below method
public void getUserData(){
db.collection("users")
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
if(document.getData().get("userID").equals(userID)){
// User user = (User)document.getData();
// Log.e(TAG, "onComplete: "+user.getUserName()+ user.getDescription() + user.isGender());
Map<String, Object> user = new HashMap<>();
user.put("name", document.getData().get("name"));
user.put("userID", document.getData().get("userID"));
user.put("email", document.getData().get("email"));
user.put("companyName",document.getData().get("companyName"));
user.put("officeAddress", document.getData().get("officeAddress"));
user.put("phoneNumber", document.getData().get("phoneNumber"));
user.put("gender",document.getData().get("gender"));
user.put("isProfileComplete",document.getData().get("isProfileComplete"));
user.put("profilePicUrl", document.getData().get("profilePicUrl"));
user.put("description", document.getData().get("description"));
/* if(document.getData().get("isProfileComplete")){
LoginActivity loginActivity = (LoginActivity)mContext;
loginActivity.navigateToHome();
}else{
LoginActivity loginActivity = (LoginActivity)mContext;
loginActivity.navigateToHome();
}*/
boolean check = (Boolean) document.getData().get("isProfileComplete");
if(check){
LoginActivity loginActivity = (LoginActivity)mContext;
loginActivity.navigateToHome();
}else{
LoginActivity loginActivity = (LoginActivity)mContext;
loginActivity.navigateToOnBoarding();
}
Log.e(TAG, "onComplete:GET DADA "+ user.get("isProfileComplete"));
}else{
Log.e(TAG, "onComplete:ID "+document.getData().get("userID") );
LoginActivity loginActivity = (LoginActivity)mContext;
loginActivity.navigateToOnBoarding();
}
}
} else {
Log.w(TAG, "Error getting documents.", task.getException());
}
}
});
}
There is no way in which you can query a Firestore database using != (not equal to operator). So the following line of code does not exist:
Query query = db.collection("users").whereNotEqualTo("userID", userID);
In this case, you need to create your own logic for that. To solve this, you need to query your database for all users but the adapter should receive all of them except one, the current user. So you need to create an if statement to check if the current user is different than the others.

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