skip to Main Content

I had try to parse the json value to my listview. I am getting the error in logcat as json parsing error, Instead of the result appearing in listview,the entire json response is appearing in toast, Please help me to solve it. Thanks.

Here is my java code

MainActivity.java

public class MainActivity extends AppCompatActivity {

private String TAG = MainActivity.class.getSimpleName();

private ProgressDialog pDialog;
private ListView lv;

// URL to get contacts JSON
private static String url = " https://private-2a004-androidtest3.apiary-mock.com/employeesList";

ArrayList<HashMap<String, String>> employeeList;

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

    employeeList = new ArrayList<>();

    lv = (ListView) findViewById(R.id.list);

    new Getemployees().execute();
}

/**
 * Async task class to get json by making HTTP call
 */
private class Getemployees extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray employees = jsonObj.getJSONArray("contacts");

                // looping through All Contacts
                for (int i = 0; i < employees.length(); i++) {
                    JSONObject c = employees.getJSONObject(i);
                    String firstName = c.getString("firstName");
                    String lastName = c.getString("lastName");
                    String designation = c.getString("designation");
                    String city = c.getString("city");
                    HashMap<String, String> emp = new HashMap<>();
                    emp.put("firstName", firstName);
                    emp.put("lastName", lastName);
                    emp.put("designation",designation);
                    emp.put("city",city);
                    employeeList.add(emp);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, employeeList,
                R.layout.list_item, new String[]{"firstName","lastName","designation", "city"},new int[]{R.id.firstName,
                R.id.lastName,R.id.city,R.id.designation});
        lv.setAdapter(adapter);
    }

}

}

HttpHandler.java

public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

My logcat:

02-17 15:45:03.667 24027-24149/com.example.simple E/MainActivity: Response from url: [
                                                                      {

                                                                          "employee": 
                                                                          [
                                                                            {
                                                                              "id": "1",
                                                                              "firstName": "Ram",
                                                                              "lastName": "Kumar",
                                                                              "address" : "1/20, Rich street",
                                                                              "city" : "Karur",
                                                                              "zipcode" : "636138",
                                                                              "gender" : "male",
                                                                              "dob" : "20-May-1995",
                                                                              "designation":"developer",
                                                                              "mobile" : "9988776655",
                                                                              "email" : "[email protected]",
                                                                              "nationality" : "Indian",
                                                                              "language" : "English",
                                                                              "imageURL" : "https://dummyimage.com/500x500/d12ad1/fff.png&text=Ram",
                                                                              "skills": [
                                                                                {
                                                                                  "technical" : [ "C", "C++", "Java" ],
                                                                                  "extra_curricular" : ["chess", "cricket"]
                                                                                }]
                                                                            },
                                                                            {
                                                                              "id": "2",
                                                                              "firstName": "Kumari",
                                                                              "lastName": "Raja",
                                                                              "address" : "2/20, Rich street",
                                                                              "city" : "Coimbatore",
                                                                              "zipcode" : "636148",
                                                                              "gender" : "female",
                                                                              "dob" : "10-Jun-1995",
                                                                              "designation":"Tester",
                                                                              "mobile" : "8899667744",
                                                                              "email" : "[email protected]",
                                                                              "nationality" : "Indian",
                                                                              "language" : "Tamil",
                                                                              "imageURL" : "https://dummyimage.com/500x500/52d929/fff.png&text=Kumari",
                                                                              "skills": [
                                                                                {
                                                                                  "technical" : [ "C", "C++", ".net" ],
                                                                                  "extra_curricular" : ["Tennis", "Carrom"]
                                                                                }]
                                                                            },
                                                                            {
                                                                              "id": "3",
                                                                              "firstName": "Raja",
                                                                              "lastName": "Ravi",
                                                                              "address" : "13/20, Rich street",
                                                                              "city" : "Salem",
                                                                              "zipcode" : "636138",
                                                                              "gender" : "male",
                                                                              "dob" : "22-Jan-1994",
                                                                              "designation":"Team Lead",
                                                                              "mobile" : "9876543210",
                                                                              "email" : "[email protected]",
                                                                              "nationality" : "Indian",
                                                                              "language" : "English",
                                                                              "imageURL" : "https://dummyimage.com/500x500/bef0af/fff.png&text=Raja",
                                                                              "skills": [
                                                                                {
                                                                                  "technical" : [ "C", "C++", "Java" , "Android"],
                                                                                  "extra_curricular" : ["chess", "cricket"]
                                                                                }]
                                                                            },
                                                                            {
                                                                              "id": "4",
                                                                              "firstName": "Sheela",
                                                                              "lastName": "Ravi",
                                                                              "address" : "14/20, Rich street",
                                                                              "city" : "Madurai",
                                                                              "zipcode" : "636200",
                                                                              "gender" : "female",
                                                                              "dob" : "10-Feb-1985",
                                                                              "designation":"developer",
                                                                              "mobile" : "5566778899",
                                                                              "email" : "[email protected]",
                                                                              "nationality" : "Indian",
                                                                              "language" : "Tamil",
                                                                              "imageURL" : "https://dummyimage.com/500x500/e6866e/fff.png&text=Sheela",
                                                                              "skills": [
                                                                                {
                                                                                  "technical" : [ "photoshop", "Ruby" ],
                                                                                  "extra_curricular" : ["Carrom", "Reading books"]
                                                                                }]
                                                                            },
                                                                            {
                                                                              "id": "5",
                                                                              "firstName": "Shankar",
                                                                              "lastName": "Kumar",
                                                                              "address" : "15/20, Rich street",
                                                                              "city" : "Madurai",
                                                                              "zipcode" : "636300",
                                                                              "gender" : "Male",
                                                                              "dob" : "10-Feb-1985",
                                                                              "designation":"Sr.Developer",
                                                                              "mobile" : "5566778899",
                                                                              "email" : "[email protected]",
                                                                              "nationality" : "Indian",
                                                                              "language" : "Tamil",
                                                                              "imageURL" : "https://dummyimage.com/500x500/8f3532/fff.png&text=Shankar",
                                                                              "skills": [
                                                                                {
                                                                                  "technical" : [ "C", "C++" ],
                                                                                  "extra_curricular" : ["chess", "Drawing"]
                                                                                }]
                                                                            },
                                                                            {
                                                                              "id": "6",
                                                                              "firstName": "Suren",
                                                                              "lastName": "Saker",
                                                                              "address" : "16/20, Rich street",
                                                                              "city" : "Salem",
                                                                              "zipcode" : "636400",
                                                                              "gender" : "Male",
                                                                              "dob" : "14-Jan-1985",
                                                                              "designat
02-17 15:45:03.676 24027-24149/com.example.simple E/MainActivity: Json parsing error: Value [{"employee":[{"id":"1","firstName":"Ram","lastName":"Kumar","address":"1/20, Rich street","city":"Karur","zipcode":"636138","gender":"male","dob":"20-May-1995","designation":"developer","mobile":"9988776655","email":"[email protected]","nationality":"Indian","language":"English","imageURL":"https://dummyimage.com/500x500/d12ad1/fff.png&text=Ram","skills":[{"technical":["C","C++","Java"],"extra_curricular":["chess","cricket"]}]},{"id":"2","firstName":"Kumari","lastName":"Raja","address":"2/20, Rich street","city":"Coimbatore","zipcode":"636148","gender":"female","dob":"10-Jun-1995","designation":"Tester","mobile":"8899667744","email":"[email protected]","nationality":"Indian","language":"Tamil","imageURL":"https://dummyimage.com/500x500/52d929/fff.png&text=Kumari","skills":[{"technical":["C","C++",".net"],"extra_curricular":["Tennis","Carrom"]}]},{"id":"3","firstName":"Raja","lastName":"Ravi","address":"13/20, Rich street","city":"Salem","zipcode":"636138","gender":"male","dob":"22-Jan-1994","designation":"Team Lead","mobile":"9876543210","email":"[email protected]","nationality":"Indian","language":"English","imageURL":"https://dummyimage.com/500x500/bef0af/fff.png&text=Raja","skills":[{"technical":["C","C++","Java","Android"],"extra_curricular":["chess","cricket"]}]},{"id":"4","firstName":"Sheela","lastName":"Ravi","address":"14/20, Rich street","city":"Madurai","zipcode":"636200","gender":"female","dob":"10-Feb-1985","designation":"developer","mobile":"5566778899","email":"[email protected]","nationality":"Indian","language":"Tamil","imageURL":"https://dummyimage.com/500x500/e6866e/fff.png&text=Sheela","skills":[{"technical":["photoshop","Ruby"],"extra_curricular":["Carrom","Reading books"]}]},{"id":"5","firstName":"Shankar","lastName":"Kumar","address":"15/20, Rich street","city":"Madurai","zipcode":"636300","gender":"Male","dob":"10-Feb-1985","designation":"Sr.Developer","mobile":"5566778899","email":"[email protected]","nationality":"Indian","language":"Tamil","imageURL":"https://dummyimage.com/500x500/8f3532/fff.png&text=Shankar","skills":[{"technical":["C","C++"],"extra_curricular":["chess","Drawing"]}]},{"id":"6","firstName":"Suren","lastName":"Saker","address":"16/20, Rich street","city":"Salem","zipcode":"636400","gender":"Male","dob":"14-Jan-1985","designation":"Sr.Developer","mobile":"8899776655","email":"[email protected]","nationality":"Indian","language":"English","imageURL":"http://indianapublicmedia.org/arts/files/2012/04/sample-gates-9-940x626.jpg","skills":[{"technical":["Java","Android"],"extra_curricular":["Reading","Stamp collection"]}]},{"id":"7","firstName":"Rajesh","lastName":"Kumar","address":"17/20, Rich street","city":"Karur","zipcode":"636800","gender":"Male","dob":"10-Feb-1985","designation":"Sr.Developer","mobile":"5566778899","email":"[email protected]","nationality":"Indian","language":"Tamil","imageURL":"http://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg","skills":[{"technical":["C","C++"],"extra_curricular":["chess","Drawing"]}]},{"id":"8","firstName":"Sham","lastName":"Kumar","address":"18/20, Rich street","city":"Salem","zipcode":"636700","gender":"Male","dob":"08-Feb-1985","designation":"Sr.Developer","mobile":"7788996655","email":"[email protected]","nationality":"Indian","language":"Tamil","imageURL":"https://taylorstaste.files.wordpress.com/2014/07/screenshot-2014-07-03-10-25-41.png","skills":[{"technical":["C","C++"],"extra_curricular":["chess","Drawing"]}]},{"id":"9","firstName":"Jayakumar","lastName":"Ravi","address":"19/20, Rich street","city":"Coimbatore","zipcode":"623300","gender":"Male","dob":"3-Mar-1986","designation":"Designer","mobile":"8879797979","email":"[email protected]","nationality":"Indian","language":"Tamil","imageURL":"http://images.fonearena.com/blog/wp-content/uploads/2013/11/google-nexus-5-macro-samples-1.jpg","skills":[{"technical":["Photoshop","Design tools"],"extra_curricular":["chess","Drawing"]}]},{

3

Answers


  1. Json key does not match :

    JSONArray jsonArray=new JSONArray(jsonStr); // As your response is in json array format
    JSONObject jsonObject =jsonArray.getJSONObject(0);
    // Getting JSON Array node
    JSONArray employees = jsonObject.getJSONArray("employee");
    

    Replace “contact” key with “employee” that will solved your problem.

    Login or Signup to reply.
  2. Use JSONArray jsArray= new JSONArray(jsonStr) instesd of JSONObject jsonObj = new JSONObject(jsonStr) becouse your response is an JsonArray.

    Login or Signup to reply.
  3. Try this,

            try {
    
    
                JSONArray jsonArray=new JSONArray(jsonStr);
    
                JSONObject jsonObj =jsonArray.getJSONObject(0);
    
                // Getting JSON Array node
                JSONArray employees = jsonObj.getJSONArray("employee");
    
                // looping through All Contacts
                for (int i = 0; i < employees.length(); i++) {
                    JSONObject c = employees.getJSONObject(i);
                    String firstName = c.getString("firstName");
                    String lastName = c.getString("lastName");
                    String designation = c.getString("designation");
                    String city = c.getString("city");
                    HashMap<String, String> emp = new HashMap<>();
                    emp.put("firstName", firstName);
                    emp.put("lastName", lastName);
                    emp.put("designation",designation);
                    emp.put("city",city);
                    employeeList.add(emp);
                }
            } catch (final JSONException e) {
    
            }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search