0

试图将数据填充到列表视图中

  • 我正在使用来自服务器的 JSON 响应
  • 有错误

我已经提到了课程


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>

主要的.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>

日志::

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

任何想法 谢谢,

4

3 回答 3

1

ArrayList<HashMap<String, String>>不建议尝试填充简单的适配器。最好使用自定义适配器。

要获得清晰的图片,请参阅以下链接:

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/

于 2013-08-23T12:05:00.297 回答
0

我希望你没有得到正确的 json 字符串数据。您尝试解析的 JSON 字符串无效 - 看起来它有一些原始 HTML,这意味着它要么生成错误,要么 PHP 正在插入错误/警告并破坏字符串

如果您获得正确的 json 数据然后不用于哈希映射,请尝试将数据存储在 Bean 对象中并将该对象添加到列表中。使用适配器添加此列表后。

于 2013-08-23T12:01:27.590 回答
0

替换以下代码段

        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();
    }

有了这个:

    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="";
    }

我希望它会有所帮助!

于 2013-08-23T12:16:32.577 回答