为什么我的ListAdapter没有显示任何数据?

时间:2015-12-15 10:36:02

标签: java android json listadapter simpleadapter

我正在尝试使用JSON数据源中的项列表填充视图。 我似乎无法让适配器在我的列表中显示JSON数据。这就是我到目前为止所做的。

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\":\"louis@hardy.eg\"},{\"index\":13,\"email\":\"cynthia@mills.mc\"},{\"index\":0,\"email\":\"leo@graham.kp\"}]}]}";

            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>

我在logcat中唯一得到的是“详细”模式

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":"louis@hardy.eg"},{"index":13,"email":"cynthia@mills.mc"},{"index":0,"email":"leo@graham.kp"}]}]}
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

`

手机上的应用程序启动正常,但随后是空白。有什么指针吗?我的json文件如下所示:

json数据

{
    "items": [
        {
            "index": 1,
            "name": "Bobby",
            "events": [
                {
                    "index": 19,
                    "email": "louis@hardy.eg"
                },
                {
                    "index": 13,
                    "email": "cynthia@mills.mc"
                },
                {
                    "index": 0,
                    "email": "leo@graham.kp"
                }
            ]
        }
}

2 个答案:

答案 0 :(得分:2)

根据您发布的JSON

private static final String TAG_ITEM = "item";

应该是

private static final String TAG_ITEM = "items";

indexint而非String,此行

String index = c.getString(TAG_INDEX);

主要是使解析失败。用

更改它

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

答案 1 :(得分:0)

我认为这可能是由于JSONException。

尝试使用以下代码并运行

 String jsonString = "{\\n\\t\\\"items\\\": [\\n\\t\\t{\\n\\t\\t\\t\\\"index\\\": 1,\\n\\t\\t\\t\\\"name\\\": \\\"Bobby\\\",\\n\\t\\t\\t\\\"events\\\": [\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\\"index\\\": 19,\\n\\t\\t\\t\\t\\t\\\"email\\\": \\\"louis@hardy.eg\\\"\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\\"index\\\": 13,\\n\\t\\t\\t\\t\\t\\\"email\\\": \\\"cynthia@mills.mc\\\"\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\\"index\\\": 0,\\n\\t\\t\\t\\t\\t\\\"email\\\": \\\"leo@graham.kp\\\"\\n\\t\\t\\t\\t}\\n\\t\\t\\t]\\n\\t\\t},\\n\\t\\t{\\n\\t\\t\\t\\\"index\\\": 2,\\n\\t\\t\\t\\\"name\\\": \\\"Maxine\\\",\\n\\t\\t\\t\\\"events\\\": [\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\\"index\\\": 14,\\n\\t\\t\\t\\t\\t\\\"email\\\": \\\"miriam@horne.mo\\\"\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\\"index\\\": 20,\\n\\t\\t\\t\\t\\t\\\"email\\\": \\\"danny@joyce.ro\\\"\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\\"index\\\": 25,\\n\\t\\t\\t\\t\\t\\\"email\\\": \\\"christina@davenport.fo\\\"\\n\\t\\t\\t\\t}\\n\\t\\t\\t]\\n\\t\\t},\\n\\t\\t{\\n\\t\\t\\t\\\"index\\\": 3,\\n\\t\\t\\t\\\"name\\\": \\\"Ruth\\\",\\n\\t\\t\\t\\\"events\\\": [\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\\"index\\\": 1,\\n\\t\\t\\t\\t\\t\\\"email\\\": \\\"heather@kirk.bm\\\"\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\\"index\\\": 29,\\n\\t\\t\\t\\t\\t\\\"email\\\": \\\"kim@middleton.ve\\\"\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\\"index\\\": 2,\\n\\t\\t\\t\\t\\t\\\"email\\\": \\\"harold@arthur.net\\\"\\n\\t\\t\\t\\t}\\n\\t\\t\\t]\\n\\t\\t},\\n\\t\\t{\\n\\t\\t\\t\\\"index\\\": 4,\\n\\t\\t\\t\\\"name\\\": \\\"Brandon\\\",\\n\\t\\t\\t\\\"events\\\": [\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\\"index\\\": 3,\\n\\t\\t\\t\\t\\t\\\"email\\\": \\\"danny@parrott.eg\\\"\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\\"index\\\": 5,\\n\\t\\t\\t\\t\\t\\\"email\\\": \\\"sarah@underwood.net\\\"\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\\"index\\\": 11,\\n\\t\\t\\t\\t\\t\\\"email\\\": \\\"bonnie@banks.ye\\\"\\n\\t\\t\\t\\t}\\n\\t\\t\\t]\\n\\t\\t},\\n\\t\\t{\\n\\t\\t\\t\\\"index\\\": 5,\\n\\t\\t\\t\\\"name\\\": \\\"Kristina\\\",\\n\\t\\t\\t\\\"events\\\": [\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\\"index\\\": 18,\\n\\t\\t\\t\\t\\t\\\"email\\\": \\\"frances@law.mf\\\"\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\\"index\\\": 15,\\n\\t\\t\\t\\t\\t\\\"email\\\": \\\"nancy@o.mo\\\"\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\\"index\\\": 6,\\n\\t\\t\\t\\t\\t\\\"email\\\": \\\"ben@holden.um\\\"\\n\\t\\t\\t\\t}\\n\\t\\t\\t]\\n\\t\\t},\\n\\t\\t{\\n\\t\\t\\t\\\"index\\\": 6,\\n\\t\\t\\t\\\"name\\\": \\\"Keith\\\",\\n\\t\\t\\t\\\"events\\\": [\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\\"index\\\": 10,\\n\\t\\t\\t\\t\\t\\\"email\\\": \\\"alfred@baldwin.za\\\"\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\\"index\\\": 9,\\n\\t\\t\\t\\t\\t\\\"email\\\": \\\"courtney@hinson.us\\\"\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\\"index\\\": 7,\\n\\t\\t\\t\\t\\t\\\"email\\\": \\\"tracey@keller.li\\\"\\n\\t\\t\\t\\t}\\n\\t\\t\\t]\\n\\t\\t}\\n\\t]\\n}\\n";

通过替换空格,换行符等将其转换为正确的json格式。

String jsonStr = jsonString.replace("\\n", "").replace("\\t", "").replace("\\'", "").replace("\\", "");

并替换

private static final String TAG_ITEM = "item";

private static final String TAG_ITEM = "items";