1

I am learning about Json Parsing I want to show the data in the listview from url for this i did some code but data in the listview is not showing which is coming from url please tell me what mistakes i am making in the code.

MainActivity Code is

public class MainActivity extends ListActivity {

private ProgressDialog pDialog;

// URL to get Cities JSON
private static String url = "http://14.140.200.186/Hospital/get_city.php";

// JSON Node names
private static final String TAG_CITIES = "Cities";
//private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";


// Cities JSONArray
JSONArray Cities = null;

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

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

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



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

/**
 * Async task class to get json by making HTTP call
 * */
private class GetCities 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) {
        // 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
                Cities = jsonObj.getJSONArray(TAG_CITIES);

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

                    //String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);


                    HashMap<String, String> Cities = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    //Cities.put(TAG_ID, id);
                    Cities.put(TAG_NAME, name);

                    // adding contact to Cities list
                    citylist.add(Cities);

                }
            } 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(MainActivity.this, citylist, R.layout.list_item, new String[] { TAG_NAME}, new int[] { R.id.name,});
        setListAdapter(adapter);
    }

}

Second Class code is

public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

/*
 * Making service call
 * @url - url to make request
 * @method - http request method
 * */
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

/*
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String url, int method,
        List<NameValuePair> params) {
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;}

And in the activity_main simply i have a listview in LinearLayout And i have also another layout file list_item with single texview for show showing result..

now please slove my problem

Thanku

1

5 Answers 5

2

Change From:

     private static final String TAG_NAME = "name";

To

   private static final String TAG_NAME = "city_name";

It will help now Please check your Service which You are using.

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

Comments

1

Change From:

 private static final String TAG_NAME = "name";

To

 private static final String TAG_NAME = "city_name";

Comments

0

There are couple of places where things could have gone wrong.

First:

} else if (method == GET) {

Check if above condition is satisfied. You may want to replace GET with ServiceHandler.GET.

Second:

setListAdapter(adapter);

You need to write code to actually make list adapter visible.

1 Comment

it is not working for me still i am getting listview blank
0
 protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    // Dismiss the progress dialog
    if (pDialog.isShowing())
        pDialog.dismiss();
    /**`enter code here`
     * Updating parsed JSON data into ListView
     * */
    ListAdapter adapter = new SimpleAdapter(MainActivity.this, citylist, R.layout.list_item, new String[] { TAG_NAME}, new int[] { R.id.name,});
    list.setAdapter(adapter);
}

Hope it will be help you.

Comments

0

You can do this way:

From

ArrayList<HashMap<String, String>> citylist;

to

ArrayList<String> citylist;

Your loop should looks like below:

for (int i = 0; i < Cities.length(); i++) {
       JSONObject c = Cities.getJSONObject(i);

        //String id = c.getString(TAG_ID);
        String name = c.getString(TAG_NAME);

         // adding contact to Cities list
         citylist.add(name);

 }

Pass only ArrayList to adapter.

Edit 2 :

From

ListAdapter adapter = new SimpleAdapter(MainActivity.this, citylist, R.layout.list_item, new String[] { TAG_NAME}, new int[] { R.id.name,});

To

ArrayAdapter adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.list_item, citylist);

Hope this will help you.

18 Comments

i changed but now citylist = new ArrayList<HashMap<String, String>>(); and ListAdapter adapter = new SimpleAdapter(MainActivity.this, citylist, R.layout.list_item, new String[] { TAG_NAME}, new int[] { R.id.name,}); getting red line
@ArjunSingh, I've edited my answer, please check it.
i make this change but mContext is showing red then i initialized it like Context mContext; now app is crashing
@ArjunSingh, change mContext to MainActivity.this.
Process: info.androidhive.jsonparsing, PID: 483 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
|

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.