11

I am parsing data from URL , Its Getting below mentioned Error.

Raw Data is Showing Perfectly from Server.Not able to Split the Data Using Json Parsing.

Please help me solve this error

EDIT : 1

Json Response from URL

[
    {
        "ID": 4,
        "Name": "Vinoth",
        "Contact": "1111111111",
        "Msg": "1"
    },
    {
        "ID": 5,
        "Name": "Mani",
        "Contact": "22222222",
        "Msg": "1"
    },
    {
        "ID": 6,
        "Name": "Manoj",
        "Contact": "33333333333",
        "Msg": "1"
    }
]

Error :

org.json.JSONException: Value [{"ID":1,"Name":"Lalita","Contact":"9997162499","Msg":"1"},{"ID":2,"Name":"kumar","Contact":"123456789","Msg":"1"}] of type java.lang.String cannot be converted to JSONArray
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:96)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:108)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at com.knowledgeflex.restapidemo.MainActivity$LoadService.onPostExecute(MainActivity.java:135)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at com.knowledgeflex.restapidemo.MainActivity$LoadService.onPostExecute(MainActivity.java:58)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.AsyncTask.finish(AsyncTask.java:632)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.Looper.loop(Looper.java:136)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5584)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at java.lang.reflect.Method.invoke(Method.java:515)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
12-11 18:23:27.259 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
12-11 18:23:27.259 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at dalvik.system.NativeStart.main(Native Method)

MainActivity.java

public class MainActivity extends Activity {

    TextView name1,email,status,face;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Button GetServerData = (Button) findViewById(R.id.button1);


      name1 = (TextView)findViewById(R.id.sname);
       email = (TextView)findViewById(R.id.email);
         status = (TextView)findViewById(R.id.status);
       face = (TextView)findViewById(R.id.fb);

        GetServerData.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

                // Server Request URL
                String serverURL = "http://webapp/api/values";

                // Create Object and call AsyncTask execute Method
                new LoadService().execute(serverURL);

            }
        });

    }


    // Class with extends AsyncTask class
    private class LoadService extends AsyncTask<String, Void, Void> {

        private final HttpClient Client = new DefaultHttpClient();
        private String Content;
        private String Error = null;
        private final String TAG = null;
        String name = null;
        private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);

        TextView uiUpdate = (TextView) findViewById(R.id.textView2);

        protected void onPreExecute() {
            // NOTE: You can call UI Element here.

            // UI Element
            uiUpdate.setText("");
            Dialog.setMessage("Loading service..");
            Dialog.show();
        }

        // Call after onPreExecute method
        protected Void doInBackground(String... urls) {
            try {

                // NOTE: Don't call UI Element here.

                HttpGet httpget = new HttpGet(urls[0]);
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                Content = Client.execute(httpget, responseHandler);

            } catch (ClientProtocolException e) {
                Error = e.getMessage();
                cancel(true);
            } catch (IOException e) {
                Error = e.getMessage();
                cancel(true);
            }

            return null;
        }

        protected void onPostExecute(Void unused) {
            // Close progress dialog
            Dialog.dismiss();
            Log.e(TAG, "------------------------------------- Output: " + Content);


            try {
                JSONArray jArr=new JSONArray(Content);
                for(int i=0;i<jArr.length();i++) {
                    JSONObject json=jArr.getJSONObject(i);


                    name1.setText(json.getString("Name"));
                    email.setText(json.getString("ID"));
                    status.setText(json.getString("Contact"));
                    face.setText(json.getString("Msg"));

                }

            } catch (JSONException e) {
                e.printStackTrace();
                Log.i("EXCEPTION   ","");
            }

            uiUpdate.setText("Raw Output : " + Content);
        }



    }


}
Chirag Savsani
  • 6,020
  • 4
  • 38
  • 74
