Search code examples
androidinitializationandroid-volleyglobal

Global variable are not being initialized from within a listener


I'm trying to initialize a global ArrayList from within a listener (to deal with JSONArray objects from the Volley library in different places of the code). However, when I try to access it in the Oncreate method it seems to be uninitialized.

I tried the same with different static and non-static variables i.g. int[], String, etc. but the problem seems to persist.

NOTE: The Question class is used for app development purposes:

public class Question {

private String question;
private boolean answer;



public Question(String question, boolean answer){
    this.question = question;
    this.answer = answer;
}

public String getQuestion() {
    return question;
}

public boolean isAnswer() {
    return answer;
}

}

public class MainActivity extends AppCompatActivity implements View.OnClickListener {




private String url = "https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json";
private static  ArrayList<Question> questionArrayList = new ArrayList<>();
int  [] intArr = new int[10];
String str = "Hello";



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



    // calling the method where the variables are re-initialized
    getQuestions();

    // printing results after re-initialization
    System.out.println("Mainactivity======================");
    System.out.println("intArray: "+ intArr[0]);
    System.out.println("STR: "+ str);
    System.out.println(questionArrayList.get(0).getQuestion());





}



public void getQuestions(){

    JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONArray>() {

               // Response Listener
                @Override
                public void onResponse(JSONArray response) {


                    // Test variables:
                    MainActivity.this.intArr[0] = 110;
                    str = "HI";



                    for(int i=0; i< response.length(); i++){
                        try {
                            // initializing ArrayList<Question>
                            questionArrayList.add(new Question(response.getJSONArray(i).getString(0), response.getJSONArray(i).getBoolean(1) ));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }




                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

   RequestQueue queue = Volley.newRequestQueue(this);
   queue.add(arrayRequest);


}

}

output:

I/System.out: Mainactivity======================

I/System.out: intArray: 0

STR: Hello

D/AndroidRuntime: Shutting down VM E/AndroidRuntime: FATAL EXCEPTION: main Process: myapp.com.triviaapp, PID: 29167 java.lang.RuntimeException: Unable to start activity ComponentInfo{myapp.com.triviaapp/myapp.com.triviaapp.MainActivity}: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0


Solution

  • The String is getting modified by the listener, however the listener is getting executing at some later point in time, after onCreate has finished. If you add a second log within the listener you will see that it gets called afterwards. This is because the listener doesn't get executed until it gets a response from the network, which will always take longer than it will take for onCreate to finish executing