你的问题是在外面(红色)跟onCreate里面(绿色)各有一个myList
myList是区域变量,这个函式结束以后就不能用了
你在onCreate里面都用myList,结果之后在Toast的时候用的是myList当然是null
你Toast应该是放在onListItemClick吧??
假如是在onCreate里呼叫的话就会用到myList而不会有问题
改法就是从头到尾都用全域变量,不要在onCreate里面另外宣告一个区域变量
public class MainActivity extends ListActivity {
private File file;
private List<String> myList;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
File file = new File( root_sd ) ;
File list[] = file.listFiles();
for(int i=0 ;i<list.length;i++)
{
myList.add(list[i].getAbsolutePath());
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myList ));
}
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Toast.makeText(getApplicationContext(),position+"",
Toast.LENGTH_LONG).show();
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
在这上面的code中会出现阵列的顺序如 0 1 2这样
但是又尝试了
Toast.makeText(getApplicationContext(),myList.get(position)+"",
Toast.LENGTH_LONG).show();
而出现了错误讯息 如下
08-25 09:24:49.432: E/AndroidRuntime(28120): FATAL EXCEPTION: main
08-25 09:24:49.432: E/AndroidRuntime(28120): java.lang.NullPointerException
08-25 09:24:49.432: E/AndroidRuntime(28120):
at com.example.projectname.MainActivity.onListItemClick(MainActivity.java:48)
看到这行就够了
烦请高手们帮解决 感恩不尽!!!!