英文:
How to get Firestore information actually added to a list so the list can passed to other functions later on
问题
I'm really new to programming in general. My question is that I know when reading from Firestore, it is asynchronous. Meaning if I do:
Log.d("data_base", "got here 1");
getFeeds();
Log.d("data_base", "got here 2");
"got here 1" and "got here 2" will be printed simultaneously despite any log statement inside getFeeds()
But what if I do want to store all the information from a Firestore collection into a list and use it later on?
This is what I have now.
List<String> username = new ArrayList<>();
List<String> imageUrl = new ArrayList<>();
getFeeds();
RecyclerViewAdapter adapter = new RecyclerViewAdapter(username, imageUrl);
private void getFeeds() {
db.collection("feeds").addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
if (error != null) {
Log.d("data_base", "listen:error");
return;
}
for (QueryDocumentSnapshot doc : value) {
if(doc.get("image") != null) {
Log.d("data_base", doc.getString("image"));
imageUrl.add(doc.getString("image"));
}
if (doc.get("username") != null) {
username.add(doc.getString("username"));
}
}
}
});
}
英文:
I'm really new to programming in general. My question is that I know when reading from Firestore, it is asynchronous. Meaning if I do:
Log.d("data_base", "got here 1");
getFeeds();
Log.d("data_base", "got here 2");
"got here 1" and "got here 2" will be printed simultaneously despite any log statement inside getFeeds()
But what if I do want to store all the information from a Firestore collection into a list and use it later on?
This is what I have now.
List<String> username = new ArrayList<>();
List<String> imageUrl = new ArrayList<>();
getFeeds();
RecyclerViewAdapter adapter = new RecyclerViewAdapter(username, imageUrl);
private void getFeeds() {
db.collection("feeds").addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
if (error != null) {
Log.d("data_base", "listen:error");
return;
}
for (QueryDocumentSnapshot doc : value) {
if(doc.get("image") != null) {
Log.d("data_base", doc.getString("image"));
imageUrl.add(doc.getString("image"));
}
if (doc.get("username") != null) {
username.add(doc.getString("username"));
}
}
}
});
}
答案1
得分: 1
原来我只需要一行:
adapter.notifyDataSetChanged(); // 在这里添加了一行
英文:
Turns out I only need one line
private void getFeeds(final RecyclerViewAdapter adapter) {
db.collection("feeds").orderBy("username", Query.Direction.ASCENDING).addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
if (error != null) {
Log.d("data_base", "listen:error");
return;
}
for (QueryDocumentSnapshot doc : value) {
if(doc.get("image") != null) {
Log.d("data_base", doc.getString("image"));
imageUrl.add(doc.getString("image"));
}
if (doc.get("username") != null) {
username.add(doc.getString("username"));
}
}
// added line here
adapter.notifyDataSetChanged();
}
});
}
My understanding is when onEvent() finish fetching data from Firestore, adapter.notifyDataSetChanged()
will be called to update the two lists.
答案2
得分: 0
- 要将数据存储在Firestore集合中,您可以使用HashMap。以下是附带的代码:
HashMap<String, Object> userData = new HashMap<>();
userData.put("username", your_username_data);
userData.put("imageurl", your_imageurl_data);
db.collection("feeds").document().set(userData).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
// 如果数据成功添加到数据库,将执行此代码
Toast.makeText(getApplicationContext(), "用户数据保存成功", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// 如果数据无法保存到数据库,将执行此代码
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
- 要从Firestore集合中检索数据,您可以参考以下代码:
db.collection("feeds").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
// 如果成功检索数据,将执行以下代码
if (task.isSuccessful()) {
for (QueryDocumentSnapshot documentSnapshot : task.getResult()) {
String username = (String) documentSnapshot.get("username"); // 这是您先前保存到数据库中的用户名
String imageurl = (String) documentSnapshot.get("imageurl"); // 这是您先前保存到数据库中的图像URL
// 附加奖励:要将图像下载到您的ImageView中,您可以使用Glide库(我将附上链接到GitHub页面)
Glide.with(getApplicationContext()).load(imageurl).into(imageview); // imageview是您要显示图像的ImageView
}
}
}
});
- 如果您希望稍后在其他活动中使用您的数据,您应该使用Bundle。以下是提供的代码:
在您的第一个活动(要从中传递数据的活动)中:
String username = your_username_data;
String imageurl = your_imageurl_data;
Intent i = new Intent(Activity1.this, Activity2.class);
i.putExtra("username", username);
i.putExtra("imageurl", imageurl);
startActivity(i);
在您的第二个活动(要传递数据到的活动)中:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String username = extras.getString("username");
String imageurl = extras.getString("imageurl");
// 在extras.getString中,您使用了您在i.putExtra中提供的键值(位于引号内的值)
}
链接:https://github.com/bumptech/glide(此库可帮助您将图像URL下载到ImageView中)
英文:
You don't have to use Lists to save data from firestore collection.
-
To store data in firestore collection you can use Hashmap. Code attached below:
HashMap<String, Object> userData = new HashMap<>(); userData.put("username", your_username_data); userData.put("imageurl", your_imageurl_data); db.collection("feeds").document().set(userData).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { //This code gets executed if data successfully added to db Toast.makeText(getApplicationContext(), "User Data save successfully", Toast.LENGTH_SHORT).show(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { `enter code here`//This code gets executed if data cannot be saved to db Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } });
-
To fetch data from firestore collection you can refer to the code below:
db.collection("feeds").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { // Code below gets executed if data fetched successfully if (task.isSuccessful()) { for (QueryDocumentSnapshot documentSnapshot : task.getResult()) { String username = (String) documentSnapshot.get("username"); // this is your username previously saved to db String imageurl = (String) documentSnapshot.get("imageurl"); // this is your imageurl previously saved to db // Bonus: to download images to your imageview you can use Glide library (I will attach link below to Github page) Glide.with(getApplicationContext()).load(imageurl).into(imageview); // imageview is your ImageView that you want to show your images } } } });
-
If you want to use your data later in your other activity you should use Bundle. Code provided below:
In your 1st Activity (Activity that you want to pass data from):
String username = your_username_data; String imageurl = your_imageurl_data; Intent i = new Intent(Activity1.this, Activity2.class); i.putExtra("username", username); i.putExtra("imageurl", imageurl); startActivity(i);
In your 2nd Activity (Activity that you want to pass data to):
Bundle extras = getIntent().getExtras(); if (extras != null) { String username = extras.getString("username"); String imageurl = extras.getString("imageurl"); // inside extras.getString you use key value (value in quote "") which you provided inside i.putExtra }
Link: https://github.com/bumptech/glide (this library helps you to download image urls to imageviews)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论