1

我是android开发的新手。我想创建一个简单的应用程序,将所有音乐文件从音乐加载到列表视图中。为此,我创建了两个文件,如下所示,

package com.chandra.TestMedia;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.ListActivity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ListAdapter;


public class TestMediaActivity  extends ListActivity {
/** Called when the activity is first created. */

private static final String MEDIA_PATH = new String("/sdcard/");
List<String> songs = new ArrayList<String>();

private MediaPlayer mp = new MediaPlayer();
private int currentPosition = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    updateSongList();
}
public void updateSongList() 
{
     System.out.println("home.list().length ");
      File home = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Music");
      System.out.println("home.list().length " + home.list().length);
      songs.addAll(Arrays.asList(home.list()));
        setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.test_item, songs));


}


protected void onListItemClick(ListView l, View v, int position, long id)
{
    currentPosition = position;
    playSong(MEDIA_PATH + songs.get(position));
}
private void playSong(String songPath) {
    try {

            mp.reset();
            mp.setDataSource(songPath);
            mp.prepare();
            mp.start();

            // Setup listener so next song starts automatically
            mp.setOnCompletionListener(new OnCompletionListener() {

                    public void onCompletion(MediaPlayer arg0) {
                            nextSong();
                    }

            });

    } catch (IOException e) {
            Log.v(getString(R.string.app_name), e.getMessage());
    }
}
private void nextSong() {
    if (++currentPosition >= songs.size()) {
        // Last song, just reset currentPosition
        currentPosition = 0;
} else {
        // Play next song
        playSong(MEDIA_PATH + songs.get(currentPosition));
 }
}


}

另一个支持类是,

package com.Chandra.TestMedia;

import java.io.File;
import java.io.FilenameFilter;

public class Mp3Filter implements FilenameFilter 
{

@Override
public boolean accept(File dir, String filename) {
    // TODO Auto-generated method stub
    return true;
}

}

我的清单如下,

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.chandra.TestMedia"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".TestMediaActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
 </manifest>

我正在具有 2.2.1 操作系统的 HTC wildfire 上对此进行测试,并且我在 2.2 中实现了该应用程序。

我的问题是当我尝试打印长度时崩溃了,System.out.println("home.list().length " + home.list().length); 我确信我的设备中有很多音乐文件。你们能帮我做错什么吗?

错误日志是,

08-16 12:19:39.028: E/AndroidRuntime(519): FATAL EXCEPTION: main
08-16 12:19:39.028: E/AndroidRuntime(519): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.vsoft.TestMedia/com.vsoft.TestMedia.TestMediaActivity}: java.lang.NullPointerException
08-16 12:19:39.028: E/AndroidRuntime(519):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
08-16 12:19:39.028: E/AndroidRuntime(519):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
08-16 12:19:39.028: E/AndroidRuntime(519):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
08-16 12:19:39.028: E/AndroidRuntime(519):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
08-16 12:19:39.028: E/AndroidRuntime(519):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-16 12:19:39.028: E/AndroidRuntime(519):  at android.os.Looper.loop(Looper.java:123)
08-16 12:19:39.028: E/AndroidRuntime(519):  at android.app.ActivityThread.main(ActivityThread.java:4627)
08-16 12:19:39.028: E/AndroidRuntime(519):  at java.lang.reflect.Method.invokeNative(Native Method)
08-16 12:19:39.028: E/AndroidRuntime(519):  at java.lang.reflect.Method.invoke(Method.java:521)
08-16 12:19:39.028: E/AndroidRuntime(519):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-16 12:19:39.028: E/AndroidRuntime(519):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-16 12:19:39.028: E/AndroidRuntime(519):  at dalvik.system.NativeStart.main(Native Method)
08-16 12:19:39.028: E/AndroidRuntime(519): Caused by: java.lang.NullPointerException
08-16 12:19:39.028: E/AndroidRuntime(519):  at java.util.Arrays$ArrayList.<init>(Arrays.java:49)
08-16 12:19:39.028: E/AndroidRuntime(519):  at java.util.Arrays.asList(Arrays.java:171)
08-16 12:19:39.028: E/AndroidRuntime(519):  at com.vsoft.TestMedia.TestMediaActivity.updateSongList(TestMediaActivity.java:40)
08-16 12:19:39.028: E/AndroidRuntime(519):  at com.vsoft.TestMedia.TestMediaActivity.onCreate(TestMediaActivity.java:34)
08-16 12:19:39.028: E/AndroidRuntime(519):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-16 12:19:39.028: E/AndroidRuntime(519):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
08-16 12:19:39.028: E/AndroidRuntime(519):  ... 11 more

谢谢,钱德拉

4

2 回答 2

2

您可以使用 MediaStore 内容提供程序来查找您的音乐:http: //developer.android.com/reference/android/provider/MediaStore.html

MediaColumns 中有一个 DATA 字段,用于保存媒体文件的数据流。

Google 有一个从 MediaStore http://developer.android.com/guide/topics/providers/content-providers.html读取图像的示例。

您的应用程序外部的几乎所有内容通常都可以使用 Content Provider 进行访问。

于 2012-08-16T07:05:25.610 回答
1

首先创建一个ContentResolver实例,检索URI外部音乐文件,并使用该实例创建一个 Cursor 实例ContentResolver来查询音乐文件:

ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);

现在您可以迭代结果:

if(musicCursor!=null && musicCursor.moveToFirst()){
  //get columns
  int titleColumn = musicCursor.getColumnIndex
    (android.provider.MediaStore.Audio.Media.TITLE);
  int idColumn = musicCursor.getColumnIndex
    (android.provider.MediaStore.Audio.Media._ID);
  int artistColumn = musicCursor.getColumnIndex
    (android.provider.MediaStore.Audio.Media.ARTIST);
  //add songs to list
  do {
    long thisId = musicCursor.getLong(idColumn);
    String thisTitle = musicCursor.getString(titleColumn);
    String thisArtist = musicCursor.getString(artistColumn);
    songList.add(new Song(thisId, thisTitle, thisArtist));
  }
  while (musicCursor.moveToNext());
}
于 2016-09-15T15:46:00.400 回答