How to stop itterating through a map when value is found - java

What i am wanting to do: When a user creates a post have an iterator iterate through a document to see if the users has too many posts. If user has a null field post is allowed
The issue i am facing is that when the user creates a post it iterates through the list and posts on every null value, not just one.
To solve this issue I added break;. This solved my issue but now for some reason when the break; statement is used the iterator will only check to see if the 5th item in the document is null not all of the documents.
Code:
currentDocument.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()) {
Log.d(TAG, map.entrySet().toString());
Log.d(TAG, entry.toString());
if (entry.getValue() == null) {
Log.d("tag", entry.toString() + " is equal to null");
posted....
break;
To solve this issue i found this stack post and they said to add a boolean flag (removed break:)
public static boolean criteriaMet=false;
currentDocument.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();
while (criteriaMet == false) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
Log.d(TAG, map.entrySet().toString());
Log.d(TAG, entry.toString());
if (entry.getValue() == null) {
criteriaMet = true;
Log.d("tag", entry.toString() + " is equal to null");
posted....
when I use this method the user goes to post it is posted four times and (skips the first null value the itterator identifies and posts on the remaining 4), if the user attempts to post again nothing, happens I don't think the variable is resetting but not sure
full code with the second method commented out i have a few other documents that i am also creating/writing to they are unrelated:
newPostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
currentDocument.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();
// while (criteriaMet == false) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
Log.d(TAG, map.entrySet().toString());
Log.d(TAG, entry.toString());
if (entry.getValue() == null) {
criteriaMet = true;
Log.d("tag", entry.toString() + " is equal to null");
postProgress.setTitle("Posting");
postProgress.setMessage("This Should Only Take A Second");
postProgress.setCanceledOnTouchOutside(false);
postProgress.show();
final String desc = newPostDesc.getText().toString();
if (!TextUtils.isEmpty(desc)) {
final String randomName = UUID.randomUUID().toString();
final StorageReference filePath = storageReference.child("post_images").child(randomName + ".jpeg");
filePath.putFile(postImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull final Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
File newImageFile = new File(Objects.requireNonNull(postImageUri.getPath()));
try {
compressedImageFile = new Compressor(NewPost.this)
.setMaxHeight(200)
.setMaxWidth(200)
.setQuality(10)
.compressToBitmap(newImageFile);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
compressedImageFile.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] thumbData = baos.toByteArray();
final UploadTask uploadTask = storageReference.child("post_images/thumbs").child(randomName + ".jpeg").putBytes(thumbData);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
Log.d("tag", downloadUrl);
FirebaseUser current_user = FirebaseAuth.getInstance().getCurrentUser();
String uid = Objects.requireNonNull(current_user).getUid();
final Map<String, Object> postMap = new HashMap<>();
// No thumb ?????
postMap.put("image_url", downloadUrl);
postMap.put("desc", desc);
postMap.put("user_id", current_user_id);
postMap.put("message_doc", uid + postCategory);
postMap.put("timestamp", FieldValue.serverTimestamp());
firebaseFirestore.collection(postCategory).add(postMap).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
#Override
public void onComplete(#NonNull Task<DocumentReference> task) {
if (task.isSuccessful()) {
firebaseFirestore.collection("Posts").add(postMap).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
#Override
public void onComplete(#NonNull final Task<DocumentReference> task) {
FirebaseUser current_user = FirebaseAuth.getInstance().getCurrentUser();
String uid = Objects.requireNonNull(current_user).getUid();
final Map<String, String> chatMap = new HashMap<>();
postMap.put("timestamp", FieldValue.serverTimestamp());
postMap.put("name", current_user_id);
postMap.put("message", "");
firebaseFirestore.collection("Messages")
.document(uid + postCategory)
.set(chatMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
final String BlogPostID = Objects.requireNonNull(task.getResult()).getId();
String document_Id = current_user_id + postCategory;
final Map<String, String> usermap = new HashMap<>();
usermap.put("Owner", current_user_id);
usermap.put("debater", null);
firebaseFirestore.collection("Messages").document(document_Id)
.set(usermap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//write to active posts document
postProgress.dismiss();
Intent startIntent = new Intent(NewPost.this, MainActivity.class);
startActivity(startIntent);
}
});
}
});
}
});
}
}
});
}
});
}
}
});
}
} else {
Log.w(TAG, "the value is not null");
Toast.makeText(getApplicationContext(), "Too many active debates", Toast.LENGTH_LONG).show();
}
break;
}
// } //attached to while crit loop
}
}
}
});
}
});}
I have been working on this for a few days and I am stumped if any more info is required let me know.

