在ListView中显示媒体文件,NullPointerException?

时间:2014-03-11 18:03:55

标签: android listview nullpointerexception android-mediaplayer

MainActivity

public class MainActivity extends Activity 
{

/** Called when the activity is first created. */
private List<String> myList;
File file;

@Override
public void onCreate(Bundle savedInstanceState) 
{
    Log.i("MEDIA", "A");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Log.i("MEDIA", "B");
    ListView listView = (ListView) findViewById(R.id.listView1);
    myList = new ArrayList<String>();

    Log.i("MEDIA", "C");
    File directory = Environment.getExternalStorageDirectory();
    file = new File(directory + "/Test");
    File list[] = file.listFiles();

    Log.i("MEDIA", "D");
    //for (int i = 0; i < list.length; i++)
    for (int i = 0; i < 5; i++)
    {
        Log.i("MEDIA", "D1"); //CRASHES HERE
        //myList.add(list[i].getName());
        myList.add(list[i].getName());
        Log.i("MEDIA", "D2");
    }

    Log.i("MEDIA", "E");
    final StableArrayAdapter adapter = new StableArrayAdapter(this,android.R.layout.simple_list_item_1, myList);
    listView.setAdapter(adapter); 
    // Set all the file in the list.
}

private class StableArrayAdapter extends ArrayAdapter<String> 
  {

    HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();

    public StableArrayAdapter(Context context, int textViewResourceId,List<String> objects) 
    {
      super(context, textViewResourceId, objects);
      for (int i = 0; i < objects.size(); ++i) 
      {
        mIdMap.put(objects.get(i), i);
      }
    }

    @Override
    public long getItemId(int position) 
    {
      String item = getItem(position);
      return mIdMap.get(item);
    }

    @Override
    public boolean hasStableIds() 
    {
      return true;
    }

  }
}

记录:http://pastebin.com/WWmqKKvQ

我已经在SO上选择了这个问题的答案: How to show audio files in a listview in Android?

Andhave也试过这个教程: http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/

1 个答案:

答案 0 :(得分:1)

探测器是“/ Test”目录不存在,所以我将其替换为“/ Bluetooth”(这是一个存在的目录),现在它显示该文件夹中的文件列表。

问题解决了。 :D

    Log.i("MEDIA", "C");
    File directory = Environment.getExternalStorageDirectory();
    file = new File(directory+ "/Bluetooth");// + "/Test");
    File list[] = file.listFiles();