Re: [問題] ListView無法顯示內容問題

作者: cooper6334 (庫波)   2014-08-25 14:36:22
你的問題是在外面(紅色)跟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)
看到這行就夠了
煩請高手們幫解決 感恩不盡!!!!
作者: cooper6334 (庫波)   2014-08-25 10:37:00
都跟你說是NullPointerException了,去看看為啥那時候myList會是Null啊!是因為你在onCreate另外開了一個myList所以外面的根本沒動到
作者: laiair (大頭)   2014-08-25 11:14:00
你的 ListView 在layout的id是list嗎?
作者: ms0561188 (蟑螂吃滷蛋)   2014-08-25 12:44:00
不是 是直接繼承ListActivity
作者: BearrrXD (BearrrXD)   2014-08-25 13:32:00
試試看把getApplicationContext換成你的Activity.this
作者: ms0561188 (蟑螂吃滷蛋)   2014-08-25 13:44:00
回樓上 一樣是出現錯誤C大 可是我可以接收到陣列的順序耶卻為什麼沒辦法獲得顯示的文字請問是我的語法有問題嗎?

Links booklink

Contact Us: admin [ a t ] ucptt.com