2014-08-27 33 views
0

爲什麼我在fn = list.getSelectedItem().toString();處遇到NullPointerException。保存所選項目的ListView時的NPE

public class FileList extends Activity{ 

ListView list; 
String fn; 

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


    list = (ListView) findViewById(R.id.lv1); 

    String pth = Environment.getExternalStorageDirectory().getPath(); 
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getListOfFiles(pth)); 
    list.setAdapter(adapter); 

    list.setOnItemClickListener(new OnItemClickListener() { 

     public void onItemClick(AdapterView<?> arg0, 
        View arg1, int position, long arg3) 
     { 
      System.out.println(list.getSelectedItem().toString()); 
      fn = list.getSelectedItem().toString(); //NPE Here 
     } 
     }); 

} 
+0

theres在getSelectedItem()的第5行上輸入了一個錯字。 – r2DoesInc 2014-08-27 13:32:04

+0

@ r2DoesInc是什麼?它看起來像我變得瞎了:D你能爲我找到它:P – 2014-08-27 13:33:25

+0

Fn宣佈在哪裏?請注意,您不能修改在OnItemClickListener範圍之外聲明的變量的值,並且只有當它們聲明爲「最終」時纔可以讀取它們的值。 – mittelmania 2014-08-27 13:34:19

回答

2

您應該使用getItemAtPosition代替

String path = (String) arg0.getItemAtPosition(position); 

http://developer.android.com/reference/android/widget/AdapterView.html#getItemAtPosition%28int%29

文檔:

在API級別

公共對象getItemAtPosition(INT位置) 增補1

Gets the data associated with the specified position in the list. 
Parameters 
position Which data to get 
Returns The data associated with the specified position in the list 

而且讀

公共對象getSelectedItem()在API級別1

返回對應的數據如果沒有選擇任何內容,則返回到當前選定的項目,或者爲空 。

+0

是的,謝謝你的詳細觀點:) – 2014-08-27 14:10:34

1

嘗試使用另一種方法:

protected void onListItemClick(ListView l, View v, int position, long id) { 
    super.onListItemClick(l, v, position, id); 
    Object selectedValue = this.getListAdapter().getItem(position); 
    String value = selectedValue.toString(); 
    Toast.makeText(this, "You have chosen " + value , Toast.LENGTH_LONG).show(); 

} 
+1

只要澄清一下,這種方式應該與ListActivity一起使用。 – 2014-08-27 13:40:18

+0

Arash,對吧! – 2014-08-27 13:42:48