2016-12-22 191 views
0

我已經創建了一個Country.java類,並使我的自定義適配器myListAdapter擴展了ArrayAdapter。我沒有讓行,我既logcat中任何內留言,但應用程序崩潰:ListView使用自定義適配器

countName.setText(" "+currentCountry.getCountryName()); 

究竟什麼是錯在這裏我怎樣才能得到國家或地區名稱?

public class Country{ 
    private String countryName; 
    private String capitalName; 

    public Country(String countryName, String capitalName) { 
    this.countryName = countryName; 
    this.capitalName = capitalName; 
} 

    public String getCountryName() { 
     return countryName; 
    } 
    public String getCapitalName() { 
     return capitalName; 
    } 
} 

這裏是類myListAdapter

private class MyListAdapter extends ArrayAdapter<Country>{ 

     public MyListAdapter() { 
      super(MainActivity.this, R.layout.item_view, myCountries); 
     } 

     public View getView(int position, View convertView, ViewGroup parent) { 

      View itemView = convertView; 
      if(itemView == null){ 
       itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false); 
      } 

      Country currentCountry = myCountries.get(position); 

      TextView countName = (TextView) findViewById(R.id.item_countryName); 
      countName.setText(" "+currentCountry.getCountryName()); 

      TextView capName = (TextView) findViewById(R.id.item_CapName); 
      capName.setText(currentCountry.getCapitalName()); 

      return itemView; 
     } 
    } 

item_view.xml是:

<TextView 
     android:text="TextView" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/item_countryName" /> 

    <TextView 
     android:text="TextView" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/item_CapName" /> 
+0

什麼是myCountries?它從何而來? –

+0

http://androidexample.com/How_To_Create_A_Custom_Listview_-_Android_Example/index.php?view=article_discription&aid=67請參閱此鏈接。適配器使用ViewHolder是很好的。 –

回答

0
Change the below code in your adapter : 

TextView countName = (TextView) itemView.findViewById(R.id.item_countryName); 
      countName.setText(" "+currentCountry.getCountryName()); 

      TextView capName = (TextView) itemView.findViewById(R.id.item_CapName); 
      capName.setText(currentCountry.getCapitalName()); 

編輯我的代碼:

MyListAdapter adapter = new MyListAdapter(this, 
     R.layout.item_view, myCountries); 
listView.setAdapter(adapter); 
+0

它沒有幫助,仍然應用程序崩潰 – SofL

+0

你能分享你的例外。你還在得到Nullpointer Exception嗎? –

+0

我收到以下異常 – SofL

0

您是否手動啓動getView()方法?你應該如下所示@Override這個方法。如果您設置了適配器並且屏幕已加載,getView()會自動觸發。

@Override 
    public View getView(int i, View view, ViewGroup viewGroup) { 

    } 

你應該使用findViewById()方法如下;

TextView countName = (TextView) itemView.findViewById(R.id.item_countryName); 
+0

非常感謝。我正在miising (TextView)itemView.findViewById(R.id.item_countryName); – SofL

+0

我很高興爲您提供幫助。它是否在不覆蓋getView()方法的情況下工作? – oyenigun

+0

實際上我沒有重寫getView()方法,但是當我在這裏粘貼代碼時,我錯過了它。 – SofL

相關問題