String is not getting added to the ArrayList in OnClick Listener after getting the data from Firestore

Mateusz :

I try to create a Forum application in FirebaseFirestore, I already have it display the topics, but when I want to add a new topic it gets the user data from the collection ("fname" and "lname" and puts them together as one name) but it appears it doesn't add them to the ArrayList which has to be declared final as it is called from OnComplete function. I get this error:

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)

It indicates that the Array is empty, If you know how to update it I would be grateful or maybe another way around that, maybe there is something simpler that can be done to achieve the result. The Code is below:

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");
                }
            });
        }
    });



}

}

Thank You for all your answers!

Kishan Maurya :

This is because,

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

are executed before you get a callback on onComplete. So when you are trying to access author[0], it has nothing and an AIOB exception occurs. Try setting the topic & setting the post after you get a response in 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");
                }
            });
        }
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=17035&siteId=1
Recommended