MainActivity找不到ID为android.R.id.list的ListView,但它就在那里

时间:2012-11-02 21:10:03

标签: android

我关注this tutorial

我已将其修改为我应用的需求,例如没有 CRUD 功能且没有主菜单 - 我只想列出在启动应用时执行的主要活动期间的所有项目

代码似乎没有错误,但运行它会给我:VM中的Unfortunately, MyFirstApp has stopped

LogCat 给了我这个:

  

E / AndroidRuntime(910):java.lang.RuntimeException:无法启动   活动   ComponentInfo {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 (使用listview的主要活动的布局):

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

5 个答案:

答案 0 :(得分:4)

看看他们如何在ListActivity文档here

中定义布局

您的ListView标识为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作为Item视图。 您应该为此传递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});

答案 1 :(得分:2)

activity_main.xml使用android:id="@android:id/list"而不是android:id="@+id/list",它应该有效。

现在,ListView的ID为yourapplicationpackage.R.id.list

答案 2 :(得分:2)

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

答案 3 :(得分:1)

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

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

答案 4 :(得分:0)

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

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

我不建议Project&gt;在这些情况下清理,您可能很容易丢失生成的R.java文件。