保存ListView的选定项目时的NPE

时间:2014-08-27 13:31:09

标签: android android-listview

为什么我在fn = list.getSelectedItem().toString();获得NullPointerException。

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
         }
         });

}

2 个答案:

答案 0 :(得分:2)

您应该使用getItemAtPosition代替

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

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

文档:

  

public Object getItemAtPosition(int position)       在API级别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

同时阅读

  

public Object getSelectedItem()在API级别1中添加

     

返回与当前所选项对应的数据,或null   如果没有选择。

答案 1 :(得分: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();

}
相关问题