2013-01-24 18 views
1

我有我的列表視圖適配器的問題。ANDROID可以得到選定的項目字符串

請檢查下面我的代碼:

public void onItemClick(AdapterView<?> parent, View v, int position, long id) { 
    // TODO Auto-generated method stub 
    String selected; 

    selected = parent.getItemAtPosition(position).toString(); 

    if(selected == "Apple"){ 
     Intent apple = new Intent(Fruits.this, Apples.class); 
     startActivity(apple); 
    } 
    else if(selected == "Apricot"){ 
     Intent apricot = new Intent(Fruits.this, Apricots.class); 
     startActivity(apricot); 
    } 
    else if(selected == "Avocado"){ 
     Intent avocado = new Intent(Fruits.this, Avocado.class); 
     startActivity(avocado); 
    } 

} // end of OnItemClick method 

每當我選擇了某一行,它拋出一個NullPointerException在這條線:

 selected = parent.getItemAtPosition(position).toString(); 

這裏有什麼問題嗎?請幫忙。謝謝。

+0

的問題是,你應該檢查,如果父母爲null,或者getItemAtPosition返回null。並建議使用完整的堆棧跟蹤。 – WarrenFaith

+0

@WarrenFaith所以我應該包括選定的== null? –

回答

1

根據你的錯誤時拋出使用下面的代碼,

selected = parent.getItem(position).toString(); 

你也用過,

if(selected == "Apple"){ 

它不是正確的方式來比較字符串,而不是用它,

if(selected.equals("Apple")){ 
+0

但我必須拋出父母 –

1

,我認爲你應該寫

if(selected.equals("Apple")){ 
//Do your Code 
} 

,而不是

if(selected == "Apple"){ 
} 
+0

嗨改變它,但仍然有nullpointerexception –

0

變化

selected = parent.getItemAtPosition(yourListView.getFirstVisiblePosition() + position).toString(); 
+0

嗨試圖改變我的,但仍然nullpointerexception –

0

對於比較字符串的equality,我們使用equals()方法。 Android中有兩種比較方式。

一個是「==」運算符,另一個是「equals()」方法。

"=="比較字符串對象的參考值,而equals()方法比較字符串對象的內容。 。

使用

selected.equals("your string") 
0
public void onItemClick(AdapterView<?> parent, View v, int position, long id) { 
    TextView tv = v.findViewById(R.id.myTitle); 
    tv.getText().toString(); // String 
} 

你可以像上面這樣你的列表項的子視圖。

0

如果您的適配器包含模型,使用此代碼:

@Override 
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
     itemDrawer seleted = (itemDrawer) parent.getItemAtPosition(position); 

     Toast.makeText(getApplicationContext(), seleted.getTitle(), Toast.LENGTH_SHORT).show(); 
    } 
相關問題