Kumar
  • 969
  • 2
  • 22
  • 56
  • you are return JSONArray change to return JSONObject i think solve your problem – Saif Dec 11 '15 at 13:03
  • I recommend that you don't parse it yourself. Try using `Gson` to parse your JSON its easier. – Jelle van Es Dec 11 '15 at 13:03
  • so this code Will not work? – Kumar Dec 11 '15 at 13:07
  • Try this tutorial http://www.androidhive.info/2014/09/android-json-parsing-using-volley/ – Anoop Kanyan Dec 11 '15 at 13:09
  • my json response not having any Json Array Name,what to do for that? – Kumar Dec 11 '15 at 13:11
  • check this http://stackoverflow.com/questions/10164741/get-jsonarray-without-array-name – Anoop Kanyan Dec 11 '15 at 13:24
  • your json is having pure array, this is correct form. There is no defect in schema. – learner Dec 11 '15 at 13:47
  • ya, its only pure array. – Kumar Dec 11 '15 at 13:50
  • try String jsonString = EntityUtils.toString(response.getEntity()) and then convert it to array – Anoop Kanyan Dec 11 '15 at 14:12
  • @AnoopKanyan i tried,Not working this code. – Kumar Dec 12 '15 at 05:56
  • Try-Catch block for good approach .Okay You can test this .Avoid `try-catch` for testing case `JSONArray jsonarray = new JSONArray(Content); for (int i = 0; i < jsonarray.length(); i++) { JSONObject jsonobj = jsonarray.getJSONObject(i); System.out.println("ID : " + i + " = " + jsonobj.getString("ID")); System.out.println("Name : " + i + " = " + jsonobj.getString("Name")); System.out.println("Contact : " + i + " = " + jsonobj.getString("Contact")); System.out.println("Msg : " + i + " = " + jsonobj.getString("Msg")); }` – IntelliJ Amiya Dec 14 '15 at 06:28
  • what is the problem ,if Try catch Using here? – Kumar Dec 14 '15 at 06:31
  • @Kumar Strange case .Getting `type java.lang.String cannot be converted to JSONArray` – IntelliJ Amiya Dec 14 '15 at 06:45
  • @IntelliJAmiya its giving error message like Unhandled Excepetion in android studio. – Kumar Dec 14 '15 at 06:51
  • @IntelliJAmiya i already posted my code.along with Logcat error message – Kumar Dec 14 '15 at 07:04
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/97816/discussion-between-intellij-amiya-and-kumar). – IntelliJ Amiya Dec 14 '15 at 07:06
  • IMO, you can try using `JSONArray jArr = new JSONArray(Content.substring(Content.indexOf("["), Content.lastIndexOf("]") + 1));` instead of `JSONArray jArr=new JSONArray(Content);` – BNK Dec 17 '15 at 02:44
  • @BNK It Shows error message like this After Adding your Code-org.json.JSONException: Expected literal value at character 2 of [{\"ID\":1,\"Name\":\"Lalita\",\"Contact\":\"9997162499\",\"Msg\":\"1\"},{\"ID\":2,\"Name\":\"kumar\",\"Contact\":\"123456789\",\"Msg\":\"1\"},{\"ID\":3,\"Name\":\"Swatantra\",\"Contact\":\"987654321\",\"Msg\":\"1\"},{\"ID\":4,\"Name\":\"Vinoth\",\"Contact\":\"1111111111\",\"Msg\":\"1\"},{\"ID\":5,\"Name\":\"Manish\",\"Contact\":\"22222222\",\"Msg\":\"1\"},{\"ID\":6,\"Name\":\"Manoj\",\"Contact\":\"33333333333\",\"Msg\":\"1\"}] – Kumar Dec 17 '15 at 05:35
  • Please use `Log.i("Output", Content.substring(Content.indexOf("["), Content.lastIndexOf("]") + 1));` and `Log.i("OutputOrg", Content);` then post the results so that I can check. I guess the string responsed from your web service is not a valid JSON – BNK Dec 17 '15 at 05:56
  • Your JSON string at your comment above has an invalid character (I don't know what is that) at `"‌​:2`. You can check by copy & paste it into Notepad+ then use left/right arrow to check (you must press the arrow key 3 times at the position between `"‌​` and `:` – BNK Dec 17 '15 at 06:10
  • @BNK Output org log message is not Printing. Showing Error Expected literal value at character 2 – Kumar Dec 17 '15 at 06:48
  • Do you mean `Log.i("OutputOrg", Content);` does not print anything? – BNK Dec 17 '15 at 07:05
  • @BNK yes , only uiUpdate.setText("Raw Output : " + Content); showing Some text WIthout Parsing Data.but, logcat Not Printing anything.Showing this Error Expected literal value at character 2 of [{\"ID\":1,\"Name\":\"Lalita\",\"Contact\":\"9997162499\",\"Msg\":\"1\"},{\"ID\"‌​:2,\"Name\":\"kumar\",\"Contact\":\"123456789\",\"Msg\":\"1\"},{\"ID\":3,\"Name\"‌​:\"Swatantra\",\"Contact\":\"987654321\",\"Msg\":\"1\"},{\"ID\":4,\"Name\":\"Vino‌​th\",\"Contact\":\"1111111111\",\"Msg\":\"1\"},{\"ID\":5,\"Name\":\"Manoj\",\"Contact\":\"33‌​333333333\",\"Msg\":\"1\"}] – Kumar Dec 17 '15 at 09:19
  • You can temporarily comment the line `JSONArray jArr = new JSONArray(Content.substring(Content.indexOf("["), Content.lastIndexOf("]") + 1));` and other lines – BNK Dec 17 '15 at 09:28
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/98205/discussion-between-kumar-and-bnk). – Kumar Dec 17 '15 at 09:37
  • @Kumar : Please check this answer -> http://stackoverflow.com/a/34331994/4018207 – AndiGeeky Dec 17 '15 at 10:17
  • you got the solution @Kumar – curiousMind Dec 18 '15 at 13:50

9 Answers9

10

As per your response is JSONArray and gson library is better to use while json data parsing so use below class to any type of data like that

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;


public class ApiData {
    @SerializedName("data")
    @Expose
    private JsonArray Data;

    public <T> List<T> getData(Class<T> c) {
        Type type = new ListParams(c);
        return new Gson().fromJson(Data, type);
    }

    private class ListParams implements ParameterizedType {

        private Type type;

        private ListParams(Type type) {
            this.type = type;
        }

        @Override
        public Type[] getActualTypeArguments() {
            return new Type[]{type};
        }

        @Override
        public Type getRawType() {
            return ArrayList.class;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }


        @Override
        public boolean equals(Object o) {
            return super.equals(o);
        }

    }
}

Create model class like :

public class Model{
   String ID;
   String Name;
   String Contact;
   String msg;
}

Now parse your data like:

ApiData apiData = new Gson().fromJson(Content, ApiData.class);
Lis<Model> models = apiData.getData(Model.class); 
Hitesh Bhalala
  • 2,872
  • 23
  • 40
6
 try {
                Object jsonObject = new JSONTokener(Content).nextValue();
                JSONArray jArr=new JSONArray(jsonObject );
                for(int i=0;i<jArr.length();i++) {
                    JSONObject json=jArr.getJSONObject(i);
                    name1.setText(json.getString("Name"));
                    email.setText(json.getString("ID"));
                    status.setText(json.getString("Contact"));
                    face.setText(json.getString("Msg"));

                }

            } catch (JSONException e) {
                e.printStackTrace();
                Log.i("EXCEPTION   ","");
            }

Directly you cannot apply string to array, you should convert string to jsonobject ,then you can do object to array. Hope you understand

learner
  • 3,092
  • 2
  • 21
  • 33
6

As i have added escaping to your json here only for storing it temporary :

Please check below parsing code and it is working for me :

String response = "[\r\n    {\r\n        \"ID\": 4,\r\n        \"Name\": \"Vinoth\",\r\n        \"Contact\": \"1111111111\",\r\n        \"Msg\": \"1\"\r\n    },\r\n    {\r\n        \"ID\": 5,\r\n        \"Name\": \"Mani\",\r\n        \"Contact\": \"22222222\",\r\n        \"Msg\": \"1\"\r\n    },\r\n    {\r\n        \"ID\": 6,\r\n        \"Name\": \"Manoj\",\r\n        \"Contact\": \"33333333333\",\r\n        \"Msg\": \"1\"\r\n    }\r\n]";
        try {
            JSONArray jsonArray = new JSONArray(response); // replace response with your response string
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Log.e("ID", jsonObject.getInt("ID") + "");
                Log.e("Name", jsonObject.getString("Name"));
                Log.e("Contact", jsonObject.getString("Contact"));
                Log.e("Msg", jsonObject.getString("Msg"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

Logs I have printed :

12-17 15:42:54.459 9064-9064/com.example.testapplication E/ID: 4 12-17 15:42:54.459 9064-9064/com.example.testapplication E/Name: Vinoth 12-17 15:42:54.459 9064-9064/com.example.testapplication E/Contact: 1111111111 12-17 15:42:54.459 9064-9064/com.example.testapplication E/Msg: 1 12-17 15:42:54.459 9064-9064/com.example.testapplication E/ID: 5 12-17 15:42:54.459 9064-9064/com.example.testapplication E/Name: Mani 12-17 15:42:54.459 9064-9064/com.example.testapplication E/Contact: 22222222 12-17 15:42:54.459 9064-9064/com.example.testapplication E/Msg: 1 12-17 15:42:54.459 9064-9064/com.example.testapplication E/ID: 6 12-17 15:42:54.459 9064-9064/com.example.testapplication E/Name: Manoj 12-17 15:42:54.459 9064-9064/com.example.testapplication E/Contact: 33333333333 12-17 15:42:54.459 9064-9064/com.example.testapplication E/Msg: 1

Thanks ..!

AndiGeeky
  • 11,266
  • 6
  • 50
  • 66
  • Again Error org.json.JSONException: Value [{"ID":1,"Name":"Lalita","Contact":"9997162499","Msg":"1"},{"ID":2,"Name":"kumar","Contact":"123456789","Msg":"1"}]of type java.lang.String cannot be converted to JSONArray error Occurred – Kumar Dec 17 '15 at 11:13
  • my response is "Content " Only , how can i add Spacing. – Kumar Dec 17 '15 at 11:55
  • @Kumar : You do not need to add any spacing for example I have added `escaping` and also your code is working fine on my machine..!! – AndiGeeky Dec 17 '15 at 12:33
2

The documentation of public JSONArray (String json) says it throws a

JSONException if the parse fails or doesn't yield a JSONArray.

Maybe he can't handle your response which is quite funny because a simple online json parser can: http://json.parser.online.fr/

As the user "Jelle van Es" mentioned in a previous comment, I would try Gson to do the work. (I would have commented under his comment but I have to few reputation xD)

cherry-wave
  • 731
  • 2
  • 6
  • 21
2

You are using getString on "ID" when you should be using getInt. I tested the JSON string you provided in your question. The following code works:

String json =
    "[{\"ID\":4,\"Name\":\"Vinoth\",\"Contact\":\"1111111111\",\"Msg\":\"1\"},{\"ID\":5,\"Name\":\"Mani\",\"Contact\":\"22222222\",\"Msg\":\"1\"},{\"ID\":6,\"Name\":\"Manoj\",\"Contact\":\"33333333333\",\"Msg\":\"1\"}]";
try {
  JSONArray jsonArray = new JSONArray(json);
  for (int i = 0, len = jsonArray.length(); i < len; i++) {
    JSONObject jsonObject = jsonArray.getJSONObject(i);
    int id = jsonObject.getInt("ID");
    String name = jsonObject.getString("Name");
    String contact = jsonObject.getString("Contact");
    String msg = jsonObject.getString("Msg");
    System.out.println("id=" + id + ", name='" + name + "\', contact='" + contact + "\', msg='" + msg);
  }
} catch (JSONException e) {
  e.printStackTrace();
}

Output from running the above code:

id=4, name='Vinoth', contact='1111111111', msg='1

id=5, name='Mani', contact='22222222', msg='1

id=6, name='Manoj', contact='33333333333', msg='1

If you are still getting an error, post the stacktrace.

Jared Rummler
  • 37,824
  • 19
  • 133
  • 148
  • org.json.JSONException: Value [{"ID":1,"Name":"Lalita","Contact":"9997162499","Msg":"1"},{"ID":2,"Name":"kumar","Contact":"123456789","Msg":"1"},{"ID":3,"Name":"Swatantra","Contact":"987654321","Msg":"1"},{"ID":4,"Name":"Vinoth","Contact":"1111111111","Msg":"1"},{"ID":5,"Name":"Manish","Contact":"22222222","Msg":"1"},{"ID":6,"Name":"Manoj","Contact":"33333333333","Msg":"1"},{"ID":7,"Name":"This Url Connected With Azure Database","Contact":"11111","Msg":"1"}] of type java.lang.String cannot be converted to JSONArray at org.json.JSON.typeMismatch(JSON.java:111) – Kumar Dec 14 '15 at 09:59
  • same error, i am getting Raw String Output.but not able to parse that values. – Kumar Dec 14 '15 at 10:00
  • tested in Two Kitkat devices. but still same error. – Kumar Dec 14 '15 at 10:20
2

Check this linkJSONArray

You should not directly use the response you get after hitting web service.First convert it to string as given in the link and also use getInt() when you are parsing your id

Community
  • 1
  • 1
Vivek Mishra
  • 5,669
  • 9
  • 46
  • 84
1

You can Parse your JSON like below.

                    try {
                            JSONArray _jArray = new JSONArray("YOUR_RESPONSE");
                            if (_jArray.length()>0){
                                for (int i = 0 ; i < _jArray.length();i++){
                                    JSONObject _jSObject = _jArray.getJSONObject(i);
                                    int ID = _jSObject.getInt("ID");
                                    String Name = _jSObject.getString("Name");
                                    String Contact = _jSObject.getString("Contact");
                                    String Msg = _jSObject.getString("Msg");
                                    System.out.println("Id : " + ID);
                                    System.out.println("Name : " + Name);
                                    System.out.println("Contact : " + Contact);
                                    System.out.println("Msg : " + Msg);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
Shoeb Siddique
  • 2,805
  • 1
  • 22
  • 42
1
Best way and very fast parsing of JSON is GSON liabrary 

dependacy for android studio compile 'com.google.code.gson:gson:2.3.1' OR you can download jar.

Make DTO names of all strings exactly same json of resonse.


Class ClassDTO{
    String ID;
    String Name;
    String Contact;
    String Msg;

    take gettters & setters

}

Just include this lines in your code.


JSONArray array=new JSONArray(Content);
if (array.length() > 0) {
    Gson gson = new Gson();
    int i = 0;
    while (i < array.length()) {
        list.add(gson.fromJson(array.getJSONObject(i).toString(), ClassDTO.class));
        i++;
    }    
} else {
    Toast.makeText(JobCardActivity.this, "No response from server", Toast.LENGTH_LONG).show();
}
Ajinkya
  • 1,029
  • 7
  • 15
0

for json url hit and parsing of the data i have use this way First i have created a class for Async request

    public class AsyncRequestForActivities extends
    AsyncTask<String, Integer, String> {

OnAsyncRequestComplete caller;
Context context;

String method = "POST";
List<NameValuePair> parameters = null;
ProgressDialog pDialog = null;
String Progress_msg;

// Three Constructors
public AsyncRequestForActivities(Context a, String m, String Msg,
        List<NameValuePair> p) {
    caller = (OnAsyncRequestComplete) a;
    context = a;
    method = m;
    parameters = p;
    Progress_msg = Msg;
}

public AsyncRequestForActivities(Context a, String m) {
    caller = (OnAsyncRequestComplete) a;
    context = a;
    method = m;

}

public AsyncRequestForActivities(Context a) {
    caller = (OnAsyncRequestComplete) a;
    context = a;
}

// Interface to be implemented by calling activity
public interface OnAsyncRequestComplete {
    public void asyncResponse(String response);
}

public String doInBackground(String... urls) {
    // get url pointing to entry point of API
    String address = urls[0].toString();
    if (method == "POST") {
        return post(address);
    }

    if (method == "GET") {
        return get(address);
    }

    return null;

}

public void onPreExecute() {

    pDialog = new ProgressDialog(context);
    pDialog.setMessage(Progress_msg); // typically you will
    pDialog.setCancelable(false); // define such
    // strings in a remote file.
    pDialog.show();

}

public void onProgressUpdate(Integer... progress) {
    // you can implement some progressBar and update it in this record
    // setProgressPercent(progress[0]);
}

public void onPostExecute(String response) {

    if (pDialog != null && pDialog.isShowing()) {
        pDialog.dismiss();
    }

    caller.asyncResponse(response);
}

protected void onCancelled(String response) {

    if (pDialog != null && pDialog.isShowing()) {
        pDialog.dismiss();
    }
    caller.asyncResponse(response);
}

@SuppressWarnings("deprecation")
private String get(String address) {
    try {

        if (parameters != null) {

            String query = "";
            String EQ = "=";
            String AMP = "&";
            for (NameValuePair param : parameters) {
                query += param.getName() + EQ
                        + URLEncoder.encode(param.getValue()) + AMP;
            }

            if (query != "") {
                address += "?" + query;
            }
        }

        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(address);
        HttpResponse response = client.execute(get);

        return stringifyResponse(response);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

    return null;
}

private String post(String address) {
    try {

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(address);

        if (parameters != null) {
            post.setEntity(new UrlEncodedFormEntity(parameters));
        }

        HttpResponse response = client.execute(post);
        return stringifyResponse(response);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

    return null;
}

private String stringifyResponse(HttpResponse response) {
    BufferedReader in;

    try {
        in = new BufferedReader(new InputStreamReader(response.getEntity()
                .getContent()));

        StringBuffer sb = new StringBuffer("");
        String line = "";
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }
        in.close();

        return sb.toString();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

}

now when you want to get Data you have to implement the interface in your activity

    public class SomeClass extends Activity implements OnAsyncRequestComplete{
    // your activity code here

   // some where in class in any function you want
    AsyncRequestForActivities req=new AsyncRequestForActivities(SomeClass.this, MethodType, YourMessage,
        Perameters_in_List<NameValuePareType>);


    req.execute(YourURL);

    }//end of that function
    @Override
    public void asyncResponse(String response) {

    try {

        if (!(response == null)) {
              JSONArray jArray = new JSONArray("response");
                        if (jArray.length()>0){
                            for (int i = 0 ; i < jArray.length();i++){
                                JSONObject jSObject = jArray.getJSONObject(i);
                                int ID = _jSObject.getInt("ID");
                                String Name = _jSObject.getString("Name");
                                String Contact = jSObject.getString("Contact");
                                String Msg = jSObject.getString("Msg");
                                System.out.println("Id : " + ID);
                                System.out.println("Name : " + Name);
                                System.out.println("Contact : " + Contact);
                                System.out.println("Msg : " + Msg);
                            }


        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
    }
    }
  • if the problem presist then fist get the response as JSON Object like : JSONObject postObject = new JSONObject(response); then get Array from this Object: hope you will find your solution gone – Faheem Ahmad Khan Dec 21 '15 at 05:05