我试图使用JsonArrayRequest检索json数据。这是我执行此操作的代码
public class QuestionDetailFragment extends Fragment {
private static final String url = "http://10.0.2.2:80/forumtest/readquestion.php?format=json";
private String data;
RequestQueue requestQueue;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.question_details_layout, container, false);
readQuestionDetails();
Log.d("user","data:"+data);
return view;
}
private void readQuestionDetails() {
requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, url, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
for (int i=0;i<response.length();i++) {
JSONObject jsonObject = response.getJSONObject(i);
data=jsonObject.getString("user");
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("user",e.getMessage());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("user", error.getMessage());
}
});
requestQueue.add(jsonArrayRequest);
}
}
问题在于,当我在循环中使用数据变量时,它返回所需的值,但每当我尝试在循环外使用数据变量时(让我们说当我使用onCreateView中的数据时),它返回null值。
答案 0 :(得分:0)
这是因为JsonArrayRequest被添加到异步执行任务的排队队列中。因此,即使您在Log.d("tag","data:"+data);
之后调用readQuestionDetails()
请求尚未执行,也意味着data
为空。
这样的事情会起作用:
public class QuestionDetailFragment extends Fragment {
private static final String url = "http://10.0.2.2:80/forumtest/readquestion.php?format=json";
private String data;
RequestQueue requestQueue;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.question_details_layout, container, false);
readQuestionDetails();
return view;
}
private void readQuestionDetails() {
requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, url, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
for (int i=0;i<response.length();i++) {
JSONObject jsonObject = response.getJSONObject(i);
data=jsonObject.getString("user");
printData(data);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("user",e.getMessage());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("user", error.getMessage());
}
});
requestQueue.add(jsonArrayRequest);
}
private void printData(String data){
Log.d("user","data:"+data);
}
}