我需要从php脚本中检索一个JSON数组,然后使用volley将值放入TextView和Button项中,据我所知,php脚本工作正常并返回这样的Json数组(使用POSTMAN测试);
[{"ID":"5","CAT":"R","PREG":"E","RESP1":"o","RESP2":"ao","RESP3":"Fa","RESPC":"Oc","id":"4.306107120873506"}]
我有互联网许可,并且清单中设置排球的所有内容(因为我的POST请求正常)但我无法使其正常工作,这是方法;
private void retrieveQuestion() {
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, Constants.URL_RETRIEVE, null, new Response.Listener<JSONObject>() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onResponse(JSONObject response) {
try {
JSONArray arr = new JSONArray(response);
JSONObject jObj = arr.getJSONObject(0);
textViewCategoria.setText(jObj.getString("CAT"));
textViewPregunta.setText(jObj.getString("PREG"));
buttonResp1.setText(jObj.getString("RESP1"));
buttonResp2.setText(jObj.getString("RESP2"));
buttonResp3.setText(jObj.getString("RESP3"));
buttonResp4.setText(jObj.getString("RESPC"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
RequestHandler.getInstance(this).addToRequestQueue(jsObjRequest);
}
当我点击一个按钮时,retrieveQuestion()方法必须运行但它什么都不做(按钮完全没有效果)我不知道为什么......我使用带有RequestQueue的Singleton模式,我可以发布它, PHP脚本或整个活动,如果需要,但我很确定问题是在该方法。
答案 0 :(得分:0)
每当您想要更新线程中的UI元素时,
您必须使用runOnUiThread func来更新UI元素
=
答案 1 :(得分:0)
你可以试试像...... Json看起来像
{"ParentNode":[{"ID":"1","CAT":"R"}]}
凌空全方法吼叫
private void doLoginAction() {
pDialog.show();
String url_login = "http://era.com/test_sstem/public/login";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_login,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//pDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray loginNodes = jsonObject.getJSONArray("ParentNode");
for (int i = 0; i < loginNodes.length(); i++) {
JSONObject jo = loginNodes.getJSONObject(i);
String ID = jo.getString("ID");
String CAT = jo.getString("CAT");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
try {
if (error instanceof TimeoutError ) {
//Time out error
}else if(error instanceof NoConnectionError){
//net work error
} else if (error instanceof AuthFailureError) {
//error
} else if (error instanceof ServerError) {
//Erroor
} else if (error instanceof NetworkError) {
//Error
} else if (error instanceof ParseError) {
//Error
}else{
//Error
}
//End
} catch (Exception e) {
}
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("uname", "era@gmail.com");
params.put("pass", "123456");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}