【发布时间】:2019-03-12 09:28:01
【问题描述】:
如何通过 json 对象键获取字符串以显示未找到的数据, 如果 json 数组数据可用,则以下代码可以完美运行。当没有找到数据时会显示截击错误,如 as
com.android.volley.ClientError
public void posLoad(){
progressBar.setVisibility(View.VISIBLE);
String url = getString(R.string.myPostLoad)+"01858456388";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
String err = jsonObject.getString("message");
if (err.equals("no")){
Toast.makeText(MyPosts.this,"No post found",Toast.LENGTH_SHORT).show();
}else{
JSONArray jsonArrayData = jsonObject.getJSONArray("posts");
for (int i=0; i<jsonArrayData.length(); i++){
Post post = new Post();
JSONObject jsonObject1 = jsonArrayData.getJSONObject(i);
//user data
post.setName(jsonObject1.getString("name"));
post.setEmail(jsonObject1.getString("email"));
post.setPhoto(jsonObject1.getString("photo"));
postList.add(post);
}
}
progressBar.setVisibility(View.GONE);
}catch (JSONException e){
e.printStackTrace();
}
postAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
Toast.makeText(MyPosts.this,error.toString(),Toast.LENGTH_SHORT).show();
}
});
MySingleton.getInstance().addToRequestQueue(stringRequest);
}
(1) json 响应是当数据未找到时
{"消息":"否"}
(1) json 响应是找到数据时
{"posts":[{"name":"Saif ullah","email":"nzsn","photo":"01858456387.png","created_at":"2012-03-19 12:57 :42","updated_at":"2012-03-19 12:57:42"}]}
找不到数据的服务器脚本
echo json_encode(array("message" => "no"));
从第一个响应没有得到字符串。 我该如何解决......帮帮我......
【问题讨论】:
-
发布您的 JSON 响应。
-
显示异常堆栈跟踪
-
编辑您的主帖,不要在 cmets 中发布 JSON。
-
发布完整的堆栈跟踪错误
-
我已经发布了 JSON 响应。