目前我正在尝试创建一个媒体播放器,我试图从我创建的活动类调用updateMusic方法,并将其显示到listFragemnt类
但我一直收到这个错误,我不确定如何让它工作 我最近在活动中编写了整个应用程序并且它工作得非常好,因此我尝试将其格式化为片段,以便我可以添加一个用于滑动的viewpager,但除了这一点之外
MediaActivity类
public class MediaActivity extends ListActivity {
Uri uri = Uri.parse(Environment.getExternalStorageDirectory() + "/");
public Uri uriMusic = Uri.parse("/storage/emulated/0/MUSIC/");
public Uri uriVideo = Uri.parse("/storage/emulated/0/VIDEOS/");
private static final String SD_PATH = new String(Environment.getExternalStorageDirectory().getPath() + "/");
public static final String MUSIC_PATH = new String("/storage/emulated/0/MUSIC/");
public static final String VIDEO_PATH = new String("/storage/emulated/0/VIDEOS/");
public List<String> videos = new ArrayList<String>();
public List<String> songs = new ArrayList<String>();
private MediaPlayer mp = new MediaPlayer();
public void updateMusic() {
File home = new File(MUSIC_PATH);
if (home.listFiles(new mp3Filter()).length > 0) {
for (File file : home.listFiles(new mp3Filter())) {
songs.add(file.getName());
}
ArrayAdapter<String> songList = new ArrayAdapter<String>(this, R.layout.song_item, songs);
setListAdapter(songList);
}
}
然后这是CategorySong类,它扩展了片段以显示列表
public class CategorySongs extends ListFragment {
MediaActivity mediaActivity;
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
container.removeAllViews();
mediaActivity = new MediaActivity();
mediaActivity.updateMusic();
mediaActivity.buttons();
return inflater.inflate(R.layout.activity_media, container, false);
}
}
但我刚收到此错误
07-13 20:54:26.701 7281-7281/com.example.mason.mediaplayer E/MediaPlayer-JNI﹕ QCMediaPlayer mediaplayer NOT present 07-13 20:54:26.711 7281-7281/com.example.mason.mediaplayer E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.mason.mediaplayer, PID: 7281
java.lang.IllegalStateException: System services not available to Activities before onCreate()
at android.app.Activity.getSystemService(Activity.java:5259)
at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:153)
at com.example.mason.mediaplayer.MediaActivity.updateMusic(MediaActivity.java:287)
at com.example.mason.mediaplayer.CategorySongs.onCreateView(CategorySongs.java:28)
答案 0 :(得分:0)
这是因为Android OS首先实例化Activity,然后它进行一些额外的设置以提供该Activity的基本Context和环境信息。这些是访问LayoutInflater
等系统服务所必需的,这是ArrayAdapter
在构建期间尝试访问的内容。
您的代码包含您声明它们的同一行中成员变量的分配。这些赋值在构造时发生(它们也可能在Activity的构造函数中),这是在OS完成Activity的设置之前。您需要将这些作业移至onCreate()
或更晚。