首页 > 解决方案 > 当我添加 2 首歌曲并单击它时,音乐应用程序崩溃

问题描述

我有 2 首歌曲,我又添加了 2 首歌曲,但现在每当我点击任何歌曲时,应用程序都会崩溃并且我收到错误消息。我只在小部件的 id 后面添加了一个数字来区分它们。任何帮助是极大的赞赏 。

..................................................... .....................

播放歌曲活动

package com.example.musicstream;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.media.AudioAttributes;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.musicstream.util.AppUtil;

import java.io.IOException;

public class PlaySongActivity extends AppCompatActivity {

    // Instance variables to store the details of the song
    private String songId = "";
    private String title = "";
    private String artiste = "";
    private String fileLink = "";
    private String coverArt = "";
    private String url = "";
    private MediaPlayer player = null;
    private static final String BASE_URL = "https://p.scdn.co/mp3-preview/";
    private Button btnPlayPause = null;
    private int musicPosition = 0;
    private SongCollection songCollection = new SongCollection();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_song);
        btnPlayPause = findViewById(R.id.btnPlayPause);
        retrieveData();
        displaySong(title, artiste, coverArt);
    }

    private void retrieveData() {
        // Get the Intent that started this activity
        Intent intent = getIntent();

        // Extract the Song data from the intent object using the
        // specific keys and put these values in the instance variables
        songId = intent.getStringExtra("id");
        title = intent.getStringExtra("title");
        artiste = intent.getStringExtra("artiste");
        fileLink = intent.getStringExtra("fileLink");
        coverArt = intent.getStringExtra("coverArt");

        //Prepare the URL link to play the song
        url = BASE_URL + fileLink;

    }

    private void displaySong(String title, String artiste, String coverArt) {
        // Retrieve the layout's song title TextView and set the string as its text
        TextView txtTitle = findViewById(R.id.txtSongTitle);
        txtTitle.setText(title);

        // Retrieve the layout's artiste TextView and set the string as its text
        TextView txtArtiste = findViewById(R.id.txtArtiste);
        txtArtiste.setText(artiste);

        // Get the id of the cover art from the drawable folder
        int imageId = AppUtil.getImageIdFromDrawable(this, coverArt);

        //Retrieve the layout's cover art ImageView
        ImageView ivCoverArt = findViewById(R.id.imgCoverArt);
        // Set the selected cover art image to the ImageView in the layout
        ivCoverArt.setImageResource(imageId);

    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void preparePlayer() {
        //1. Create a new media player
        player = new MediaPlayer();
        //The try-catch code is required by the prepare() method
        //It is to catch and handle any error that may occur.
        //The code shown simply print the error to the console
        //Using the printStackTrace()method.
        try {
            //2. Set the content type of the Audio attributes to music
            player.setAudioAttributes(new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .build());
            //3. Set the source of the music
            player.setDataSource(url);
            //4. Prepare the player for playback
            player.prepare(); //might take long !(for buffering, etc)

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void playOrPauseMusic(View view) {
        //1. If there is no MediaPlayer object , call
        // the preparePlayer method to create it.
        if (player == null) {
            preparePlayer();
        }
        //2. If player is NOT playing,
        if (!player.isPlaying()) {
            // If the position of the music is greater than 0
            if (musicPosition > 0) {
                //Get the player to go to the music position
                player.seekTo(musicPosition);
            }
            // Start the player
            player.start();

            //Set the text of the play button to PAUSE
            btnPlayPause.setText("PAUSE");

            //Set the top bar title to the app to the music that is
            //currently playing
            setTitle("Now playing: " + title + " - " + artiste);

            //When the music ends , stop the player
            gracefullyStopsWhenMusicEnds();
        }
        else{
            //pause the music
            pauseMusic();
        }

    }

    private void pauseMusic (){
        //1. Pause the player.
        player.pause();
        //2. Get the current position of the music that is playing
        musicPosition = player.getCurrentPosition();

        //3. Set the text of the play view to PLAY.
        btnPlayPause.setText("PLAY");
    }

    private void gracefullyStopsWhenMusicEnds () {
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                //Add code here if you want something to happen to happen when the music ends
                stopActivities();
            }
        });
    }
    private void stopActivities (){
        if (player != null) {
            btnPlayPause.setText("PLAY");
            musicPosition = 0;
            setTitle("");
            player.stop();
            player.release();
            player = null;
        }


    }
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void playNext (View view){
        Song nextSong = songCollection.getNextSong(songId);
        if (nextSong != null) {
            songId = nextSong.getId();
            title = nextSong.getTitle();
            artiste = nextSong.getArtiste();
            fileLink = nextSong.getFileLink();
            coverArt = nextSong.getCoverArt();
            url = BASE_URL + fileLink;
            displaySong(title,artiste,coverArt);
            stopActivities();
            playOrPauseMusic(view);



        }

    }
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void playPrev (View view ){
        Song prevSong = songCollection.getPrevSong(songId);
        if ( prevSong != null) {
            songId = prevSong.getId();
            title = prevSong.getTitle();
            artiste = prevSong.getArtiste();
            fileLink = prevSong.getFileLink();
            coverArt = prevSong.getCoverArt();
            url = BASE_URL + fileLink;
            displaySong(title, artiste, coverArt);
            stopActivities();
        }   playOrPauseMusic(view);
    }
    public void playRepeat (View view ){
        Song repeatSong = songCollection.getCurrentSong(songId);
        if ( repeatSong != null) {
            songId = repeatSong.getId();
            title = repeatSong.getTitle();
            artiste = repeatSong.getArtiste();
            fileLink = repeatSong.getFileLink();
            coverArt = repeatSong.getCoverArt();
            url = BASE_URL + fileLink;
            displaySong(title, artiste, coverArt);
            stopActivities();
        }   playOrPauseMusic(view);
    }


}

活动主xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <ImageButton
        android:id="@+id/S1001"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginStart="64dp"
        android:layout_marginTop="32dp"
        android:onClick="handleSelection"
        android:scaleType="centerCrop"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/michael_buble_collection" />

    <TextView
        android:id="@+id/txtTitle1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="200dp"
        android:layout_marginTop="32dp"
        android:text="The Way You Look Tonight"
        app:layout_constraintStart_toEndOf="@+id/S1001"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/txtArtiste1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="200dp"
        android:layout_marginTop="102dp"
        android:text="Michael Buble"
        app:layout_constraintStart_toEndOf="@+id/S1001"
        app:layout_constraintTop_toBottomOf="@+id/txtTitle1" />

    <ImageButton
        android:id="@+id/S1002"
        android:layout_width="101dp"
        android:layout_height="100dp"
        android:layout_marginStart="64dp"
        android:layout_marginTop="200dp"
        android:onClick="handleSelection"
        android:scaleType="centerCrop"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/S1001"
        app:srcCompat="@drawable/billie_jean" />

    <TextView
        android:id="@+id/txtTitle2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="200dp"
        android:layout_marginTop="200dp"
        android:text="Billie Jean"
        app:layout_constraintStart_toEndOf="@+id/S1002"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/txtArtiste2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="200dp"
        android:layout_marginTop="270dp"
        android:text="Michael Jackson"
        app:layout_constraintStart_toEndOf="@+id/S1002"
        app:layout_constraintTop_toBottomOf="@+id/txtTitle2" />

    <ImageView
        android:id="@+id/add1"
        android:layout_width="62dp"
        android:layout_height="65dp"
        android:layout_marginStart="360dp"
        android:layout_marginTop="50dp"
        android:contentDescription="S1001"
        android:onClick="addToFavourite"
        app:srcCompat="@android:drawable/ic_input_add" />

    <ImageView
        android:id="@+id/add2"
        android:layout_width="62dp"
        android:layout_height="65dp"
        android:layout_marginStart="360dp"
        android:layout_marginTop="200dp"
        android:contentDescription="S1002"
        android:onClick="addToFavourite"
        app:srcCompat="@android:drawable/ic_input_add" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="160dp"
        android:onClick="goToFavouriteActivity"
        android:layout_marginTop="650dp"
        android:text="View Playlist" />

    <ImageView
        android:id="@+id/S1003"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginStart="64dp"
        android:layout_marginTop="370dp"
        android:onClick="handleSelection"
        android:scaleType="centerCrop"
        app:srcCompat="@drawable/michael_buble_collection" />

    <TextView
        android:id="@+id/txtTitle3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="200dp"
        android:layout_marginTop="370dp"
        android:text="Feeling Good" />

    <TextView
        android:id="@+id/txtArtiste3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="200dp"
        android:layout_marginTop="440dp"
        android:text="Michael Buble" />

    <ImageView
        android:id="@+id/add3"
        android:layout_width="62dp"
        android:layout_height="65dp"
        android:layout_marginStart="360dp"
        android:layout_marginTop="380dp"
        android:onClick="addToFavourite"
        app:srcCompat="@android:drawable/ic_input_add" />

    <ImageView
        android:id="@+id/S1004"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginStart="64dp"
        android:layout_marginTop="540dp"
        android:onClick="handleSelection"
        android:scaleType="centerCrop"
        app:srcCompat="@drawable/michael_buble_collection" />

    <TextView
        android:id="@+id/txtTitle4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="200dp"
        android:layout_marginTop="540dp"
        android:text="Come Fly With Me" />

    <TextView
        android:id="@+id/txtArtiste4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="200dp"
        android:layout_marginTop="600dp"
        android:text="Michael Buble" />


</FrameLayout>

错误

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.musicstream, PID: 21804
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.musicstream/com.example.musicstream.PlaySongActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.musicstream.PlaySongActivity.displaySong(PlaySongActivity.java:69)
        at com.example.musicstream.PlaySongActivity.onCreate(PlaySongActivity.java:42)
        at android.app.Activity.performCreate(Activity.java:6975)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
        at android.os.Handler.dispatchMessage(Handler.java:105) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6541) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

标签: javaandroid

解决方案


这里..

TextView txtTitle = findViewById(R.id.txtSongTitle);// id = txtSongTitle did not found in your xml 
TextView txtArtiste = findViewById(R.id.txtArtiste);// id = txtArtiste did not found in your xml 

正因为如此,txtTitle并且txtArtiste是 NULL 并且您试图在 NULL 上调用方法

传递布局中提到的正确 ID

内部displaySong方法通过正确的 id 获取 TextView:

TextView txtTitle = findViewById(R.id.txtTitle3);
        txtTitle.setText(title);

        // Retrieve the layout's artiste TextView and set the string as its text
        TextView txtArtiste = findViewById(R.id.txtArtiste3);
        txtArtiste.setText(artiste);

推荐阅读