Related

Trying to update multi images. The code below works if I update single image but on two or more images

If I try to do it with the help of Array then it update all the fields in Firestore and I want to update only the particular field only. I have tried many things but I am not able to achieve what I want.Help.
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
i =0;
HashMap<Integer,String> downloadurii = new HashMap<>();
if(numap.size()!=0){
for ( i=1;i<=3;i++){
if (numap.containsKey(i)){
StorageReference fileRefernces = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(Uri.parse(numap.get(i))));
fileRefernces.putFile(Uri.parse(numap.get(i))).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileRefernces .getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = uri.toString();
//downloadurii.put(i,url);
if(i == 1)
{
HashMap<String,Object> keymap = new HashMap<>();
keymap.put("image1",url);
firebaseFirestore.collection("users").document(userid).collection("update").document(userid)
.update(keymap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
progressBar.setVisibility(View.GONE);
Toast.makeText(getContext(),"Success",Toast.LENGTH_SHORT).show();
}else {
progressBar.setVisibility(View.GONE);
Toast.makeText(getContext(), "Error"+task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
}else if(i == 2)
{
HashMap<String,Object> keymap = new HashMap<>();
keymap.put("image2",url);
firebaseFirestore.collection("users").document(userid).collection("update").document(userid)
.update(keymap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
progressBar.setVisibility(View.GONE);
Toast.makeText(getContext(),"Success",Toast.LENGTH_SHORT).show();
}else {
progressBar.setVisibility(View.GONE);
Toast.makeText(getContext(), "Error"+task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
}else if (i == 3)
{
HashMap<String,Object> keymap = new HashMap<>();
keymap.put("image3",url);
firebaseFirestore.collection("users").document(userid).collection("update").document(userid)
.update(keymap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
progressBar.setVisibility(View.GONE);
Toast.makeText(getContext(),"Success",Toast.LENGTH_SHORT).show();
}else {
progressBar.setVisibility(View.GONE);
Toast.makeText(getContext(), "Error"+task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
});
}
}
}
}
});
[[[[[public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null) {
imageuriOne = data.getData();
dpOne.setImageURI(imageuriOne);
numap.put(1,""+imageuriOne);
}
}
private void uploadstoarge(){
progressBar.setVisibility(View.VISIBLE);
HashMap<Integer,String> downloadurii = new HashMap<>();
if(numap.size()!=0){
for ( int i=1;i<=3;i++){
if (numap.containsKey(i) == true){
int j = i;
StorageReference fileRefernces = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(Uri.parse(numap.get(i))));
fileRefernces.putFile(Uri.parse(numap.get(i))).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileRefernces .getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = uri.toString();
uploadfirestore(j,url);
progressBar.setVisibility(View.GONE);
}
});
}
});
}else{
continue;
}
}
}
}
private void uploadfirestore(int i,String url) {
HashMap<String,Object> keymap = new HashMap<>();
keymap.put("image"+i,url);
firebaseFirestore.collection("users").document(userid).collection("update").document(userid)
.update(keymap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
progressBar.setVisibility(View.GONE);
Toast.makeText(getContext(),"Success",Toast.LENGTH_SHORT).show();
}else {
progressBar.setVisibility(View.GONE);
Toast.makeText(getContext(), "Error"+task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
}]]]]

Adding 2 Hashmaps to a single document in Firestore

I have uploaded 1 Hashmap to firestore.And when i try to upload one more Hashmap to the same document it replaces my previous Hashmap.Why is it so?
I change the String title everytime and still it replaces the previous Hashmap.
String poll1 = Poll1.getText().toString().trim();
String poll2 = Poll2.getText().toString().trim();
String poll3 = Poll3.getText().toString().trim();
String title = Title.getText().toString().trim();
DocumentReference documentReference = firestore.collection("Polls").document("abc1");
Map<String, Object> nestedData = new HashMap<>();
nestedData.put(poll1 , 0 );
nestedData.put(poll2 , 0);
nestedData.put(poll3 , 0);
Map<String, Object> upload = new HashMap<>();
upload.put(title, nestedData);
documentReference.set(upload).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(polls.this, "UPLOADED", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(polls.this, "FAILED", Toast.LENGTH_LONG).show();
}
});
your document needs to mention that this has to be merged instead replace.
.set(data, SetOptions.merge())
Try this if it works.
documentReference.set(upload, SetOptions.merge()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(polls.this, "UPLOADED", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(polls.this, "FAILED", Toast.LENGTH_LONG).show();
}
});

My hashmap is not getting implemented in firebase database

