简体   繁体   English

为什么我的ListFragment中出现此错误?

[英]Why Am I getting this error in my ListFragment?

This is the specific error I am curious about. 这是我很好奇的特定错误。

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'

I researched and put the listView in my xml to android:id = "@android:id/list" but still, the error persists. 我进行了研究,并将listView放入xml中的android:id = "@android:id/list"但错误仍然存​​在。

Here is my .java file 这是我的.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);

        }

    }
}

And here is the xml 这是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>

UPDATED JAVA FILE 更新的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);

        }

    }
}

UPDATED XML FILE 更新的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>

LogCat after replacing getActivity().getApplicationContext() with getActivity(), and ArrayAdapter with LsitAdapter and changing xml file : 在用getActivity()替换getActivity()。getApplicationContext()和用LsitAdapter替换ArrayAdapter并更改xml文件之后,使用LogCat:

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

Change your ListView for this: 为此更改您的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>

I changed to id to this: android:id="@id/android:list" 我将ID更改为此: android:id="@id/android:list"

According to this tutorial 根据教程

I finally retrieved the data and that is by replacing the ArrayAdapter definition on the onPostExecute clause 我终于检索了数据,那就是通过替换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);

        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在运行应用程序时出现此错误? - Why am I getting this error when I run my app? 为什么我的Android代码中出现空指针错误? - Why am I getting a null pointer error in my Android Code? 为什么我在android中的活动出错? - Why I am getting error with my activity in android? 为什么在sqlite通话中出现语法错误? - Why am I getting a syntax error on my sqlite call? 为什么我的main.xml中出现错误? - Why am I getting an error in my main.xml? 为什么在尝试与我的服务器通信时出现此错误? - Why am i getting this error when trying to communicate with my server? 为什么在我的项目中实现 mapbox 时会出错? - Why am I getting error when implementing mapbox to my project? 为什么我在AsyncTask中得到这个ClassCastException? - Why am I getting this ClassCastException in my AsyncTask? 为什么我的代码中出现ArrayIndexOutOfBounds错误? 我没有为我的ArrayAdapter设置默认长度 - Why am I getting an ArrayIndexOutOfBounds error in my code? I do not set a default length to my ArrayAdapter 我在 getuserinformation 中的 DataSnapShot 中遇到错误 - I am getting error in my DataSnapShot in getuserinformation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM