如何在android中单击按钮时显示特定文件夹内容

时间:2012-11-22 05:40:03

标签: android android-listview android-sdcard

我正在寻找在按钮点击事件上打开指定文件夹内容(存在于外部存储卡上)。并将它们显示在单独的列表中。当我在列表中加载内容时,我将错误视为空指针异常。我的源代码是:

public class Access_MemCardActivity_main extends Activity {

Button btn_view;
boolean mExternalMediaAvailable=false;
ArrayList<String> item=new ArrayList<String>();
ArrayAdapter<String> adapter;
private ListView lv;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    String state=Environment.getExternalStorageState();

    if(Environment.MEDIA_MOUNTED.equals(state)){
        mExternalMediaAvailable=true;
    }
    else{
        mExternalMediaAvailable=false;
    }

    btn_view=(Button)findViewById(R.id.btn_view);

    btn_view.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {

        if(mExternalMediaAvailable){
            Toast.makeText(getApplicationContext(), "External Media..", Toast.LENGTH_LONG).show();


            String SD_Card_Path=Environment.getExternalStorageDirectory().toString()+"/reports";


            File file = new File(SD_Card_Path);
            File[] file_Array=file.listFiles();

            Toast.makeText(getApplicationContext(), file_Array.toString(), Toast.LENGTH_LONG).show();

            for(int i=0;i< file_Array.length;i++){
                 file=file_Array[i];
                 if(file.isDirectory()){
                     item.add(file.getName()+"/");
                 }
                 else{
                     item.add(file.getName());
                 }
            }
            Toast.makeText(getApplicationContext(), item.toString(),Toast.LENGTH_LONG).show();



            lv=(ListView)findViewById(R.id.list_view);
            adapter=new ArrayAdapter<String>(Access_MemCardActivity_main.this,R.layout.main,R.id.list_view,item);
            lv.setAdapter(adapter);



        }
        else{
            Toast.makeText(getApplicationContext(), "You Dont Have External Media..", Toast.LENGTH_LONG).show();
        }
    }

1 个答案:

答案 0 :(得分:0)

此,

adapter=new ArrayAdapter<String>(Access_MemCardActivity_main.this,R.layout.main,R.id.list_view,item);

我看错了......你无法通过R.layout.main。相反,你应该通过row.xml布局。

无论如何,在片段下面都可以正常工作。

lv = (ListView) findViewById(R.id.list_view);
adapter = new ArrayAdapter < String > (this,
android.R.layout.simple_list_item_1);

for (int i = 0; i < file_Array.length; i++) {
    file = file_Array[i];
    if (file.isDirectory()) {
        adapter.add(file.getName() + "/");

    } else {
        adapter.add(file.getName());
    }
}
lv.setAdapter(adapter);

如果您在onClickListener下构建ArrayAdapter,则将上下文作为ActivityName.this传递。

adapter = new ArrayAdapter < String > (ActivityName.this,
    android.R.layout.simple_list_item_1);