我正在创建多个选择测试,我试图使用volley从服务器检索数据,当我调用这个方法时,我从服务器获得响应,但是方法返回NULL。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = loadJsonArray();
rb4.setText(contactList.toString());
public ArrayList<Questions> loadJsonArray() {
JsonArrayRequest jsArrayRequest = new JsonArrayRequest
(Request.Method.GET, obj_url, null, new Response.Listener<JSONArray>() {
public ArrayList<Questions> contactList = new ArrayList<>();
public Questions questions = new Questions();
@Override
public void onResponse(JSONArray responseArray) {
try {
//ArrayList<Questions> contactList = new ArrayList<>();
//Parse the JSON response array by iterating over it
for (int i = 0; i < responseArray.length(); i++) {
JSONObject response = responseArray.getJSONObject(i);
//Questions questions = new Questions();
questions.setId(response.getInt("q_id"));
questions.setQuestions(response.getString("q_name"));
questions.setOption1(response.getString("q_opt1"));
questions.setOption2(response.getString("q_opt2"));
questions.setOption3(response.getString("q-opt3"));
questions.setAnswerNr(response.getInt("1"));
questions.setDifficulty(response.getString("easy"));
contactList.add(questions);
}
//rb4.setText(contactList.toString()); //when i ckeked there it is working fine
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Display error message whenever an error occurs
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
// rb4.setText(contactList.toString());
return contactList;
}
and i got following error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.util.ArrayList.toString()' on a null object reference
at com.access.myquiz.QuizActivity.loadJsonArray(QuizActivity.java:190)
is there any way to return volley response
发布于 2019-06-10 11:48:16
Volley异步加载。loadJsonArray
返回一个空数组,因为尚未收到Web服务器的响应。我将参考关于如何正确处理异步请求的Volley文档
https://stackoverflow.com/questions/-100006960
复制相似问题