如何将Firestore文档中的Map转换为ArrayList。

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

How to convert a Map into arrayList from firestore document

问题

我的目标是查询集合并获取每个文档中的三个或五个哈希映射。我的目标是获取具有不同ID的文档,并在嵌套的RecyclerView中填充它们。但我在将映射值转换为ArrayList时遇到了麻烦。

我的主要模型类:

public class BattleGroupPosts {

    private String userId;
    public ArrayList<PostBattle> userPost;

    public BattleGroupPosts() {
    } // 下面有getter和setter以及构造函数
}

我的PostBattle模型类

```java
public class PostBattle {

    private String id;
    private String imageuri;
    private String description;
    private String publisher;
    private String tags;
    private String challenge_tittle;
    private int NumberOfLikesPoints;
    private int battle_post_count;
    private long TimeLimit;
    private Boolean post_time_done;
    private @ServerTimestamp
    Date timestamp;

    public PostBattle() {
    } // 下面有getter和setter以及构造函数
}

从Firestore查询

```java
private List<BattleGroupPosts> battleGroupPosts;
private ArrayList<PostBattle> battlePostLists;

private void GettingAllBattleGroupPosts() {
    battleGroupPosts = new ArrayList<>();
    battlePostLists = new ArrayList<>();
    adapter = new BattlGroupAdapter(mContext, battleGroupPosts);//设置适配器
    battle_posts.setAdapter(adapter);

    CollectionReference GroupIdRef = mFirestore
            .collection("OpenBattle")
            .document(BattlesPost_creator)
            .collection("BattlePost")
            .document(BattlePost_id)
            .collection("Participants");
    GroupIdRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    Log.d(TAG, document.getId() + " => " + document.getData());

                    final BattleGroupPosts groupPosts = document.toObject(BattleGroupPosts.class);
                    groupPosts.setUserId(groupPosts.getUserId());

                    groupPosts.setUserPosts(battlePostLists);

                    Map<String, PostBattle> batPost = (Map<String, PostBattle>) document.get("userPost1");

                    // 我在这里遇到了问题,不知道如何将它们添加到模型类中的ArrayList中,我尝试将HashMap转换为ArrayList,但我的图像在RecyclerView中以所有项目的ID填充,因为它在for循环中,我猜。

                    // 以下是我尝试的方法之一:

                    List<PostBattle> newList = new ArrayList<>(batPost.values());
                    Log.d(TAG, "onComplete: liisd:" + newList.get(0));
                    PostBattle postBattle = new PostBattle();
                    postBattle.setImageuri(String.valueOf(newList.get(1)));
                    postBattle.setNumberOfLikesPoints(Integer.valueOf(String.valueOf(newList.get(2))));
                    battlePostLists.add(postBattle);
                    battleGroupPosts.add(groupPosts);
                    adapter.notifyDataSetChanged(); // 这些方法我在for循环内部执行

                    // 我还尝试过这个:
                    
                    PostBattle postBattle = new PostBattle();
                    Object value = batPost.get("imageuri");
                    postBattle.setImageuri(String.valueOf(value));
                    Log.d(TAG, "onComplete: value: " + value);
                    battlePostLists.add(postBattle);
                    groupPosts.setUserPosts(battlePostLists);
                    battleGroupPosts.add(groupPosts);
                    adapter.notifyDataSetChanged();

                    // 以及这个:

                    Map<String, Object> idMaps = document.getData();
                    for (Map.Entry<String, Object> id : idMaps.entrySet()){
                        String userId = id.getKey();
                        Object yourObject = id.getValue();
                        Log.d(TAG, "onComplete: IDSSS: " + userId);
                        Log.d(TAG, "onComplete: Object: " + yourObject);

                        Map<String, PostBattle> batPost = (Map<String, PostBattle>) document.get("userPost1");
                        PostBattle postBattle = new PostBattle();
                        Object value = batPost.get("imageuri");
                        postBattle.setImageuri(String.valueOf(value));
                        batPost.clear();
                        battlePostLists.add(postBattle);
                    }
                }
            }
        }
    });
}

希望这些代码对你有所帮助。如果你有任何问题或需要进一步的帮助,请随时提出。

英文:

My goal is to get query a collection and get the documents each document has three or five hashmap in it .my aim is to get the documents with different id's and populate in nested recycler view . But i facing trouble in converting the map values into arraylist

My Main Model class:

public class BattleGroupPosts {

private String userId;
public ArrayList&lt;PostBattle&gt; userPost;
public BattleGroupPosts() {
} ///below there getters and setters and constructions are there

My PostBattle Modelclass:

public class PostBattle {
private String id;
private String imageuri;
private String description;
private String publisher;
private String tags;
private String challenge_tittle;
private int NumberOfLikesPoints;
private int battle_post_count;
private long TimeLimit;
private Boolean post_time_done;
private @ServerTimestamp
Date timestamp;
public PostBattle() {
} //below the getter and setter and constructor

Querying from firestore:

private List&lt;BattleGroupPosts&gt; battleGroupPosts;
private ArrayList&lt;PostBattle&gt; battlePostLists;
private void GettingAllBattleGroupPosts(){
battleGroupPosts = new ArrayList&lt;&gt;();
battlePostLists = new ArrayList&lt;&gt;();
adapter = new BattlGroupAdapter(mContext,battleGroupPosts);//Setting the adapter
battle_posts.setAdapter(adapter);
CollectionReference GroupIdRef = mFirestore
.collection(&quot;OpenBattle&quot;)
.document(BattlesPost_creator)
.collection(&quot;BattlePost&quot;)
.document(BattlePost_id)
.collection(&quot;Participants&quot;);
GroupIdRef.get().addOnCompleteListener(new OnCompleteListener&lt;QuerySnapshot&gt;() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onComplete(@NonNull Task&lt;QuerySnapshot&gt; task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + &quot; =&gt; &quot; + document.getData());
final BattleGroupPosts groupPosts = document.toObject(BattleGroupPosts.class);
groupPosts.setUserId(groupPosts.getUserId());
groupPosts.setUserPosts(battlePostLists);
Map&lt;String, PostBattle&gt; batPost = (Map&lt;String, PostBattle&gt;) document.get(&quot;userPost1&quot;); 

I get stuck here i don't know how to to add these to array list in the model class i tried converting hashMap to arraylist but my images getting populated with all items Id's in recylerview as it is in the for loop i guess.
my method try:

List&lt;PostBattle&gt; newList = new ArrayList&lt;PostBattle&gt;(batPost.values());
Log.d(TAG, &quot;onComplete: liisd:&quot; + newList.get(0));
PostBattle postBattle = new PostBattle();
postBattle.setImageuri(String.valueOf(newList.get(1)));
postBattle.setNumberOfLikesPoints(Integer.valueOf(String.valueOf(newList.get(2))));
battlePostLists.add(postBattle);
battleGroupPosts.add(groupPosts);
adapter.notifyDataSetChanged(); ///These methods i did it inside for the loop  

Have tried this :

                    PostBattle postBattle = new PostBattle();
Object value = batPost.get(&quot;imageuri&quot;);
postBattle.setImageuri(String.valueOf(value));
Log.d(TAG, &quot;onComplete: value: &quot; + value);
battlePostLists.add(postBattle);
groupPosts.setUserPosts(battlePostLists);
battleGroupPosts.add(groupPosts);
adapter.notifyDataSetChanged();

And this too:

    Map&lt;String, Object&gt; idMaps = document.getData();
for (Map.Entry&lt;String, Object&gt; id : idMaps.entrySet()){
String userId = id.getKey();
Object yourObject = id.getValue();
Log.d(TAG, &quot;onComplete: IDSSS: &quot; + userId);
Log.d(TAG, &quot;onComplete: Object: &quot; + yourObject);
Map&lt;String, PostBattle&gt; batPost = (Map&lt;String, PostBattle&gt;) document.get(&quot;userPost1&quot;);
PostBattle postBattle = new PostBattle();
Object value = batPost.get(&quot;imageuri&quot;);
postBattle.setImageuri(String.valueOf(value));
batPost.clear();
battlePostLists.add(postBattle);

如何将Firestore文档中的Map转换为ArrayList。

如何将Firestore文档中的Map转换为ArrayList。

答案1

得分: 1

以下是翻译好的部分:

看起来你想解析地图以获取值,你可以为多个键执行以下操作:
for (Map.Entry<String, PostBattle> params : batPost.entrySet()) {
if (params.getKey().equals("imageuri")) { // 或者其他内容
// 添加到你的ArrayList中
}
}
或者如果你只需要一个:
String imageuri = batPost.getKey("imageuri").toString();
将上述图像URI添加到你的ArrayList中
如果你想根据ID分隔:
Map<String, Yourobject> idmaps = document.getData();
for (Map.Entry<String, Yourobject> id : idmaps.entrySet()) {
// 在这里执行你的代码
// 首先获取ID
String userid = id.getKey();
// 然后执行你上面已经做过的操作
Yourobject = id.getValue();
// 在上面的对象上执行你的逻辑,这将分隔你的用户ID
}
英文:

It looks like you want to parse the map to get values, you can do this for multiple keys:

for (Map.Entry&lt;String, PostBattle&gt; params : batPost.entrySet()) {
if (params.getKey().equals(&quot;imageuri&quot;)) { // or something else
//add to your arraylist  
}
}

or if you require only one:

String imageuri = batPost.getKey(&quot;imageuri&quot;).toString();

add the above image uri to your arraylist

If you want to seperate on basis of ids:

Map&lt;String, yourobject&gt; idmaps = document.getData();
for (Map.Entry&lt;String, yourobject&gt; id : idmaps.entrySet()) {
// do your code here
// first get the id 
String userid = id.getKey();
//then do what you have done above
yourobject = id.getValue();
// do your logic on above object this will seperate your userids
}

huangapple
  • 本文由 发表于 2020年8月7日 13:47:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63295921.html
匿名

发表评论

匿名网友

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

确定