How to get Firestore information actually added to a list so the list can passed to other functions later on

huangapple go评论81阅读模式
英文:

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(&quot;data_base&quot;, &quot;got here 1&quot;);
        getFeeds();
        Log.d(&quot;data_base&quot;, &quot;got here 2&quot;);

"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&lt;String&gt; username = new ArrayList&lt;&gt;();
    List&lt;String&gt; imageUrl = new ArrayList&lt;&gt;();
    getFeeds();
    RecyclerViewAdapter adapter = new RecyclerViewAdapter(username, imageUrl);
    private void getFeeds() {
        db.collection(&quot;feeds&quot;).addSnapshotListener(new EventListener&lt;QuerySnapshot&gt;() {
            @Override
            public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
                if (error != null) {
                    Log.d(&quot;data_base&quot;, &quot;listen:error&quot;);
                    return;
                }
                for (QueryDocumentSnapshot doc : value) {
                    if(doc.get(&quot;image&quot;) != null) {
                        Log.d(&quot;data_base&quot;, doc.getString(&quot;image&quot;));
                        imageUrl.add(doc.getString(&quot;image&quot;));
                    }
                    if (doc.get(&quot;username&quot;) != null) {
                        username.add(doc.getString(&quot;username&quot;));
                    }
                }
            }
        });
    }

答案1

得分: 1

原来我只需要一行:

adapter.notifyDataSetChanged(); // 在这里添加了一行
英文:

Turns out I only need one line

    private void getFeeds(final RecyclerViewAdapter adapter) {
        db.collection(&quot;feeds&quot;).orderBy(&quot;username&quot;, Query.Direction.ASCENDING).addSnapshotListener(new EventListener&lt;QuerySnapshot&gt;() {
            @Override
            public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
                if (error != null) {
                    Log.d(&quot;data_base&quot;, &quot;listen:error&quot;);
                    return;
                }
                for (QueryDocumentSnapshot doc : value) {
                    if(doc.get(&quot;image&quot;) != null) {
                        Log.d(&quot;data_base&quot;, doc.getString(&quot;image&quot;));
                        imageUrl.add(doc.getString(&quot;image&quot;));
                    }
                    if (doc.get(&quot;username&quot;) != null) {
                        username.add(doc.getString(&quot;username&quot;));
                    }
                }
                // 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

  1. 要将数据存储在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();
    }
});
  1. 要从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
            }
        }
    }
});
  1. 如果您希望稍后在其他活动中使用您的数据,您应该使用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.

  1. To store data in firestore collection you can use Hashmap. Code attached below:

     HashMap&lt;String, Object&gt; userData = new HashMap&lt;&gt;();
     userData.put(&quot;username&quot;, your_username_data);
     userData.put(&quot;imageurl&quot;, your_imageurl_data);
    
     db.collection(&quot;feeds&quot;).document().set(userData).addOnSuccessListener(new OnSuccessListener&lt;Void&gt;() {
         @Override
         public void onSuccess(Void aVoid) {
             //This code gets executed if data successfully added to db
             Toast.makeText(getApplicationContext(), &quot;User Data save successfully&quot;, 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();
         }
     });
    
  2. To fetch data from firestore collection you can refer to the code below:

     db.collection(&quot;feeds&quot;).get().addOnCompleteListener(new OnCompleteListener&lt;QuerySnapshot&gt;() {
         @Override
         public void onComplete(@NonNull Task&lt;QuerySnapshot&gt; task) {
             // Code below gets executed if data fetched successfully
             if (task.isSuccessful()) {
                 for (QueryDocumentSnapshot documentSnapshot : task.getResult()) {
                     String username = (String) documentSnapshot.get(&quot;username&quot;); // this is your username previously saved to db
                     String imageurl = (String) documentSnapshot.get(&quot;imageurl&quot;); // 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
                 }
             }
         }
     });
    
  3. 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(&quot;username&quot;, username);
     i.putExtra(&quot;imageurl&quot;, 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(&quot;username&quot;); 
         String imageurl = extras.getString(&quot;imageurl&quot;);
         // inside extras.getString you use key value (value in quote &quot;&quot;) which you provided inside i.putExtra
     }     
    

Link: https://github.com/bumptech/glide (this library helps you to download image urls to imageviews)

huangapple
  • 本文由 发表于 2020年8月14日 02:50:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/63401479.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定