为什么我在ListFragment中收到此错误?

时间:2013-02-13 16:56:28

标签: android android-listfragment

这是我很好奇的具体错误。

02-14 00:54:41.993: E/AndroidRuntime(2000): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.thesis.menubook/com.thesis.menubook.MenuMain}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

我研究并将listView放入我的xml android:id = "@android:id/list"但仍然存在错误。

这是我的.java文件

package com.thesis.menubook;

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

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MenuCategory extends ListFragment {
    JSONParser jsonParser = new JSONParser();
    ArrayList<HashMap<String, String>> categoryList = new ArrayList<HashMap<String, String>>();
    private ProgressDialog pDialog;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        new GetCategories().execute();
    }


    @Override
    public void onResume() {
      //onResume happens after onStart and onActivityCreate
        new GetCategories().execute();
        super.onResume() ; 
    }

    class GetCategories extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
             super.onPreExecute();
             pDialog = new ProgressDialog(getActivity().getApplicationContext());
             Log.d("Activity Context", getActivity().getApplicationContext().toString() + "");
             pDialog.setMessage("Loading Categories. Please wait...");
             pDialog.setIndeterminate(false);
             pDialog.setCancelable(false);
             pDialog.show();
        }

        /**
         * Getting product details in background thread
         * */
        protected String doInBackground(String... param) {
            Bundle b = getActivity().getIntent().getExtras();
            String ipaddress = b.getString("IPAddress");

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            Log.d("IP ADDRESS", ipaddress +" ");

            JSONObject json = jsonParser.makeHttpRequest("http://"+ipaddress+"/MenuBook/selectCategories.php", "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Categories: ", json.toString() + " ");
            int num = 1;
            try {
                // Checking for SUCCESS TAG
                int success = json.getInt("success");

                if (success == 1) {
                    // products found
                    // Getting Array of Products

                    JSONArray category_list = json.getJSONArray("category_list");
                    Log.d("Category List JSON Array", category_list.toString() + "");
                    // looping through All Products
                    for (int j = 1; j < category_list.length(); j++) {
                        JSONObject c = category_list.getJSONObject(j);

                        // Storing each json item in variable
                        String category = c.getString("category");

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

                        // adding each child node to HashMap key => value
                        map.put("category", category);

                        Log.d("category #"+num+"", category + " ");
                        num = num + 1;
                        // adding HashList to ArrayList
                        if(categoryList.contains(map) != true)
                        {
                            categoryList.add(map);
                        }
                        Log.d("Category List", categoryList.toString() + " ");
                    }
                } 
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String result) {
            pDialog.dismiss();

            ArrayAdapter<ArrayList<HashMap<String, String>>> arrayAdapter = new ArrayAdapter<ArrayList<HashMap<String, String>>>
            (getActivity().getApplicationContext(), 
                    R.layout.activity_menu_category);
            arrayAdapter.add(categoryList);
            Log.d("Category List", categoryList.toString() + "" );
            setListAdapter(arrayAdapter);

        }

    }
}

这是xml

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >


</ListView>

更新的JAVA文件

package com.thesis.menubook;

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

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MenuCategory extends ListFragment {
    JSONParser jsonParser = new JSONParser();
    ArrayList<HashMap<String, String>> categoryList = new ArrayList<HashMap<String, String>>();
    private ProgressDialog pDialog;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        new GetCategories().execute();
    }


    class GetCategories extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
             super.onPreExecute();
             pDialog = new ProgressDialog(getActivity());
             Log.d("Activity Context", getActivity().getApplicationContext().toString() + "");
             pDialog.setMessage("Loading Categories. Please wait...");
             pDialog.setIndeterminate(false);
             pDialog.setCancelable(false);
             pDialog.show();
        }

        /**
         * Getting product details in background thread
         * */
        protected String doInBackground(String... param) {
            Bundle b = getActivity().getIntent().getExtras();
            String ipaddress = b.getString("IPAddress");

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            Log.d("IP ADDRESS", ipaddress +" ");

            JSONObject json = jsonParser.makeHttpRequest("http://"+ipaddress+"/MenuBook/selectCategories.php", "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Categories: ", json.toString() + " ");
            int num = 1;
            try {
                // Checking for SUCCESS TAG
                int success = json.getInt("success");

                if (success == 1) {
                    // products found
                    // Getting Array of Products

                    JSONArray category_list = json.getJSONArray("category_list");
                    Log.d("Category List JSON Array", category_list.toString() + "");
                    // looping through All Products
                    for (int j = 1; j < category_list.length(); j++) {
                        JSONObject c = category_list.getJSONObject(j);

                        // Storing each json item in variable
                        String category = c.getString("category");

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

                        // adding each child node to HashMap key => value
                        map.put("category", category);

                        Log.d("category #"+num+"", category + " ");
                        num = num + 1;
                        // adding HashList to ArrayList
                        if(categoryList.contains(map) != true)
                        {
                            categoryList.add(map);
                        }
                        Log.d("Category List", categoryList.toString() + " ");
                    }
                } 
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String result) {
            pDialog.dismiss();

            ListAdapter arrayAdapter = new ArrayAdapter<ArrayList<HashMap<String, String>>>
            (getActivity(), 
                    R.layout.activity_menu_category, R.id.category);
            Log.d("Category List", categoryList.toString() + "" );
            setListAdapter(arrayAdapter);

        }

    }
}

