传递意图黑白活动时Android应用程序崩溃

时间:2018-01-12 17:56:13

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

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

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) 

1 个答案:

答案 0 :(得分:0)

使用检查mediaPlayer.start()的if语句环绕null,并且仅当mediaPlayer不为空时才执行该块。在您的情况下,mediaPlayer对象可能是null,因为Uri对象u没有有效的Uri。插入日志以检查其值,但首先插入if块以避免崩溃。