0

I'm trying to parse below JSON which is received from server

{"status":1,"data":{"msg":"Invertory Added","inventory_id":2001}}

Using Below

try 
{
    jObj = new JSONObject(json);
    final Integer status = jObj.getInt("status");

    if(status == 1) {
        msg="Inventory Created Successfully";
    } else { 
        msg = jObj.getString("data"); 
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    builder.setTitle("Info")
        .setMessage(msg)
        .setCancelable(false)
        .setIcon(R.drawable.ic_launcher)
        .setPositiveButton("OK", 
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    //do things
                    if(status==1)
                    {
                        displayView(6);
                    }
                }
            });

    AlertDialog alert = builder.create();
    alert.show();

} catch (JSONException e) {
    Log.e("msgtest", "unexpected JSON exception", e);
    // Do something to recover ... or kill the app.
}

Log says

E/msgtest﹕ unexpected JSON exception

org.json.JSONException: Value org.apache.http.conn.BasicManagedEntity@41f14cd0 of type java.lang.String cannot be converted to JSONObject
    at org.json.JSON.typeMismatch(JSON.java:111)
    at org.json.JSONObject.<init>(JSONObject.java:158)
    at org.json.JSONObject.<init>(JSONObject.java:171)
    at info.androidhive.wolf.NewInventoryFragment$submitAction.onPostExecute(NewInventoryFragment.java:575)
    at info.androidhive.wolf.NewInventoryFragment$submitAction.onPostExecute(NewInventoryFragment.java:388)

at line #575 jObj = new JSONObject(json);


AsyncTask

@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(getActivity());
    pDialog.setMessage("Loading");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    pDialog.show();
}

@Override
protected String doInBackground(String... arg0) {
    // TODO Auto-generated method stub
    File file1 = new File(selectedPath1);
    File file2 = new File(selectedPath2);
    File file3 = new File(selectedPath3);
    File file4 = new File(selectedPath4);
    File file5 = new File(selectedPath5);
    String urlString="http://url/index.php";

    List<NameValuePair> params = new ArrayList<NameValuePair>();

    try
    {
        FileBody bin2 = new FileBody(file2);
        FileBody bin3 = new FileBody(file3);
        FileBody bin4 = new FileBody(file4);
        FileBody bin5 = new FileBody(file5);

        params.add(new BasicNameValuePair("section","inventory"));
        params.add(new BasicNameValuePair("action","new"));
        params.add(new BasicNameValuePair("apron_id",stock_number_ele.getText().toString()));
        params.add(new BasicNameValuePair("nickname",nick_name_ele.getText().toString()));
        params.add(new BasicNameValuePair("location",location));
        params.add(new BasicNameValuePair("manufacture",manufacture));
        params.add(new BasicNameValuePair("core_material",core_material_ele.getText().toString()));
        params.add(new BasicNameValuePair("color",color_ele.getText().toString()));
        params.add(new BasicNameValuePair("Date_purchase",dop_ele.getText().toString()));
        params.add(new BasicNameValuePair("UID_no",gtin_uid_ele.getText().toString()));
        params.add(new BasicNameValuePair("serial",serial_ele.getText().toString()));
        params.add(new BasicNameValuePair("Batch",batch_lot_ele.getText().toString()));
        params.add(new BasicNameValuePair("Expiration",ed_ele.getText().toString()));
        params.add(new BasicNameValuePair("garment_type",description_ele.getText().toString()));
        params.add(new BasicNameValuePair("QTY",county_ele.getText().toString()));
        params.add(new BasicNameValuePair("user_id",SignInActivity.user_id));*/

        HttpClient client = new DefaultHttpClient();

        HttpPost post = new HttpPost(urlString);

        FileBody bin1 = new FileBody(file1);
        FileBody bin2 = new FileBody(file2);
        FileBody bin3 = new FileBody(file3);
        FileBody bin4 = new FileBody(file4);
        FileBody bin5 = new FileBody(file5);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("section", new StringBody("inventory"));
        reqEntity.addPart("action", new StringBody("new"));
        reqEntity.addPart("apron_id", new StringBody(stock_number_ele.getText().toString()));
        reqEntity.addPart("nickname", new StringBody(nick_name_ele.getText().toString()));
        reqEntity.addPart("location", new StringBody(location+""));
        reqEntity.addPart("manufacture", new StringBody(manufacture+""));
        reqEntity.addPart("core_material", new StringBody(core_material_ele.getText().toString()));
        reqEntity.addPart("color", new StringBody(color_ele.getText().toString()));
        reqEntity.addPart("Date_purchase", new StringBody(dop_ele.getText().toString()));
        reqEntity.addPart("UID_no", new StringBody(gtin_uid_ele.getText().toString()));
        reqEntity.addPart("serial", new StringBody(serial_ele.getText().toString()));
        reqEntity.addPart("Batch", new StringBody(batch_lot_ele.getText().toString()));
        reqEntity.addPart("Expiration", new StringBody(ed_ele.getText().toString()));
        reqEntity.addPart("garment_type", new StringBody(description_ele.getText().toString()));
        reqEntity.addPart("QTY", new StringBody(county_ele.getText().toString()));
        reqEntity.addPart("user_id", new StringBody(SignInActivity.user_id));

        if(selectedPath1!="NONE")
            reqEntity.addPart("image1", bin1);

        if(selectedPath2!="NONE") {
            Log.d("Image2","Image2");
            reqEntity.addPart("image2", bin2);
        }

        if(selectedPath3!="NONE") {
            Log.d("Image3","Image2");
            reqEntity.addPart("image3", bin3);
        }

        if(selectedPath4!="NONE") {
            Log.d("Image4","Image2");
            reqEntity.addPart("image4", bin4);
        }

        if(selectedPath5!="NONE") {
            Log.d("Image5","Image2");
            reqEntity.addPart("image5", bin5);
        }

        post.setEntity(reqEntity);
        HttpResponse response = client.execute(post);
        resEntity = response.getEntity();
        final String response_str = EntityUtils.toString(resEntity);

        if (resEntity != null) {
            Log.i("RESPONSE",response_str);
        }
    }
    catch (Exception ex)
    {
        Log.e("Debug", "error: " + ex.getMessage(), ex);
    }

    return resEntity.toString();
}

