作者cooper6334 (小恐龍)
看板AndroidDev
標題Re: [問題] ListView無法顯示內容問題
時間Mon Aug 25 14:36:22 2014
你的問題是在
外面(紅色)跟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)
看到這行就夠了
煩請高手們幫解決 感恩不盡!!!!
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 210.61.163.55
※ 文章網址: http://www.ptt.cc/bbs/AndroidDev/M.1408930345.A.9DE.html
※ 編輯: ms0561188 (210.61.163.55), 08/25/2014 09:33:52
推 cooper6334: 都跟你說是NullPointerException了,去看看為啥那時候 08/25 10:37
→ cooper6334: myList會是Null 08/25 10:37
→ cooper6334: 啊!是因為你在onCreate另外開了一個myList所以外面的 08/25 10:38
→ cooper6334: 根本沒動到 08/25 10:39
推 laiair: 你的 ListView 在layout的id是list嗎? 08/25 11:14
→ ms0561188: 不是 是直接繼承ListActivity 08/25 12:44
推 BearrrXD: 試試看把getApplicationContext換成你的Activity.this 08/25 13:32
→ ms0561188: 回樓上 一樣是出現錯誤 08/25 13:44
→ ms0561188: C大 可是我可以接收到陣列的順序耶 08/25 13:47
→ ms0561188: 卻為什麼沒辦法獲得顯示的文字 08/25 13:48
→ ms0561188: 請問是我的語法有問題嗎? 08/25 13:48
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.163.58.205
※ 文章網址: http://www.ptt.cc/bbs/AndroidDev/M.1408948585.A.B04.html
※ 編輯: cooper6334 (118.163.58.205), 08/25/2014 14:46:37
推 ms0561188: 感謝!! 已獲得解答 謝謝高手!! 08/25 18:13