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

Android 当我的JSON中没有值时,我的应用程序崩溃,android,Android,我正在发布“id”值(通过getintent传递给此活动) 到服务器并检索相应的JSONObject @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("id", Uid);

我正在发布“id”值(通过getintent传递给此活动)

到服务器并检索相应的JSONObject

@Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("id", Uid);
            return params;
        }
@覆盖
受保护的映射getParams(){
Map params=新的HashMap();
参数put(“id”,Uid);
返回参数;
}
当我的jsonarray为空时,我的应用程序崩溃。当jsonarray为空时,我想吐司“Error”。我怎样才能解决这个问题

这是我的密码:

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);
}


}
public类kill扩展了碎片活动{
GridView grid1;
自定义网格相册适配器;
私人对话;
字符串Uid,Disp;
公共字符串类别;
选择公共字符串;
公共静态字符串imagename;
按钮Alb_选择;
ArrayList gridArray=新的ArrayList();
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.album_显示);
grid1=(GridView)findViewById(R.id.gridView2);
Uid=getIntent().getStringExtra(“id”);
Disp=getIntent().getStringExtra(“Disp”);
Alb_sel=(按钮)findviewbyd(R.id.album_to_select);
pDialog=newprogressdialog(kill.this);
设置消息(“加载…”);
pDialog.show();
//获取JSONArray
final RequestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest StringRequest=新建StringRequest(com.android.volley.Request.Method.POST,AppConfig.URL\u Gallery4,
新的Response.Listener(){
@凌驾
公共void onResponse(字符串响应){
Datas.imageIds=新字符串[response.length()];
JSONArray arr=null;
试一试{
arr=新JSONArray(响应);
}捕获(JSONException e1){
e1.printStackTrace();
}
int i=0;
对于(i=0;i
在响应上应用签入

if(response.length()==0){
// error message
}else{
// your rest of the code
}

我只想在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();
    }

    ...

您已声明
JSONArray arr=null

然后将服务器的JSON分配给该JSONArray

在获得该信息后添加一行

if(arr==null)
{
 //toast
}
else
{
//whatever you want to do with JSON
}
StringRequest StringRequest=newstringrequest(com.android.volley.Request.Method.POST,AppConfig.URL\u Gallery4,
新的Response.Listener(){
@凌驾
公共void onResponse(字符串响应){
if(response.length()==0){
Toast.makeText(getActivity(),“找不到数据”,Toast.LENGTH_SHORT.show();
}
否则{
Datas.imageIds=新字符串[response.length()];
JSONArray arr=null;
试一试{
arr=新JSONArray(响应);
}捕获(JSONException e1){
e1.printStackTrace();
}
如果(阵列长度()>0){
int i=0;
对于(i=0;iif(arr==null)
{
 //toast
}
else
{
//whatever you want to do with JSON
}
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;
        }

    };
Datas.imageIds = new String[response.length()];
public void onResponse(String response) {
    JSONArray arr = null;

    try {
        arr = new JSONArray(response);
        Datas.imageIds = new String[arr.length()];
    } catch (JSONException e1) {
        e1.printStackTrace();
    }
arr = new JSONArray(response);
if (arr.length() == 0) {
    // TODO: Toast
}
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();
}
}
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
           Log.e(TAG, "onErrorResponse: "+error.getMessage() );
        }
    })