【问题标题】:Android app crash while passing intent b/w activities在活动之间传递意图时Android应用程序崩溃
【发布时间】:2018-06-22 05:38:30
【问题描述】:

当我尝试传递播放歌曲的意图时,应用程序会强制关闭。我是初学者,所以找不到错误。我正在从教程中获得帮助,但现在我被困在这里。我正在尝试从移动存储中获取音乐并在新活动中播放。 我错在哪里? 此活动正在接收意图值。

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);

        Intent j = getIntent();
        Bundle b = j.getExtras();
        arrayList = (ArrayList) b.getParcelableArrayList("songlist");
        int position = b.getInt("pos", 0);

        Uri u;
        u = Uri.parse(arrayList.get(i).toString());
        mediaPlayer = MediaPlayer.create(getApplicationContext(),u);
        mediaPlayer.start();
    }

这是主要活动

public class MainActivity extends AppCompatActivity {

    private static final int MY_PERMISSION_REQUEST = 1;

    ArrayList<String> arrayList;

    ListView listView;
    ArrayAdapter<String> adapter;

    MediaPlayer mediaPlayer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (ContextCompat.checkSelfPermission(MainActivity.this,
        Manifest.permission.READ_EXTERNAL_STORAGE) !=PackageManager.PERMISSION_GRANTED){
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)){
                ActivityCompat.requestPermissions(MainActivity.this,
                        new  String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSION_REQUEST);
            }else {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSION_REQUEST);
            }
        }else {
                doStuff();
            }
    }

    public void doStuff(){
        listView = (ListView) findViewById(R.id.listView);
        arrayList = new ArrayList<>();
        getMusic();
        adapter = new ArrayAdapter<>(this,  android.R.layout.simple_list_item_1, arrayList);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                startActivity(new Intent(getApplicationContext(),Player.class).putExtra("pos",i).putExtra("songlist",arrayList));
            }
        });
    }

public void getMusic() {
        ContentResolver contentResolver = getContentResolver();
        Uri songUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Cursor songCursor = contentResolver.query(songUri, null, null, null, null);

        if (songCursor != null && songCursor.moveToFirst()){
            int songTitle = songCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
            int songArtist = songCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
            /*int songLocation = songCursor.getColumnIndex(MediaStore.Audio.Media.DATA);*/

            do {
                String currentTitle = songCursor.getString(songTitle);
                String currentArtist = songCursor.getString(songArtist);
                /*String currentLocation = songCursor.getString(songLocation);*/
                arrayList.add(currentTitle + "\n"
                        + "Artist: " + currentArtist);
            }while (songCursor.moveToNext());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case MY_PERMISSION_REQUEST: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    if (ContextCompat.checkSelfPermission(MainActivity.this,
                            Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
                        Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
                        doStuff();
                    }
                }else {
                    Toast.makeText(this, "Permission Not Granted", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }

这是 Logcat 详细信息

01-12 23:01:50.658 25516-25516/com.example.name.audioplayer D/AndroidRuntime: Shutting down VM
01-12 23:01:50.658 25516-25516/com.example.name.audioplayer E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: com.example.name.audioplayer, PID: 25516
                                                                               java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.name.audioplayer/com.example.name.audioplayer.Player}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
                                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
                                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
                                                                                   at android.app.ActivityThread.-wrap14(ActivityThread.java)
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                   at android.os.Looper.loop(Looper.java:154)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
                                                                                   at com.example.name.audioplayer.Player.onCreate(Player.java:29)
                                                                                   at android.app.Activity.performCreate(Activity.java:6956)
                                                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
                                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
                                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045) 
                                                                                   at android.app.ActivityThread.-wrap14(ActivityThread.java) 
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642) 
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                   at android.os.Looper.loop(Looper.java:154) 
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:6776) 
                                                                                   at java.lang.reflect.Method.invoke(Native Method) 
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518) 
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408) 

【问题讨论】:

  • 添加 try catch (Throwable e) 并在文本框中显示错误或使用 addb 调试器,如果您可以将 ph 连接到计算机并在调试中运行?
  • 能否提供logcat错误?
  • 我刚刚添加了 Logcat...
  • 确保您拥有READ_EXTERNAL_STORAGE 权限
  • 是的!授予权限。列表视图正在显示存储中的所有 mp3。

标签: android android-intent android-activity crash parameter-passing


【解决方案1】:

mediaPlayer.start() 周围加上一个检查null 的if 语句,并且只有在mediaPlayer 不为空时才会执行该块。在您的情况下,mediaPlayer 对象是null,可能是因为 Uri 对象u 没有有效的Uri。插入日志以检查其值,但首先插入if 块以避免崩溃。

【讨论】:

  • 我插入了 if 语句,现在播放器不再崩溃,但是歌曲没有播放。
  • 这是预期的,因为当到达 if 语句时,mediaPlayer 为空。在设置u 之后放置一条日志语句,如:Log.d("Uri Value", u.toString()); 以了解您正在获取的Uri 是什么,并检查它是否有效
  • 能否请您编辑代码。我已经分享了上面的所有代码。
  • 编辑有问题的代码会改变问题。只需在 mediaPlayer = MediaPlayer.create(getApplicationContext(),u); 行之前添加 Log.d("Uri Value", u.toString()); ,每当执行该语句时,您就会在日志中获得 Uri u 的值,您可以在其中检查和调试代码。
猜你喜欢
  • 1970-01-01
  • 2018-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多