@SuppressWarnings("deprecation")
//@Override
protected void onPostExecute(String json) {

    String msg="";
    JSONArray jArray=null;

    if (pDialog.isShowing()) {
        pDialog.dismiss();
    }

    try 
    {
        jObj = new JSONObject(json);
        final Integer status = jObj.getInt("status");
        msg = jObj.getString("data"); // get the name from data.

        if (status == 1) {
            msg="Inventory Created Successfully";
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        builder.setTitle("Info")
            .setMessage(msg)
            .setCancelable(false)
            .setIcon(R.drawable.ic_launcher)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    if(status==1)
                    {
                        displayView(6);
                    }
                }
            });

            AlertDialog alert = builder.create();
            alert.show();

    }
    catch (JSONException e) 
    {
        Log.e("msgtest", "unexpected JSON exception", e);
        // Do something to recover ... or kill the app.
    }
}

Please suggest your views . Thanks in advance.

4
  • post the whole AsyncTask Commented May 4, 2015 at 14:05
  • that is a lot to paste . Is it not enough to get it @Blackbelt Commented May 4, 2015 at 14:07
  • no it is not. The string you posted is a valid json. So you are probably messing somewhere else. May not the whole AsyncTask.. How are you converting the input stream in string ? Commented May 4, 2015 at 14:08
  • msg = jObj.getString("data"); returns JSONObject["data"] and you are trying to assign it to a String object. It would throw JSONExceptioin. Commented May 4, 2015 at 14:34

2 Answers 2

1

your are correctly using EntityUtils.toString to read the content of the entity and as a String, but you are returning the wrong object in doInBackground. Instead of returning resEntity.toString();, you have to return response_str.

Sign up to request clarification or add additional context in comments.

Comments

0

I think I know why this code is failing.

in your code you have :

try 
{
    jObj = new JSONObject(json);
    final Integer status = jObj.getInt("status");

    if(status == 1)
    {
        msg = "Inventory Created Successfully";
    }
    else
    { 
        msg = jObj.getString("data"); 
    }

    ...

} 
catch (JSONException e) 
{
    Log.e("msgtest", "unexpected JSON exception", e);
    // Do something to recover ... or kill the app.
}

You said that you were receiving JSON messages like this (I added the types of the fields):

// "Main" Object
{
    "status": 1,  // Integer
    "data":       // Object
    {
        "msg" : "Invertory Added", // String
        "inventory_id" : 2001      // Integer
    }
}

So in your code when you try this msg = jObj.getString("data"); you ask a String BUT in your JSON message "data" is of the type Object which is why you get this Error.

So instead you should do this :

try 
{
    jObj = new JSONObject(json);
    final Integer status = jObj.getInt("status");

    if(status == 1) 
    {
        msg = "Inventory Created Successfully";
    }
    else
    { 
        // Here is the change
        // you should also change the type of msg to JSONObject
        // and probably the name of the variable for a better understanding 
        msg = jObj.getObject("data"); 
    }

    // And of course handle this object accordingly
    // Example : String message = msg.getString("msg");

    ...

} 
catch (JSONException e) 
{
    Log.e("msgtest", "unexpected JSON exception", e);
    // Do something to recover ... or kill the app.
}

If I am guessing right you wanted to retrieve the "msg" field inside the "data" Object. You can simply get it like so :

String message = jObj.getObject("data").getString("msg");

Hope this helps,

Cheers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.