0

Trying to populate data into listview

  • I am using JSON Response from the server
  • Having the error

I have mentioned the classes


MainActivity.java

public class MainActivity extends ListActivity {

    // url to make request
    private static String url = "http://54.218.73.244:7002/";

    // JSON Node names
    private static final String TAG_CONTACTS = "restaurants";
    private static final String TAG_ID = "restaurantID";
    private static final String TAG_NAME = "restaurantNAME";

    // contacts JSONArray
    JSONArray contacts = null;

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

        // Hashmap for ListView
        ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of Contacts
            contacts = json.getJSONArray(TAG_CONTACTS);

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

                // Storing each json item in variable
                String id = c.getString(TAG_ID);
                String name = c.getString(TAG_NAME);


                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

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


                // adding HashList to ArrayList
                contactList.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(this, contactList,
                R.layout.list_item,
                new String[] { TAG_NAME }, new int[] {
                        R.id.name });

        setListAdapter(adapter);


    }

}

JSONParser.java

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

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

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">  
        <!-- Name Label -->
        <TextView
            android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="#43bd00"
            android:textSize="16sp"
            android:textStyle="bold"
            android:paddingTop="6dip"
            android:paddingBottom="2dip" />


</LinearLayout>

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <!-- Main ListView 
         Always give id value as list(@android:id/list)
    -->
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

single_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <!-- Name Label -->
  <TextView android:id="@+id/name_label"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textSize="25dip"
            android:textStyle="bold"
            android:paddingTop="10dip"
            android:paddingBottom="10dip"
            android:layout_gravity="center"
            android:textColor="#43bd00"/>
</LinearLayout>

Log::

08-23 17:08:14.940: E/JSON Parser(985): Error parsing data org.json.JSONException: Value Cannot of type java.lang.String cannot be converted to JSONObject
08-23 17:08:14.950: D/AndroidRuntime(985): Shutting down VM
08-23 17:08:14.950: W/dalvikvm(985): threadid=1: thread exiting with uncaught exception (group=0x40015560)
08-23 17:08:14.980: E/AndroidRuntime(985): FATAL EXCEPTION: main
08-23 17:08:14.980: E/AndroidRuntime(985): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.project.findmybuffet/com.project.findmybuffet.MainActivity}: java.lang.NullPointerException
08-23 17:08:14.980: E/AndroidRuntime(985):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
08-23 17:08:14.980: E/AndroidRuntime(985):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-23 17:08:14.980: E/AndroidRuntime(985):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-23 17:08:14.980: E/AndroidRuntime(985):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-23 17:08:14.980: E/AndroidRuntime(985):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-23 17:08:14.980: E/AndroidRuntime(985):  at android.os.Looper.loop(Looper.java:123)
08-23 17:08:14.980: E/AndroidRuntime(985):  at android.app.ActivityThread.main(ActivityThread.java:3683)
08-23 17:08:14.980: E/AndroidRuntime(985):  at java.lang.reflect.Method.invokeNative(Native Method)
08-23 17:08:14.980: E/AndroidRuntime(985):  at java.lang.reflect.Method.invoke(Method.java:507)
08-23 17:08:14.980: E/AndroidRuntime(985):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-23 17:08:14.980: E/AndroidRuntime(985):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-23 17:08:14.980: E/AndroidRuntime(985):  at dalvik.system.NativeStart.main(Native Method)
08-23 17:08:14.980: E/AndroidRuntime(985): Caused by: java.lang.NullPointerException
08-23 17:08:14.980: E/AndroidRuntime(985):  at com.project.findmybuffet.MainActivity.onCreate(MainActivity.java:53)
08-23 17:08:14.980: E/AndroidRuntime(985):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-23 17:08:14.980: E/AndroidRuntime(985):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-23 17:08:14.980: E/AndroidRuntime(985):  ... 11 more
08-23 17:13:15.060: I/Process(985): Sending signal. PID: 985 SIG: 9
08-23 17:20:27.350: E/JSON Parser(1018): Error parsing data org.json.JSONException: Value Cannot of type java.lang.String cannot be converted to JSONObject
08-23 17:20:27.362: D/AndroidRuntime(1018): Shutting down VM
08-23 17:20:27.362: W/dalvikvm(1018): threadid=1: thread exiting with uncaught exception (group=0x40015560)
08-23 17:20:27.390: E/AndroidRuntime(1018): FATAL EXCEPTION: main
08-23 17:20:27.390: E/AndroidRuntime(1018): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.project.findmybuffet/com.project.findmybuffet.MainActivity}: java.lang.NullPointerException
08-23 17:20:27.390: E/AndroidRuntime(1018):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
08-23 17:20:27.390: E/AndroidRuntime(1018):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-23 17:20:27.390: E/AndroidRuntime(1018):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-23 17:20:27.390: E/AndroidRuntime(1018):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-23 17:20:27.390: E/AndroidRuntime(1018):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-23 17:20:27.390: E/AndroidRuntime(1018):     at android.os.Looper.loop(Looper.java:123)
08-23 17:20:27.390: E/AndroidRuntime(1018):     at android.app.ActivityThread.main(ActivityThread.java:3683)
08-23 17:20:27.390: E/AndroidRuntime(1018):     at java.lang.reflect.Method.invokeNative(Native Method)
08-23 17:20:27.390: E/AndroidRuntime(1018):     at java.lang.reflect.Method.invoke(Method.java:507)
08-23 17:20:27.390: E/AndroidRuntime(1018):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-23 17:20:27.390: E/AndroidRuntime(1018):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-23 17:20:27.390: E/AndroidRuntime(1018):     at dalvik.system.NativeStart.main(Native Method)
08-23 17:20:27.390: E/AndroidRuntime(1018): Caused by: java.lang.NullPointerException
08-23 17:20:27.390: E/AndroidRuntime(1018):     at com.project.findmybuffet.MainActivity.onCreate(MainActivity.java:53)
08-23 17:20:27.390: E/AndroidRuntime(1018):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-23 17:20:27.390: E/AndroidRuntime(1018):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-23 17:20:27.390: E/AndroidRuntime(1018):     ... 11 more

