Search code examples
javaandroidjsonlistadaptersimpleadapter

Why is my ListAdapter not showing any data?


I am trying to fill a View with a list of items from a JSON data source. I can't seem to make the adapter show the JSON data in my list. This is what I have done so far.

MainActivity.java

package com.todoapp.android.json;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends ListActivity {

    private ProgressDialog pDialog;

    // JSON Node names
    private static final String TAG_ITEM = "items";
    private static final String TAG_INDEX = "index";
    private static final String TAG_NAME = "name";


    // contacts JSONArray
    JSONArray items = null;

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



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

        // 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(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {

            String jsonStr = "{\"items\":[{\"index\":1,\"name\":\"Bobby\",\"events\":[{\"index\":19,\"email\":\"[email protected]\"},{\"index\":13,\"email\":\"[email protected]\"},{\"index\":0,\"email\":\"[email protected]\"}]}]}";

            if (jsonStr != null) {
                try {
                    Log.d("Response: ", "> " + jsonStr);
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    items = jsonObj.getJSONArray(TAG_ITEM);

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

                        //String id = c.getString(TAG_INDEX);
                        //String index = c.getString(TAG_INDEX);
                        String index = String.valueOf(c.getInt(TAG_INDEX));
                        String name = c.getString(TAG_NAME);


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

                        // adding each child node to HashMap key => value
                        contact.put(TAG_INDEX, index);
                        contact.put(TAG_NAME, name);


                        // adding contact to contact list
                        contactList.add(contact);
                    }
                } catch (JSONException e) {
                    Log.e("foo", "error", e);
                }
            } 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, contactList,
                    R.layout.list_item, new String[] { TAG_INDEX, TAG_NAME}, new int[] { R.id.index,
                    R.id.name });

            setListAdapter(adapter);
        }

    }
}

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="vertical"
    android:padding="10dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp" >

    <!-- Name Label -->

    <TextView
        android:id="@+id/index"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="#43bd00"
        android:textSize="16sp"
        android:textStyle="bold" />

    <!-- Email label -->
    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:textColor="#acacac" />



</LinearLayout>

content_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>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.todoapp.android.json.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

The only thing i get in logcat is in "Verbose" mode is

12-15 12:13:58.152 18184-18184/? I/art: Late-enabling -Xcheck:jni
12-15 12:13:58.235 18184-18184/com.todoapp.android.json D/ContextHelper: convertTheme. context->name=com.todoapp.android.json themeResourceId=2131230766
12-15 12:13:58.245 18184-18184/com.todoapp.android.json I/PhoneWindow: [generateLayout] setColorNavigationBar => color=0x ff000001
12-15 12:13:58.252 18184-18184/com.todoapp.android.json D/PhoneWindowEx: [PWEx][generateLayout] setNavigationBarColor2 : colors=0xff000000
12-15 12:13:58.252 18184-18184/com.todoapp.android.json I/PhoneWindow: [setNavigationBarColor2] color=0x ff000000
12-15 12:13:58.351 18184-18184/com.todoapp.android.json I/PhoneWindow: [generateLayout] setColorNavigationBar => color=0x ff000001
12-15 12:13:58.353 18184-18184/com.todoapp.android.json D/PhoneWindowEx: [PWEx][generateLayout] setNavigationBarColor2 : colors=0xff000000
12-15 12:13:58.353 18184-18184/com.todoapp.android.json I/PhoneWindow: [setNavigationBarColor2] color=0x ff000000
12-15 12:13:58.376 18184-18214/com.todoapp.android.json D/OpenGLRenderer: Render dirty regions requested: false
12-15 12:13:58.377 18184-18214/com.todoapp.android.json E/[DRVB][EXT][UTIL]: disp_only_chk: DRVB CHECK PROCESS DONE ! STATUS (0/0x2002)
12-15 12:13:58.377 18184-18214/com.todoapp.android.json W/[DRVB]: sec_drv_base_check: DRVB PROCESS STATUS = 0x2002
12-15 12:13:58.381 18184-18214/com.todoapp.android.json I/OpenGLRenderer: Initialized EGL, version 1.4
12-15 12:13:58.382 18184-18214/com.todoapp.android.json D/OpenGLRenderer: Enabling debug mode 0
12-15 12:13:58.387 18184-18184/com.todoapp.android.json D/Atlas: Validating map...
12-15 12:13:58.389 18184-18214/com.todoapp.android.json I/[MALI][Gralloc]: dlopen libsec_mem.so fail
12-15 12:13:58.399 18184-18220/com.todoapp.android.json D/Response:: > {"items":[{"index":1,"name":"Bobby","events":[{"index":19,"email":"[email protected]"},{"index":13,"email":"[email protected]"},{"index":0,"email":"[email protected]"}]}]}
12-15 12:13:58.453 18184-18214/com.todoapp.android.json I/MaliEGL: [Mali]window_type=1, is_framebuffer=0, errnum = 0
12-15 12:13:58.453 18184-18214/com.todoapp.android.json I/MaliEGL: [Mali]surface->num_buffers=4, surface->num_frames=3, win_min_undequeued=1
12-15 12:13:58.453 18184-18214/com.todoapp.android.json I/MaliEGL: [Mali]max_allowed_dequeued_buffers=3
12-15 12:13:58.504 18184-18214/com.todoapp.android.json I/MaliEGL: [Mali]window_type=1, is_framebuffer=0, errnum = 0
12-15 12:13:58.504 18184-18214/com.todoapp.android.json I/MaliEGL: [Mali]surface->num_buffers=4, surface->num_frames=3, win_min_undequeued=1
12-15 12:13:58.504 18184-18214/com.todoapp.android.json I/MaliEGL: [Mali]max_allowed_dequeued_buffers=3
12-15 12:13:58.596 18184-18184/com.todoapp.android.json I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@f8bfa22 time:6011123

`

The app on the physical phone starts alright but then is blank. Any pointers? My json file looks like this:

json data

{
    "items": [
        {
            "index": 1,
            "name": "Bobby",
            "events": [
                {
                    "index": 19,
                    "email": "[email protected]"
                },
                {
                    "index": 13,
                    "email": "[email protected]"
                },
                {
                    "index": 0,
                    "email": "[email protected]"
                }
            ]
        }
}

Solution

  • Accordingly to the JSON you posted:

    private static final String TAG_ITEM = "item";
    

    should be

    private static final String TAG_ITEM = "items";
    

    index is an int not a String, and this line

    String index = c.getString(TAG_INDEX);

    is mostly making the parsing failing. Change it with

    String index = String.valueOf(c.getInt(TAG_INDEX));