2012-11-02 27 views
0

我正在關注this tutorialMainActivity無法找到ID爲android.R.id.list的ListView,但它存在

我已將其修改爲我的應用程序的需求,例如沒有CRUD功能和沒有主菜單 - 我只想列出應用程序啓動時執行的主要活動期間的所有項目。

代碼似乎沒有錯誤,但運行它給了我:在虛擬機中的Unfortunately, MyFirstApp has stopped

logcat的給了我這樣的:

E/AndroidRuntime(910):了java.lang.RuntimeException:無法啓動 活動 ComponentInfo {com.example.myfirstproject/com.example.myfirstproject。 MainActivity}: 了java.lang.RuntimeException:你的內容必須有一個ListView的ID 屬性爲 '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> 

回答

4

看看他們的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標識並使用正確的TextView標識(名稱)

例如:

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

似乎進入「加載汽車...請稍候」對話框,但一段時間後它再次崩潰。 LogCat給出以下內容:E/Buffer Error(999):轉換結果時出錯java.lang.NullPointerException E/JSON解析器(999):解析數據時出錯org.json.JSONException:字符0處的輸入結束 E/AndroidRuntime(999):致命異常:AsyncTask#1 E/AndroidRuntime(999):java.lang.RuntimeException:執行doInBackground()時發生錯誤。對不起,我對此很陌生,錯誤似乎沒有告訴我很像以前那樣,除此之外,還有一些NullPointerException – user1701467

+0

它看起來像在你的JSON解析中的某個地方,你得到一個空指針。在堆棧跟蹤中,它應該指向代碼中崩潰的那一行 – dymmeh

+0

看起來像這一行:'JSONObject json = jParser.makeHttpRequest(url_all_cars,「GET」,params);',因此它意味着它沒有從我的PHP web服務(在wamp上運行)獲取汽車列表?爲什麼它不工作?如果我直接進入任何Web瀏覽器的'url_all_cars'路徑,就會生成正確的JSON列表。 – user1701467

2

在你activity_main.xml使用android:id="@android:id/list"而不是android:id="@+id/list",它應該工作。

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

1

注意ListView控件的ID必須@android:id/list引用所需android.R.id.listListActivity documentation

相比之下,您的id爲@+id/list會創建一個新的ID com.example.myfirstproject.R.id.list

2

使用android:id="@android:id/list",同時在XML中分配ID。

0

這是舊的文章,但對於其他人誰在這裏面臨着同樣的問題,是我的解決方案:

如果你確保,在列表視圖或您所創建的任何其他對象的ID在佈局存在 - 爲了確保去頭部源代碼,檢查在R.java文件中的ID的名稱。如果它不在那裏,那麼你沒有創建任何項目。 - 然後,在Java代碼中確保android.R不在導入列表中。如果這樣擺脫。然後手動添加你的軟件包R.java import com.yourpackagename.R; 現在您可以將我們的項目添加到Java代碼中:exp: ListView lvitems =(ListView)findViewById(R.id.nameofit);

我不建議在這些情況下使用Project> Clean,否則很容易丟失生成的R.java文件。

+1

失去一個生成的文件,那麼是什麼? – kmas

相關問題