当我的JSON中没有值时,我的应用程序崩溃了

时间:2016-10-18 09:22:56

标签: android

我发布了“id”值(我通过getintent传递给了这个活动)

Uid = getIntent().getStringExtra("id");

到服务器并检索相应的jsonobjects。

@Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("id", Uid);
            return params;
        }

当我的jsonarray为空时,我的应用程序崩溃了。我想在jsonarray为空时敬酒“错误”。我怎样才能解决这个问题?

这是我的代码:

public class kill extends FragmentActivity {
GridView grid1;
CustomGrid_Album adapter;
private ProgressDialog pDialog;
String Uid,Disp;
public String category;
public String selected;
public static String imagename;
Button Alb_sel;
ArrayList<Item_album> gridArray = new ArrayList<Item_album>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.album_display);

    grid1 = (GridView) findViewById(R.id.gridView2);
    Uid = getIntent().getStringExtra("id");
    Disp = getIntent().getStringExtra("disp");

    Alb_sel=(Button)findViewById(R.id.album_to_select);

    pDialog = new ProgressDialog(kill.this);
    pDialog.setMessage("Loading...");
    pDialog.show();

    //fetching JSONArray

    final RequestQueue queue = Volley.newRequestQueue(getApplicationContext());

    StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Datas.imageIds = new String[response.length()];
                    JSONArray arr = null;

                    try {
                        arr = new JSONArray(response);

                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }
                    int i=0;

                    for (i = 0; i < arr.length(); i++) {
                        try {

                            JSONObject obj = arr.getJSONObject(i);
                            category = obj.getString("category_name");
                            selected = obj.getString("album_id");
                            imagename  = obj.getString("org_image_name");

                            Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);

                            gridArray.add(new Item_album(Datas.imageIds[i]));


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    final int xl = i;
                    adapter = new CustomGrid_Album(kill.this,xl,gridArray);
                    adapter.notifyDataSetChanged();
                    grid1.setAdapter(adapter);
                    pDialog.dismiss();


                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
            error.printStackTrace();

        }

    })

    {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("id", Uid);
            return params;
        }

    };

    queue.add(stringRequest);
}


}

7 个答案:

答案 0 :(得分:1)

onResponse

中应用支票
if(response.length()==0){
// error message
}else{
// your rest of the code
}

答案 1 :(得分:1)

这看起来有问题。

Datas.imageIds = new String[response.length()];

您不希望数组具有字符串的大小。您需要响应中的JSONArray 大小的数组

public void onResponse(String response) {
    JSONArray arr = null;

    try {
        arr = new JSONArray(response);
        Datas.imageIds = new String[arr.length()];
    } catch (JSONException e1) {
        e1.printStackTrace();
    }

但是,如果在那里抛出异常,你的代码将继续运行,那么你最终会得到一个NullPointerException,因此你也应该将for循环移动到try-catch

但实际上,如果你期望JSONArrayRequest,你应该使用JSONArray

  

我想在jsonarray为空时敬酒“错误”

足够简单。

arr = new JSONArray(response);
if (arr.length() == 0) {
    // TODO: Toast
}

答案 2 :(得分:0)

我只需在onResponse方法中添加两项检查:

...

public void onResponse(String response) {
    // Check if the response itself is an empty string or null
    if(TextUtils.isEmpty(response)) {
        // Show your user feedback
        return;
    }

    Datas.imageIds = new String[response.length()];
    JSONArray arr = null;

    try {
        arr = new JSONArray(response);

        // Check if your JSON has no elements in it
        if(arr.length == 0) {
            // Show your user feedback
            return;
        }
    } catch (JSONException e1) {
        e1.printStackTrace();
    }

    ...

答案 3 :(得分:0)

您已声明JSONArray arr = null;

之后,将服务器的JSON分配给该JSONArray。

获得

后添加一行
if(arr==null)
{
 //toast
}
else
{
//whatever you want to do with JSON
}

答案 4 :(得分:0)

StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                if(response.length()==0){
                    Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
                    }
                    else{                   
                            Datas.imageIds = new String[response.length()];
                            JSONArray arr = null;

                            try {
                                arr = new JSONArray(response);

                            } catch (JSONException e1) {
                                e1.printStackTrace();
                            }

                        if(arr.length()>0){
                            int i=0;

                            for (i = 0; i < arr.length(); i++) {
                                try {

                                    JSONObject obj = arr.getJSONObject(i);
                                    category = obj.getString("category_name");
                                    selected = obj.getString("album_id");
                                    imagename  = obj.getString("org_image_name");

                                    Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);

                                    gridArray.add(new Item_album(Datas.imageIds[i]));


                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            final int xl = i;
                            adapter = new CustomGrid_Album(kill.this,xl,gridArray);
                            adapter.notifyDataSetChanged();
                            grid1.setAdapter(adapter);
                        }else{
                        Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
                        }
                    }



                    pDialog.dismiss();


                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
            error.printStackTrace();

        }

    })

    {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("id", Uid);
            return params;
        }

    };

答案 5 :(得分:0)

使用以下代码检查响应是否为null,并在对象中检查它是否具有键或具有键的数据不为空

if(response!=null){

   try {
   Datas.imageIds = new String[response.length()];
   JSONArray arr = new JSONArray(response);
   for (int i = 0; i < arr.length(); i++) {
      try {
               JSONObject obj = arr.getJSONObject(i);
               if(obj!=null){
                  if(obj.has("category_name") && !obj.isNull("category_name"){
                      category = obj.getString("category_name");
                  }
                  if(obj.has("album_id") && !obj.isNull("album_id"){
                       selected = obj.getString("album_id");
                  }
                  if(obj.has("org_image_name") && !obj.isNull("org_image_name"){
                        imagename  = obj.getString("org_image_name");
                  }
                   if(obj.has("album_image") && !obj.isNull("album_image"){                     
                          Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
                          gridArray.add(new Item_album(Datas.imageIds[i]));
                  }
           }
        } catch (JSONException e) {
            e.printStackTrace();
        }
      }

      final int xl = i;
      adapter = new CustomGrid_Album(kill.this,xl,gridArray);
      adapter.notifyDataSetChanged();
      grid1.setAdapter(adapter);
      pDialog.dismiss();
} catch (JSONException e1) {
     e1.printStackTrace();
}
}

答案 6 :(得分:0)

您正在使用StringRequest,而不是使用JsonArrayRequest来发出请求,如下所示,当响应中存在有效的JSONArray时,您将在onResponse方法中获得响应,如果没有数据,那么您将在onError方法中获得响应

JsonArrayRequest rReq = new JsonArrayRequest(Request.Method.GET,&#34; url&#34;,new JSONObject(),new Response.Listener(){             @覆盖             public void onResponse(JSONArray response){                 Log.e(TAG,&#34; onResponse:&#34; + response.toString());

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
           Log.e(TAG, "onErrorResponse: "+error.getMessage() );
        }
    })