在ListView中显示ArrayList内容

时间:2012-12-03 07:13:26

标签: android listview android-arrayadapter android-sdcard

我在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();
        }
    }
});        
}

}

1 个答案:

答案 0 :(得分:1)

在将适配器设置为 ListView 之前,请先打印 arraylist 大小,检查arraylist是否包含项目>在日志