当前位置: 首页 > 知识库问答 >
问题:

无法从sd卡启动歌曲

徐昊焜
2023-03-14

我的歌曲适配器:

public class songAdapter extends RecyclerView.Adapter<songAdapter.ViewHolder> {


    ArrayList<songInfo> songs;
    Context context;
     OnitemClickListener onitemClickListener;

    public songAdapter(ArrayList<songInfo> songs, Context context) {
        this.songs = songs;
        this.context = context;
    }
    public interface OnitemClickListener{
        void onItemclick(ViewHolder holder, View v, songInfo obj, int position);
    }
    public void setOnitemClickListener(OnitemClickListener onitemClickListener)
    {
        this.onitemClickListener=onitemClickListener;
    }



    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View mView= LayoutInflater.from(context).inflate(R.layout.raw_songs,parent,false);
        return new ViewHolder(mView);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        final songInfo song=songs.get(position);
        holder.songName.setText(song.songName);
        holder.artistName.setText(song.artistName);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              if(onitemClickListener!=null)
              {
                  onitemClickListener.onItemclick(holder,view,song,position);
              }
        }
        });

    }

    @Override
    public int getItemCount() {
        return songs.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView songName,artistName;
        public ViewHolder(View itemView) {
            super(itemView);
            songName=(TextView)itemView.findViewById(R.id.songname);
            artistName=(TextView)itemView.findViewById(R.id.artistName);

        }
    }
}

this is my mainactivity

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    private  ArrayList<songInfo> songs=new ArrayList<songInfo>();
    songAdapter songAdapter;
    MediaPlayer mediaPlayer;
    SeekBar seekBar;
    Cursor cursor;
    private Handler myHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView=(RecyclerView)findViewById(R.id.recyclerView);
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        songAdapter=new songAdapter(songs, this);
        recyclerView.setAdapter(songAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
                linearLayoutManager.getOrientation());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addItemDecoration(dividerItemDecoration);
        songAdapter.setOnitemClickListener(new songAdapter.OnitemClickListener() {

            @Override
            public void onItemclick(songAdapter.ViewHolder holder, View v, songInfo obj, int position) {

                mediaPlayer.start();
                    System.gc();
                    int songPath = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
                    cursor.moveToPosition(position);
                    final String filename = cursor.getString(songPath);




                    if(mediaPlayer.isPlaying()){

                        mediaPlayer.reset();
                        mediaPlayer.start();


                    }else {

                        Runnable runnable = new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    mediaPlayer = new MediaPlayer();
                                    mediaPlayer.setDataSource(filename);
                                    mediaPlayer.prepareAsync();
                                    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                                        @Override
                                        public void onPrepared(MediaPlayer mp) {
                                            mp.start();
                                            seekBar.setProgress(0);
                                            seekBar.setMax(mediaPlayer.getDuration());
                                            Log.d("Prog", "run: " + mediaPlayer.getDuration());
                                        }
                                    });
                                    // b.setText("Stop");



                                }catch (Exception e){}
                            }

                        };
                        myHandler.postDelayed(runnable,100);

                    }

                }

        });
        checkUserPermission();

        Thread t = new runThread();
        t.start();
    }

    public class runThread extends Thread {


        @Override
        public void run() {
            while (true) {

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Log.d("Runwa", "run: " + 1);
                if (mediaPlayer != null) {
                    seekBar.post(new Runnable() {
                        @Override
                        public void run() {
                            seekBar.setProgress(mediaPlayer.getCurrentPosition());
                        }
                    });

                    Log.d("Runwa", "run: " + mediaPlayer.getCurrentPosition());
                }
            }
        }

    }

    private void checkUserPermission(){
        if(Build.VERSION.SDK_INT>=23){
            if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED){
                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},123);
                return;
            }
        }
        loadSongs();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 123:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    loadSongs();
                }else{
                    Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
                    checkUserPermission();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        }

    }

    private void loadSongs(){
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String selection = MediaStore.Audio.Media.IS_MUSIC+"!=0";
         cursor = getContentResolver().query(uri,null,selection,null,null);
        if(cursor != null){
            if(cursor.moveToFirst()){
                do{
                    String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                    String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                    int songPath = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);

                    songInfo s = new songInfo(name,artist,songPath);
                    songs.add(s);

                }while (cursor.moveToNext());
            }

       //     cursor.close();
            songAdapter = new songAdapter(songs, MainActivity.this);

        }
    }

    public void onDestroy() {
        super.onDestroy();
        cursor.close();

        }
    }