Any ideas Thanks,

3 Answers3

1

Trying to populate a simple adapter with ArrayList<HashMap<String, String>> is not recommended. Better you use a custom adapter.

To get a clear picture refer the following links:

http://www.vogella.com/articles/AndroidListView/article.html

http://androidexample.com/How_To_Create_A_Custom_Listview_-_Android_Example/index.php?view=article_discription&aid=67&aaid=92

http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/

Hariharan
  • 24,741
  • 6
  • 50
  • 54
  • can i use ...... List yourData = new ArrayList(); ..... provided Item is a bean class? –  Aug 23 '13 at 12:39
  • 1
    Ya you can use List yourData = new ArrayList(); to populate simple adapter.. – Hariharan Aug 23 '13 at 12:42
  • hey i have tried the solution .... as you suggested .... please have a look at this (http://stackoverflow.com/questions/18404164/populating-data-into-listview).... having a error –  Aug 23 '13 at 13:33
  • @Sky: you are having exception while parsing json.so have a look at my answer.most probably it will solve your issue as I have tested. – Mehul Joisar Aug 23 '13 at 13:41
0

I hope you are not getting the proper json string data. The JSON string you're trying to parse is invalid - looks like it's got some raw HTML, which mean it's either badly generated, or PHP is inserting errors/warnings and destroying the string

if you getting the json data proper then not used for hash map, try to store data in the Bean object and add this object with list. After you add this list with adapter.

Sunil Kumar
  • 7,086
  • 4
  • 32
  • 50
  • I am getting proper JSON response ... please check this link i am using for parsing [http://54.218.73.244:7002/] –  Aug 23 '13 at 12:02
0

Replace following snippet

        try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    }

with this one:

    if (is != null) {
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(is, "UTF-8"));
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            is.close();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
        }
        json = sb.toString();
    } else {
        json="";
    }

I hope it will be helpful !!

Mehul Joisar
  • 15,348
  • 6
  • 48
  • 57