0

I have an android application by which i want to read json the following json.

[{"name":"ABCD","country":"INDIA","twitter":"abc"},{"name":"nehasharma","country":"india","twitter":"indore"},{"name":"Arif","country":"India","twitter":"@sdf"},{"name":"gsutam","country":"india","twitter":"hwello"},{"name":"gsutam","country":"india","twitter":"hwello"},{"name":"gsutam","country":"india","twitter":"hwello"},{"name":"gsutam","country":"india","twitter":"hwello"},{"name":"gsutam","country":"india","twitter":"hwello"},{"name":"bawender","country":"18","twitter":null},{"name":"dddd","country":"india","twitter":"sdtt"},{"name":"dddd","country":"india","twitter":"sdtt"},{"name":"dddd","country":"india","twitter":"fghjj"},{"name":"je","country":"xe","twitter":"@rtttt.com\n"},{"name":"ajh","country":"eyohio","twitter":"mp"},{"name":"hasan","country":"jsjs","twitter":"snsns"},{"name":"13.3738383383","country":"38.3838383829","twitter":"location"},{"name":"Latitude:13.07136399","country":"Longitude:77.55943079","twitter":"Current Location"},{"name":"Latitude:13.07136399","country":"Longitude:77.55943079","twitter":"Current Location"},{"name":"Latitude:13.07136399","country":"Longitude:77.55943079","twitter":"Current Location"},{"name":"13.07136399","country":"77.55943079","twitter":"Current Location"},{"name":"13.07136399","country":"77.55943079","twitter":"Current Location"}]

Here is the android code.

public class Cultural extends ListActivity {

    private ProgressDialog pDialog;


    private static String url = "http://hmkcode.appspot.com/jsonservlet";

    private static final String NAME = "name";
    private static final String COUNTRY = "country";
    private static final String TWITTER = "twitter";

    // contacts JSONArray
    JSONArray contacts = null;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cultural);

        contactList = new ArrayList<HashMap<String, String>>();

        ListView lv = getListView();

        // Listview on item click listener
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                // getting values from selected ListItem

                String name = ((TextView)view.findViewById(R.id.name)).getText().toString();

                String country = ((TextView) view.findViewById(R.id.time)).getText().toString();
                String twitter = ((TextView) view.findViewById(R.id.venue)).getText().toString();

                Intent in = new Intent(getApplicationContext(),SingleEventActivity.class);
                in.putExtra(NAME, name);
                in.putExtra(COUNTRY, country);
                in.putExtra(TWITTER, twitter);

                startActivity(in);

            }
        });

        // Calling async task to get json
        new GetContacts().execute();
    }

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

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

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

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

            Log.d("Response: ", "> " + jsonStr);

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

                    // Getting JSON Array node
                    // contacts = jsonObj.getJSONArray(NAME);

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String name = c.getString(NAME);
                        String time = c.getString(COUNTRY);
                        String twitter=c.getString(TWITTER);

                        // Phone node is JSON Object

                        // tmp hashmap for single contact
                        HashMap<String, String> contact = new HashMap<String, String>();

                        // adding each child node to HashMap key => value

                        contact.put(NAME, name);
                        contact.put(COUNTRY, time);
                        contact.put(TWITTER,twitter);

                        //contact.put(TAG_ADDRESS, address);

                        // adding contact to contact list
                        contactList.add(contact);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            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(Cultural.this, contactList,R.layout.list_item, new String[] { NAME, COUNTRY,TWITTER }, new int[] { R.id.name,R.id.time, R.id.venue});

            setListAdapter(adapter);
        }

    }

}

Whenever i try to run the app, i get a black screen and i get the following information in console: JSONArray cannot be converted to JSONObject error.

The data is getting downloaded and i am able to see it in console.

Where am i going wrong here ?

1

5 Answers 5

1

1.Create JsonArray from jsonString after that get jsonobject of each index.
2. Jsonobject to getString with pass key parameter

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

Comments

0

JSONArray cannot be converted to JSONObject error

Because returned response string is JSONArray of JSONObject's instead of JSONObject's.

So, need to convert jsonStr String to JSONArray instead of JSONObject. Change :