I'm using this hashmap to transfer the username from one child(Users) to another(Notes) in database.
In my app you can create as well as update notes.
I want that every time a note is created or updated in the database a username is added along with the note. the username is saved in the users child.
But when the note is created the username doesn't show up. But when the note is updated, it is added in the child.
here is the code:
fAuth = FirebaseAuth.getInstance();
fNotesDatabase = FirebaseDatabase.getInstance().getReference()
.child("Notes").child(fAuth.getCurrentUser().getUid());
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
current_user_id = fAuth.getCurrentUser().getUid();
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String title = etTitle.getText().toString().trim();
String content = etContent.getText().toString().trim();
if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(content)) {
createNote(title, content);
putUsername();
} else {
Snackbar.make(view, "Fill empty fields", Snackbar.LENGTH_SHORT).show();
}
}
});
private void putUsername() {
UsersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String username = snapshot.child("username").getValue().toString();
HashMap usernameMap = new HashMap();
usernameMap.put("username", username);
fNotesDatabase.child(noteID).updateChildren(usernameMap);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
I'm not able to understand as how come the username is added when the note is updated but not when the note us created.
I have updated the second note thats why there is a username but when is simply created the upper one there username is not showing.
EDIT
putData method :
private void putData() {
if (isExist) {
fNotesDatabase.child(noteID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("title") && dataSnapshot.hasChild("content")) {
String title = dataSnapshot.child("title").getValue().toString();
String content = dataSnapshot.child("content").getValue().toString();
etTitle.setText(title);
etContent.setText(content);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
createNote method:
private void createNote(String title, String content) {
if (fAuth.getCurrentUser() != null) {
Calendar calFordDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calFordDate.getTime());
if (isExist) {
Map updateMap = new HashMap();
updateMap.put("title", etTitle.getText().toString().trim());
updateMap.put("content", etContent.getText().toString().trim());
updateMap.put("timestamp", ServerValue.TIMESTAMP);
updateMap.put("date",saveCurrentDate);
fNotesDatabase.child(noteID).updateChildren(updateMap);
SendUsersToPostActivity();
Toast.makeText(this, "Article updated", Toast.LENGTH_SHORT).show();
} else {
final DatabaseReference newNoteRef = fNotesDatabase.push();
final Map noteMap = new HashMap();
noteMap.put("title", title);
noteMap.put("content", content);
noteMap.put("timestamp", ServerValue.TIMESTAMP);
noteMap.put("date",saveCurrentDate);
Thread mainThread = new Thread(new Runnable() {
#Override
public void run() {
newNoteRef.setValue(noteMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(NewNoteActivity.this, "Article Created", Toast.LENGTH_SHORT).show();
SendUsersToPostActivity();
} else {
Toast.makeText(NewNoteActivity.this, "ERROR: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
mainThread.start();
}
}
}
It's hard to be certain, but I don't see where you set the noteID value that putUsername depends on.
In general though, I'd recommend changing createNote to take all the data that it needs for the new note, including the user name:
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String title = etTitle.getText().toString().trim();
String content = etContent.getText().toString().trim();
if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(content) && fAuth.getCurrentUser() != null) {
UsersRef.child(current_user_id).child("username").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String username = snapshot.getValue(String.class);
createNote(title, content, current_user_id, username);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException()
}
});
} else {
Snackbar.make(view, "Fill empty fields", Snackbar.LENGTH_SHORT).show();
}
}
});
private void createNote(String title, String content, String uid, String username) {
Calendar calFordDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calFordDate.getTime());
Map updateMap = new HashMap();
updateMap.put("title", title);
updateMap.put("content", content);
updateMap.put("timestamp", ServerValue.TIMESTAMP);
updateMap.put("date",saveCurrentDate);
updateMap.put("uid",uid);
updateMap.put("username",username);
final DatabaseReference noteRef = isExist ? fNotesDatabase.push() : fNotesDatabase.child(noteID);
noteRef.updateChildren(noteMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(NewNoteActivity.this, "Article "+(isExists ? "updated" : "created"), Toast.LENGTH_SHORT).show();
SendUsersToPostActivity();
} else {
Toast.makeText(NewNoteActivity.this, "ERROR: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
Some of the changes in this code versus yours:
Looks up the user name before creating the new note. Uses a addListenerForSingleValueEvent for this, to ensure we only do this once for every button click.
Only loads the username child of the user profile, since that's all you use.
Use the values you pass into createNote instead of recalculating them from the UI views.
Only has a single write to the database, as updateChildren works fine for creating the initial data too.
There is no need to run the Firebase setValue call on a new thread, as Firebase runs it off the main thread already.
Please don't leave onCancelled empty, as it may hide important error messages.

How to add image list in Firebase?

I want to upload image list in firebase but in the firebase upload success listener doesn't add image list on OnSuccessListener.
Tried
I add string value outside of the add onSuccessListener class it works and i tried to log the url it works too.But it doesn't add the string value in the arrayList in the OnSuccessListener.
Thank you for the help.
Main code
public void UploadImage() {
if (isUserSelected != null) {
progressDialog.setTitle("Image is Uploading...");
Log.d(TAG, "UploadImage: uploading");
progressDialog.show();
Log.d(TAG, "UploadImage: after progress bar");
for (int i = 0; i < multipleFileUploads.size(); i++) {
Log.d(TAG, "UploadImage: " + i);
final StorageReference storageReference2 = storageReference.child(System.currentTimeMillis() + "." + GetFileExtension(multipleFileUploads.get(i)));
storageReference2.putFile(multipleFileUploads.get(i))
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.d(TAG, "onSuccess: ");
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();
storageReference2.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.d(TAG, "onSuccess: uri " + uri.toString());
imagelist.add(uri.toString());
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
Log.d(TAG, "onProgress: " + taskSnapshot.getBytesTransferred());
Log.d(TAG, "onProgress: " + taskSnapshot.getTotalByteCount());
}
}).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
Log.d(TAG, "onComplete: " + task.getException());
}
});
}
imageList.add("custom list");
uploadinfo imageUploadInfo = new uploadinfo(txtdata.getText().toString(), txtData1.getText().toString(), imageList.toString());
String ImageUploadId = databaseReference.push().getKey();
databaseReference.child(ImageUploadId).setValue(imageUploadInfo);
} else {
Toast.makeText(uploadimg1.this, "Please Select Image or Add Image Name", Toast.LENGTH_LONG).show();
}
POJO Code for Firebase
public class uploadinfo {
public String imageName;
public String imageName1;
public String imageListString;
public uploadinfo(String imageName, String imageName1, String imageListString) {
this.imageName = imageName;
this.imageName1 = imageName1;
this.imageListString = imageListString;
}
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
public String getImageName1() {
return imageName1;
}
public void setImageName1(String imageName1) {
this.imageName1 = imageName1;
}
public String getImageListString() {
return imageListString;
}
public void setImageListString(String imageListString) {
this.imageListString = imageListString;
}
}
In Firebase
The problem might be in your model. In firebase the order goes imageListString, imageName, imageName1. But in model in constructor you got String imageName, String imageName1, String imageListString. At the same time im not sure how you generate the list which you create BEFORE send it to Firebase.
You can try this method
UploadTask uploadTask = storageReference2.putFile(multipleFileUploads.get(i));
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
imagelist.add(downloadUri.toString());
} else {
// Handle failures
// ...
}
}
});

