0

我在 android 的 ListView 中显示 ArrayList 时遇到问题。尝试在 ListView 中加载数组 List 时出现空指针异常。实际上我正在尝试在 android 列表视图中加载存储卡内容。(显示特定文件夹内容)。我是 Android 开发的新手,请帮忙。

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) {
        // TODO Auto-generated method stub
        if(mExternalMediaAvailable){
            Toast.makeText(getApplicationContext(), "External Media..", Toast.LENGTH_LONG).show();

            //getDir(Environment.getExternalStorageDirectory().toString());
            //Intent i = new Intent(Intent.ACTION_VIEW);
        String SD_Card_Path=Environment.getExternalStorageDirectory().toString();

            //String SD_Card="/sdcard/reports";
            File file = new File(SD_Card_Path);
            File[] file_Array=file.listFiles();

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

            lv=(ListView)findViewById(R.id.list_view);

            for(int i=0;i< file_Array.length;i++){
                 file=file_Array[i];
                 if(file.isDirectory()){
                     Log.d("Directory","Added...");
                     item.add(file.getName()+"/");
                 }
                 else{
                     Log.d("File","Added...");
                     item.add(file.getName());
                 }
            }
            Log.d("adapter", "Before...");
            ArrayAdapter<String> adapter=new ArrayAdapter<String>(Access_MemCardActivity_main.this,android.R.layout.simple_list_item_1,item);
            lv.setAdapter(adapter);
            Log.d("set_adapter", "After...");
            Toast.makeText(getApplicationContext(), adapter.toString(),Toast.LENGTH_LONG).show();
        }
        else{
            Toast.makeText(getApplicationContext(), "You Dont Have External Media..", Toast.LENGTH_LONG).show();
        }
    }
});        
}

}

4

1 回答 1

1

在将适配器设置为ListView之前,通过在Log中打印arraylist的大小来检查 arraylist 是否包含项目

于 2012-12-05T11:08:50.577 回答