全局变量未从侦听器内部初始化

时间:2019-05-20 14:21:21

标签: android initialization android-volley global

我正在尝试从侦听器内部初始化全局ArrayList(以在代码的不同位置处理Volley库中的JSONArray对象)。但是,当我尝试使用Oncreate方法访问它时,它似乎尚未初始化。

我尝试了不同的静态和非静态变量,例如int [],String等,但问题似乎仍然存在。

注意: Question类用于应用程序开发目的:

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


}

}

输出:

I / System.out:主要活动性======================

I / System.out:intArray:0

STR:您好

D / AndroidRuntime:关闭VM E / AndroidRuntime:致命异常:main     流程:myapp.com.triviaapp,PID:29167     java.lang.RuntimeException:无法启动活动ComponentInfo {myapp.com.triviaapp / myapp.com.triviaapp.MainActivity}:java.lang.IndexOutOfBoundsException:索引:0,大小:0

2 个答案:

答案 0 :(得分:0)

侦听器正在修改String,但是在onCreate完成之后,侦听器将在稍后的某个时间执行。如果在侦听器中添加第二个日志,您将看到它随后被调用。这是因为侦听器直到从网络获得响应才被执行,这总是比onCreate完成执行所需的时间长。

答案 1 :(得分:0)

System.out.println(questionArrayList.get(0).getQuestion()); <-在这里您会崩溃,因为数组列表为空。

您可以在获得结果后放入打印信息:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // calling the method where the variables are re-initialized
    getQuestions();
}
@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();
        }
    }

    System.out.println("Mainactivity======================");
    System.out.println("intArray: "+ intArr[0]);
    System.out.println("STR: "+ str);
    if (!questionArrayList.isEmpty()) { // and check if we have at least one element
        System.out.println(questionArrayList.get(0).getQuestion());
    }
}