更新的XML文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id = "@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <TextView
        android:id="@+id/category"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="6dip"
        android:paddingLeft="6dip"
        android:textSize="20sp"
        android:textStyle="bold" />
</LinearLayout>

用getActivity()替换getActivity()。getApplicationContext()后的LogCat,用LsitAdapter替换ArrayAdapter并更改xml文件:

02-14 01:56:15.382: V/TLINE(2474): new: android.text.TextLine@4066b8e0
02-14 01:56:16.772: V/TLINE(2474): new: android.text.TextLine@406747c0
02-14 01:56:47.052: D/dalvikvm(2474): GC_FOR_ALLOC freed 160K, 5% free 6481K/6791K, paused 167ms
02-14 01:56:47.096: I/dalvikvm-heap(2474): Grow heap (frag case) to 6.927MB for 513744-byte allocation
02-14 01:56:47.566: D/dalvikvm(2474): GC_CONCURRENT freed 2K, 5% free 6981K/7303K, paused 24ms+26ms
02-14 01:56:48.123: D/NetWork Info(2474): NetworkInfo: type: mobile[UMTS], state: CONNECTED/CONNECTED, reason: simLoaded, extra: internet, roaming: false, failover: false, isAvailable: true
02-14 01:56:54.762: D/Response(2474): org.apache.http.message.BasicHttpResponse@4064d2f0--response from apache
02-14 01:56:54.762: D/IP Address(2474): 192.168.10.149:80
02-14 01:56:54.898: D/NEXT VALUE --in Async on postexecute(2474): true
02-14 01:56:58.702: D/dalvikvm(2474): GC_CONCURRENT freed 95K, 4% free 7297K/7559K, paused 9ms+21ms
02-14 01:57:04.461: D/URL(2474): http://192.168.10.149:80/MenuBook/checkTable.php
02-14 01:57:07.901: D/Check Table(2474): {"success":1,"tabledb":[{"table_location":"UP","table_seat":"5","table_status":"AVAILABLE","table_ID":"001"}]}
02-14 01:57:08.028: D/Table Status in doinbg(2474): AVAILABLE
02-14 01:57:08.518: D/Table Status in post execute(2474): AVAILABLE
02-14 01:57:10.718: D/Activity Context(2474): android.app.Application@40646bf8
02-14 01:57:10.982: D/IP ADDRESS(2474): 192.168.10.149:80 
02-14 01:57:12.905: D/dalvikvm(2474): GC_CONCURRENT freed 267K, 6% free 7451K/7879K, paused 10ms+22ms
02-14 01:57:17.432: D/All Categories:(2474): {"success":1,"category_list":[{"category":"MAIN DISH"},{"category":"MAIN DISH"},{"category":"DESSERT"}]} 
02-14 01:57:17.572: D/Category List JSON Array(2474): [{"category":"MAIN DISH"},{"category":"MAIN DISH"},{"category":"DESSERT"}]
02-14 01:57:17.572: D/category #1(2474): MAIN DISH 
02-14 01:57:17.638: D/Category List(2474): [{category=MAIN DISH}] 
02-14 01:57:17.862: D/category #2(2474): DESSERT 
02-14 01:57:18.022: D/Category List(2474): [{category=MAIN DISH}, {category=DESSERT}] 
02-14 01:57:18.672: D/Category List(2474): [{category=MAIN DISH}, {category=DESSERT}]
02-14 01:57:20.442: D/dalvikvm(2474): GC_CONCURRENT freed 371K, 8% free 7561K/8135K, paused 14ms+14ms
02-14 01:57:20.632: D/dalvikvm(2474): GC_FOR_ALLOC freed <1K, 8% free 7560K/8135K, paused 174ms
02-14 01:57:20.652: I/dalvikvm-heap(2474): Grow heap (frag case) to 7.726MB for 246508-byte allocation
02-14 01:57:20.882: D/dalvikvm(2474): GC_FOR_ALLOC freed 0K, 8% free 7801K/8391K, paused 148ms

2 个答案:

答案 0 :(得分:1)

为此更改ListView:

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>

我更改为id:android:id="@id/android:list"

根据this教程

答案 1 :(得分:0)

我终于检索了数据,这是通过替换onPostExecute子句上的ArrayAdapter定义

        @Override
        protected void onPostExecute(String result) {
            pDialog.dismiss();

            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
            (getActivity(), 
                    R.layout.activity_menu_category, R.id.category);
            for(int i = 0; i<= categoryList.size() - 1; i++)
            {
                String value = categoryList.get(i).values().toString();
                value.replace('[', ' ');
                value.replace(']', ' ');
                arrayAdapter.add(value);
                Log.d("Specific Value Category List", value + "");
            }
            Log.d("Category List", categoryList.toString() + "" );
            setListAdapter(arrayAdapter);

        }
相关问题