how to retrieve only field(field name ) as list array from FireStore in android?

I want to retrieve field as List Array from Firestore
in this Horror field is "map" I want to retrieve all field in HINDI document as Array
as shown in the image
public class HindiStory extends AppCompatActivity {
private static final String TAG = "HindiStory";
List<String> list;
FirebaseFirestore db = FirebaseFirestore.getInstance();
private DocumentReference hindiStoryref = db.collection("story").document("HINDI");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hindi_story);
}
public void hmoral(View v){
hindiStoryref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
list = new ArrayList<>();
Map<String, Object> map = task.getResult().getData();
for (Map.Entry<String, Object> entry : map.entrySet()){
list.add(entry.getKey());
Log.d(TAG, entry.getKey());
}
}
}
});
}
public void hromantic(View v){
}
}
I want to retrieve on a button click
and use this array data in listview in another activity thanks
Try bellow code it will work for you
hindiStoryref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.getResult() != null && task.getResult().exists() && task.getResult().getData() != null) {
list.addAll(task.getResult().getData().keySet()); //Adding list of field list into list object
Log.d("arrayKeys size", list.size() + "");
Log.d("arrayKeys size", list.toString());
}
}
});
You can try to cast with hashmap.
HashMap<String, Object> categoriesMap = (HashMap)task.getResult().getData()
Also
list.add(entry.getKey());
You can use
categoriesMap.keySet();
To get all value from Hashmap
This is how i have done to retrieve the HasMap values :
ref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot doc = task.getResult();
Log.d(TAG, "onComplete: " + doc);
HashMap<String, String> categoriesMap = (HashMap)doc.getData().get("categories");
mCategories.addAll(categoriesMap.keySet());
}
}
});

Categories

Resources