-1

I have 2 songs , and i added 2 more but now whenever i clicked on any of the songs , the app will crash and i received an error.I only added a number behind the ids of the widgets to differentiate them. Any help is greatly appreciated .

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

PLAY SONG ACTIVITY

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);
    }


}

activity main 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>

ERROR

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) 
Markus Kauppinen
  • 2,756
  • 4
  • 16
  • 28
Synconix
  • 11
  • 4

2 Answers2

0

Here..

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 

Because of that txtTitle and txtArtiste are NULL and you are trying to call method on NULL

Pass correct ids as mentioned in your layout

Inside displaySong method get TextView by correct ids:

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);
chand mohd
  • 1,689
  • 1
  • 7
  • 20
0

Well, you added an id, so now in your layout, you have txtArtiste1, txtArtiste2, txtArtiste3 and txtArtiste4. Thus, findViewById(R.id.txtSongTitle) return null because txtSongTitle is undefined

benjiii
  • 355
  • 2
  • 8
  • so for example , i will need to change TextView txtTitle = findViewById(R.id.txtSongTitle); to TextView txtTitle = findViewById(R.id.txtTitle1); ?? – Synconix Aug 13 '20 at 13:01