JSONObject jsonObj = new JSONObject(jsonStr);

to

JSONArray jsonArr = new JSONArray(jsonStr);
for (int i = 0; i < jsonArr.length(); i++) {
   JSONObject c = jsonArr.getJSONObject(i);
   .....
}

Now get all JSONObjects from jsonArr.

2 Comments

I edited as you have said it says jsonArr value has never been used, if possible kindly brief you answer more :)
@penta: use jsonArr instead of jsonObj
0

Your string is JSONArray, so parsing it as JSONObject will make error. Better way to use:

JSONArray contacts = new JSONArray(jsonStr);
for(int i=0; i<contacts.length(); i++) {
    //your code
}

Comments

0
JSONObject jsonObj = new JSONObject(jsonStr);

jsonStr is an array, not an object, So you have to create a JSONArray instead of a JSONObject to create the root

Comments

0

Activity and fetching JSON

public class MainActivity extends ActionBarActivity {
CustomListAdapter adapter;
ListView mListView;
final static String URL = "http://hmkcode.appspot.com/jsonservlet";
ArrayList<Model> resModel = new ArrayList<>();
ProgressBar bar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mListView = (ListView) findViewById(R.id.list);
    bar = (ProgressBar) findViewById(R.id.bar);
    getResponse();


    adapter = new CustomListAdapter(this, resModel);

    mListView.setAdapter(adapter);

}

private void getResponse() {
    bar.setVisibility(View.VISIBLE);
    String tag_json_obj = "getresponse";
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
            URL, null, new com.android.volley.Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            Log.d("Response", response.toString());
            try {
                JSONArray feedArray = response.getJSONArray("feed");
                Model[] model = new Gson().fromJson(feedArray.toString(), Model[].class);
                Collections.addAll(resModel, model);
                adapter.addItems(resModel);
                bar.setVisibility(View.GONE);
                mListView.setVisibility(View.VISIBLE);
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
            }
        }
    }, new com.android.volley.Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d("Error: " + error.getMessage());
        }
    }) {
        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            return getRequestHeaders();
        }
    };
    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}


public static HashMap<String, String> getRequestHeaders() {
    HashMap<String, String> requestHeader = new HashMap<String, String>();
    String requestUsername = "user_name";
    String requestPassword = "password";
    String creds = String.format("%s:%s", requestUsername, requestPassword);
    String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
    requestHeader.put("Authorization", auth);
    requestHeader.put("Content-Type", "application/json; charset=utf-8");
    return requestHeader;
}

ListAdapter

public class CustomListAdapter extends BaseAdapter {
LayoutInflater inflater;
ImageLoader mImageLoader;
Context mContext;
ArrayList<Model> result;


public CustomListAdapter(Context context, ArrayList<Model> results) {
    mContext = context;
    result = results;
    inflater = LayoutInflater.from(context);
    mImageLoader = ImageLoader.getInstance();
}

@Override
public int getCount() {
    return result.size();
}

@Override
public Object getItem(int position) {
    return result.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    final Model modit = result.get(position);
    if (convertView == null) {
        holder = new ViewHolder();
        convertView = inflater.inflate(R.layout.list_item, parent, false);
        // Initialize all attribiutes
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    final ViewHolder holder1 = holder;
    // set values
    return convertView;
}

public void clearItems() {
    result.clear();
}

public void addItems(ArrayList<Model> rrespo) {
    result.addAll(rrespo);
    notifyDataSetChanged();
}

static class ViewHolder {
    ImageView picture;
    TextView title;
    TextView about;
    TextView dateTime;
}
}

here is your model

public class Model implements Serializable {
private String name;
private String country;
private String twitter;

public String getTwitter() {
    return twitter;
}

public void setTwitter(String twitter) {
    this.twitter = twitter;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

Create your XML layout and put values

4 Comments

dont edit it... just get it.. and save in ur model. and use it wherever u want.
can u just copy my code from question and edit your answer with full working code ?
i am sorry Ankit but you seems to have made it more complex, posper has given a working answer
Its okay... No need to be sorry... In fact I learned it.. By this code I can handle any JSONArray of any length :)

Your Answer

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