我从sd卡上取了这首歌,可以在屏幕上看到,但当我尝试播放这些歌曲时,我的应用程序崩溃了,出现了以下错误。尝试调用虚拟方法“void android”。媒体MediaPlayer。在空对象引用上启动()。

我不知道该怎么办请帮忙。

这是我的日志

过程:com。实例壁画。musicmania,PID:26119爪哇。lang.NullPointerException:尝试调用虚拟方法“void android”。媒体MediaPlayer。在com的空对象引用上启动()。实例壁画。音乐狂热。主要活动1美元。com上的onItemclick(MainActivity.java:54)。实例壁画。音乐狂热。宋体适配器1美元。onClick(songAdapter.java:54)**

共有1个答案

桂宏旷
2023-03-14

问题是您试图访问MediaPlayer的空实例,

尝试调用虚拟方法“void android”。媒体MediaPlayer。在空对象引用上启动()。

因此,在执行mediaPlayer.start();方法内部onClick()之前,您需要初始化MediaPlayer实例:

MediaPlayer mediaPlayer = new MediaPlayer();

例如:

private  MediaPlayer mediaPlayer; //* Create variable type MediaPlayer .

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ...
        ...
        mediaPlayer = new MediaPlayer();  //* Initialize MediaPlayer!
        ...
        ...
        songAdapter.setOnitemClickListener(new songAdapter.OnitemClickListener() {

            @Override
            public void onItemclick(songAdapter.ViewHolder holder, View v, songInfo obj, int position) {

                mediaPlayer.start(); //*Now you can use the MediaPlayer instance.
        ...
        ...
 类似资料:
  • 我有一个应用程序使用外部存储来存储照片。根据需要,在其清单中请求以下权限 并使用以下方法检索所需的目录 在我的一部测试手机(Android one)升级到6之后,它在尝试创建必需的目录“/sdcard/pictures/myapp-yy-mm”时返回了一个错误。 sd卡配置为“便携式存储”。我已经格式化了sd卡。我已经把它换掉了。我重新启动了。都是徒劳。 此外,内置的android截图功能(通过电

  • 问题内容: 我看到很多关于写入SD卡的帖子,但是我相信我的问题有所不同。在建立AVD的过程中,我无法创建SD卡。 我最初尝试使用Android SDK和AVD Manager来执行此操作,选择 名称 :my_avd 目标 :Android 2.2-API级别8 SD卡 :大小:1024 MiB 皮肤 :内置:默认(HVGA) 硬件 :属性:抽象的LCD密度,值:160 这会弹出一个窗口,并显示以下

  • SD卡设备的使用 SD卡设备的使用 源码/* * Copyright (c) 2006-2018, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2018-09-25 misonyo first edition. *//* * 程序清

  • 问题内容: 我尝试使用此代码下载图像并将其保存在以下行中: 我在emulator.my应用程序上尝试了此操作,但出现异常,没有权限保存到此路径: 我也添加了这一行: 这是代码: 问题答案:

  • 问题内容: 我正在尝试从设备sd卡加载png图像作为可绘制图像。我使用以下功能,但不起作用: 图像路径为:mnt / sdcard / MyFolder / image.png 当我尝试调用该方法时,应用程序崩溃了,我该如何加载位于sdcard中的png图像并将其转换为Drawable对象? 问题答案: 实际上,直接在文件路径中有一个BitmapDrawable构造函数。您正在使用的方法已被描述。

  • Windows 10,JDK 1.8或15,eclipse 2021-06,maven project HelloWorld。我从eclipse marketplace安装了payara工具。启动payara服务器给出错误消息: “在Felix平台上启动Payara服务器错误:解析系统捆绑语句时出错。org.osgi.framework.BundleException:导出的软件包名称不能是零长度