【发布时间】:2019-03-29 10:36:26
【问题描述】:
我正在创建一个 Android 应用程序,但我被困在某一点上,不知道该怎么做。我正在调用网络服务并获取 JSON 值。然后我将该值设置为TextView 字段。但是我面临的问题是当页面加载时,将值设置为TextView 已经很晚了。有时该值未设置为TextView。因此,在继续执行另一个函数之前,我必须检查该值,如果该值未设置为,则再次调用以下方法。
调用 Web 服务并获取值并将文本设置为
TextValue
private void getJsonRequest() {
String tag_string_req = "req_data";
request = new StringRequest(Request.Method.POST, "URL", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.names().get(0).equals("res")) {
JSONArray array = jsonObject.getJSONArray("res");
JSONObject obj = array.getJSONObject(0);
String value = obj.getString("value");
spin.setText(value);
} else {
Toast.makeText(getApplicationContext(), "No Value Available", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
hashMap = new HashMap<String, String>();
hashMap.put("uid", userID);
return hashMap;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(15 * 1000, 1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(request, tag_string_req);
}
然后我在onCreate()内部调用了那个方法。
protected void onCreate(Bundle savedInstanceState) {
//There are more codes,
getJsonRequest();
}
所以我需要在页面加载时设置该值。在我看到必须设置值的页面之前。我怎样才能做到这一点?
【问题讨论】:
-
保持 UI 会很糟糕,而是显示进度条来保持用户交互。
-
有个东西叫ASYNC TASK
-
如果有人能提供一些代码sn-p,我真的很感激?
标签: android json android-volley