Android - Validating JSON when getting a response from a server to avoid a JSONException

孤街浪徒 提交于 2019-12-06 07:02:45
O__O

You have to make sure you do the parsing after doing a null check/or any other validation like checking if it contains the response code before doing any operation on the String result.

protected void onPostExecute(String result) 
{  
try{

    String foodName="";
    int Description=0;

if(result!=null)//Do your validation for result

{
    jArray = new JSONArray(result); // here if the result is null an exeption will occur
    JSONObject json_data = null;

    for (int i = 0; i < jArray.length(); i++) {
        json_data = jArray.getJSONObject(i);
        foodName=json_data.getString("Name");
        .
        .
        .
        .
        .
    } 
 }
   catch(JSONException e){ 
        **// what i can do here to prevent my app from crash and 
        //  make toast " the entered food isnot available " ????**
        Log.e("log_tag", "parssing  error " + e.toString()); 
    }   
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!