【问题标题】:MainActivity can't find ListView with id of android.R.id.list, but it's thereMainActivity 找不到 ID 为 android.R.id.list 的 ListView,但它在那里
【发布时间】:2012-10-23 13:49:37
【问题描述】:

我在关注this tutorial

我已根据我的应用程序的需要对其进行了修改,例如没有 CRUD 功能和主菜单 - 我只想列出在应用程序启动时执行的主要活动期间的所有项目.

代码似乎没有错误,但在虚拟机中运行它会给我:Unfortunately, MyFirstApp has stopped

LogCat 给了我这个:

E/AndroidRuntime(910): java.lang.RuntimeException: 无法启动 活动 组件信息{com.example.myfirstproject/com.example.myfirstproject.MainActivity}: java.lang.RuntimeException: 你的内容必须有一个 ID 的 ListView 属性是'android.R.id.list'

做什么?我检查了我的 .xml 布局并进行了更改,但应用程序仍然崩溃。

MainActivity.java

package com.example.myfirstproject;

//imports

public class MainActivity extends ListActivity implements OnItemClickListener {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> carsList;

    // url to get all products list
    private static String url_all_cars = "http://localhost/webservice/get_all_cars.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_CARS = "cars";
    private static final String TAG_NAME = "name";

    // products JSONArray
    JSONArray cars = null;

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

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

        // Loading products in Background Thread
        new LoadAllcars().execute();

        // Get listview
        ListView lv = getListView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllcars extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading cars. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All cars: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    cars = json.getJSONArray(TAG_CARS);

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

                        // Storing each json item in variable
                        String title = 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_NAME, name);

                        // adding HashList to ArrayList
                        carsList.add(map);
                    }
                } else {
                    // no products found
                    pDialog = new ProgressDialog(MainActivity.this);
                    pDialog.setMessage("No cars found");
                    pDialog.setIndeterminate(false);
                    pDialog.setCancelable(false);
                    pDialog.show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            MainActivity.this, carsList,
                            android.R.id.list, new String[] {TAG_NAME},
                            new int[] { R.id.title });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }
    }
}

activity_main.xml(带有列表视图的 mainactivity 的布局):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >
    </ListView>   
</LinearLayout>

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

    <!-- Name Label -->
    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="6dip"
        android:paddingLeft="6dip"
        android:textSize="17dip"
        android:textStyle="bold" />

</LinearLayout>

【问题讨论】:

    标签: android


    【解决方案1】:

    看看他们是如何在 ListActivity 文档here中定义布局的

    您的 ListView Id 是 android:id="@+id/list",它必须是 android:id="@android:id/list"

    另外,你的 ListAdapter 会崩溃

    ListAdapter adapter = new SimpleAdapter(
                                MainActivity.this, carsList,
                                android.R.id.list, new String[] {TAG_NAME},
                                new int[] { R.id.title });
    

    您正在告诉适配器使用 android ListView 作为项目视图。 您应该为此传递您的 list_item.xml ID 并使用正确的 TextView ID(名称)

    例如:

    ListAdapter adapter = new SimpleAdapter(
                                    MainActivity.this, carsList,
                                    R.layout.list_item, new String[] {TAG_NAME},
                                    new int[] { R.id.name});
    

    【讨论】:

    • 似乎进入了“正在加载汽车...请稍候”对话框,但过了一段时间它又崩溃了。 LogCat 提供以下信息:E/Buffer Error(999): Error converting result java.lang.NullPointerException E/JSON Parser(999): Error parsing data org.json.JSONException: End of input at character 0 of E/AndroidRuntime(999): FATAL EXCEPTION: AsyncTask #1 E/AndroidRuntime(999): java.lang.RuntimeException: An error occured while executing doInBackground()。抱歉,我对此很陌生,除了在某处有一些 NullPointerException 之外,该错误似乎并没有像以前那样告诉我
    • 看起来在你的 JSON 解析中的某个地方你得到了一个空指针。在堆栈跟踪中,它应该指向代码中崩溃的行
    • 看起来是这一行:JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params);,因此这意味着它没有从我的 PHP 网络服务(在 wamp 上运行)获取汽车列表?为什么它不起作用?如果我在任何 Web 浏览器中直接转到 url_all_cars 路径,我会正确生成 JSON 列表。
    • 您的应用清单中是否设置了互联网权限? stackoverflow.com/questions/2378607/…
    • 刚刚做了。同样的问题在同一行。但我使用的是本地主机(我的计算机上的 MySQL、WAMP),所以我需要那个权限吗?
    【解决方案2】:

    在您的activity_main.xml 中使用android:id="@android:id/list" 而不是android:id="@+id/list",它应该可以工作。

    现在您的 ListView 的 ID 是 yourapplicationpackage.R.id.list

    【讨论】:

      【解决方案3】:

      请注意,ListView 的 ID必须@android:id/list 以根据 ListActivity documentation 引用所需的 android.R.id.list

      相比之下,您的 ID @+id/list 会创建一个新 ID com.example.myfirstproject.R.id.list

      【讨论】:

        【解决方案4】:

        在 xml 中分配 id 时使用 android:id="@android:id/list"

        【讨论】:

          【解决方案5】:

          这是旧帖子,但对于其他面临同样问题的人来说,这是我的解决方案:

          如果您确定列表视图或您创建的任何其他对象的 ID 存在于布局中 - 为确保前往生成源,请检查 R.java 文件中的 ID 名称。如果它不存在,那么您没有创建任何项目。 - 然后,在 Java 代码中确保 android.R 不在导入列表中。如果这样摆脱。然后手动添加你的包 R.java 导入 com.yourpackagename.R; 现在您可以将我们的项目添加到 Java 代码中:exp: ListView lvitems = (ListView) findViewById(R.id.nameofit);

          我不建议在这些情况下使用 Project>Clean,您很容易丢失生成的 R.java 文件。

          【讨论】:

          • 丢失了一个生成的文件,那又怎样?
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-07-29
          • 2021-01-06
          • 1970-01-01
          • 1970-01-01
          • 2015-02-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多