嘿大家现在我正试图在 android 设备 sd 卡上显示某个文件夹中的所有文件,ListView
到目前为止我运气不好,它因空指针异常而崩溃,所以我想知道这里是否有人可以发光我的问题将我的活动和 logcat 贴在下面,谢谢。
活动
package com.mkyong.android;
import java.io.File;
import java.util.ArrayList;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.view.View;
public class ListMobileActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.res);
}
public ArrayList<String> GetFiles(String DirectoryPath) {
ArrayList<String> MyFiles = new ArrayList<String>();
File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles();
if (files.length == 0)
return null;
else {
for (int i=0; i<files.length; i++)
MyFiles.add(files[i].getName());
}
return MyFiles;
}
{
ListView lv;
ArrayList<String> FilesInFolder = GetFiles("/sdcard/RootBox");
lv = (ListView)findViewById(R.id.listView1);
lv.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, FilesInFolder));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
}
});
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
//get selected items
String selectedValue = (String) getListAdapter().getItem(position);
Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();
}
}
和日志猫
05-24 06:42:28.992: E/AndroidRuntime(796): FATAL EXCEPTION: main
05-24 06:42:28.992: E/AndroidRuntime(796): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mkyong.android/com.mkyong.android.ListMobileActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
05-24 06:42:28.992: E/AndroidRuntime(796): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
05-24 06:42:28.992: E/AndroidRuntime(796): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-24 06:42:28.992: E/AndroidRuntime(796): at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-24 06:42:28.992: E/AndroidRuntime(796): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-24 06:42:28.992: E/AndroidRuntime(796): at android.os.Handler.dispatchMessage(Handler.java:99)