【问题标题】:String is not getting added to the ArrayList in OnClick Listener after getting the data from Firestore从 Firestore 获取数据后,字符串未添加到 OnClick 侦听器中的 ArrayList
【发布时间】:2020-06-05 19:47:28
【问题描述】:

我尝试在 FirebaseFirestore 中创建一个论坛应用程序,我已经让它显示主题,但是当我想添加一个新主题时,它会从集合中获取用户数据(“fname”和“lname”并将它们放在一起作为一个名称),但它似乎没有将它们添加到必须声明为 final 的 ArrayList 中,因为它是从 OnComplete 函数调用的。我收到此错误:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mechachromemobileapp, PID: 15590
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.get(ArrayList.java:437)
    at com.example.mechachromemobileapp.ForumPostTopic$1.onClick(ForumPostTopic.java:91)
    at android.view.View.performClick(View.java:6256)
    at android.view.View$PerformClick.run(View.java:24701)
    at android.os.Handler.handleCallback(Handler.java:789)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6541)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

这表明数组是空的,如果您知道如何更新它,我将不胜感激,或者可能有另一种解决方法,也许可以做一些更简单的事情来实现结果。代码如下:

public class ForumPostTopic extends AppCompatActivity {

public static final String TAG = "TAG";
EditText editTopic, editContent;
Button addTopicBtn;
FirebaseFirestore fStore;
FirebaseAuth fAuth;
Date date_published;
String userID;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_forum_post_topic);

    editTopic = findViewById(R.id.editTopic);
    editContent = findViewById(R.id.editContent);
    addTopicBtn = findViewById(R.id.addTopicBtn);

    fAuth = FirebaseAuth.getInstance();
    userID = fAuth.getCurrentUser().getUid();

    fStore = FirebaseFirestore.getInstance();

    date_published = Calendar.getInstance().getTime();



    addTopicBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String topic = editTopic.getText().toString().trim();
            String content = editContent.getText().toString().trim();
            final ArrayList<String> author = new ArrayList<>();


            // getting the user
            DocumentReference userRef = fStore.collection("users").document(userID);
            userRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                    DocumentSnapshot user = task.getResult();
                    if(task.isSuccessful()) {
                        if (user.exists()) {
                            Log.d(TAG,"Got the user " + userID);
                            String author_temp = user.get("fname").toString() + " " + user.get("lname").toString();
                            author.add(0,author_temp);
                        } else {
                            Log.d(TAG,"No such user");
                        }
                        notifyAll();
                    }

                    else {
                        Log.d(TAG, "get failed with ", task.getException());
                    }
                }
            });


            // setting the topic
            DocumentReference topicRef = fStore.collection("forum_topics").document();
            Map<String, Object> addTopic = new HashMap<>();
            addTopic.put("topic_name", topic);
            addTopic.put("date_published", date_published);
            addTopic.put("author", author.get(0));
            topicRef.set(addTopic).addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Log.d(TAG,"New Topic document created");
                }
            });

            // setting the post
            DocumentReference postRef = fStore.collection("forum_posts").document();
            Map<String, Object> addPost = new HashMap<>();
            addPost.put("topic_name", topic);
            addPost.put("date_published", date_published);
            addPost.put("author", author.get(0);
            addPost.put("content", content);
            postRef.set(addPost).addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Log.d(TAG,"New Post document created");
                }
            });
        }
    });



}

}

感谢您的所有回答!

【问题讨论】:

  • 这是因为,行 addTopic.put("author", author.get(0)); addPost.put("author", author.get(0); 在 onComplete 回调之前执行。所以当你尝试访问 author[0] 时,它没有任何内容。并且 AIOB 异常。调用 // 设置主题& // 在 OnComplete 中获得响应后设置帖子
  • 您在哪一行代码中遇到了该错误?也请回复@AlexMamo
  • @KishanMaurya 哦,伙计,我没有尝试过-.-我想是因为在以前的适配器嵌套问题中它不会也不会。非常感谢!
  • @AlexMamo 错误日志显示,第 91 行,但问题现已解决,谢谢!
  • @Mateusz 希望这能解决您的问题。

标签: java android arraylist google-cloud-firestore


【解决方案1】:

这是因为,

addTopic.put("author", author.get(0));
addPost.put("author", author.get(0);

在您收到onComplete 的回调之前执行。因此,当您尝试访问author[0] 时,它什么都没有,并且会发生 AIOB 异常。在onComplete 收到回复后,尝试设置主题并设置帖子。

   public class ForumPostTopic extends AppCompatActivity {

        public static final String TAG = "TAG";
        EditText editTopic, editContent;
        Button addTopicBtn;
        FirebaseFirestore fStore;
        FirebaseAuth fAuth;
        Date date_published;
        String userID;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_forum_post_topic);

            editTopic = findViewById(R.id.editTopic);
            editContent = findViewById(R.id.editContent);
            addTopicBtn = findViewById(R.id.addTopicBtn);

            fAuth = FirebaseAuth.getInstance();
            userID = fAuth.getCurrentUser().getUid();

            fStore = FirebaseFirestore.getInstance();

            date_published = Calendar.getInstance().getTime();



            addTopicBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final ArrayList<String> author = new ArrayList<>();


                    // getting the user
                    DocumentReference userRef = fStore.collection("users").document(userID);
                    userRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                            DocumentSnapshot user = task.getResult();
                            if(task.isSuccessful()) {
                                if (user.exists()) {
                                    Log.d(TAG,"Got the user " + userID);
                                    String author_temp = user.get("fname").toString() + " " + user.get("lname").toString();
                                    author.add(0,author_temp);
                                    setTopic(author);
                                    setPost(author);
                                } else {
                                    Log.d(TAG,"No such user");
                                }
                                notifyAll();
                            }

                            else {
                                Log.d(TAG, "get failed with ", task.getException());
                            }
                        }
                    });

                }
            });

        }

        private void setTopic(ArrayList<String> author){
            String topic = editTopic.getText().toString().trim();
            DocumentReference topicRef = fStore.collection("forum_topics").document();
            Map<String, Object> addTopic = new HashMap<>();
            addTopic.put("topic_name", topic);
            addTopic.put("date_published", date_published);
            addTopic.put("author", author.get(0));
            topicRef.set(addTopic).addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Log.d(TAG,"New Topic document created");
                }
            });
        }

        private void setPost(ArrayList<String> author){
            String topic = editTopic.getText().toString().trim();
            String content = editContent.getText().toString().trim();
            DocumentReference postRef = fStore.collection("forum_posts").document();
            Map<String, Object> addPost = new HashMap<>();
            addPost.put("topic_name", topic);
            addPost.put("date_published", date_published);
            addPost.put("author", author.get(0);
            addPost.put("content", content);
            postRef.set(addPost).addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Log.d(TAG,"New Post document created");
                }
            });
        }
    }

【讨论】:

  • 虽然这可能会回答问题,但代码块本身通常不是有用的答案,而且更有可能吸引反对票。建议解释您所展示的解决方案的作用,以及该代码为何/如何回答问题。
  • 当然@AlexMamo,感谢您的建议。我会用解释更新答案。
  • 我只是将它嵌套在 onComplete 中,它似乎可以工作,我的意思是在另一个循环之后的 if(task.isSuccessful()) { } 中
  • 虽然这似乎是更优雅的解决方案,但我会在完成所有内容并清理代码后执行此操作。你很有帮助。
猜你喜欢
  • 2011-09-28
  • 1970-01-01
  • 2023-04-08
  • 2022-08-03
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多