java.lang.Nullpointerexception: Attempt to invoke virtual method 'void android.media.Mediaplayer.start()' on a null Object Reference

Asked

Viewed 688 times

0

I am learning Java and know basically what Nullpointerexception means. But I would like to understand why this occurs.

This is the Activity code:

package com.example.android.miwok;

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;

public class FamilyActivity extends AppCompatActivity {

    MediaPlayer mediaPlayer;

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

        //Instantiate an ArrayList
        final ArrayList<Words> famillyArray = new ArrayList<Words>( );

        //Supply Array
        famillyArray.add(new Words("father", "әpә", R.drawable.family_father, R.raw.family_father));
        famillyArray.add(new Words("mother", "әṭa", R.drawable.family_mother, R.raw.family_mother));
        famillyArray.add(new Words("son", "angsi", R.drawable.family_son, R.raw.family_son));
        famillyArray.add(new Words("daughter", "tune", R.drawable.family_daughter, R.raw.family_daughter));
        famillyArray.add(new Words("older brother", "taachi", R.drawable.family_older_brother, R.raw.family_older_brother));
        famillyArray.add(new Words("younger brother", "chalitti", R.drawable.family_younger_brother, R.raw.family_younger_brother));
        famillyArray.add(new Words("older sister", "teṭe", R.drawable.family_older_sister, R.raw.family_older_sister));
        famillyArray.add(new Words("younger sister", "kolliti", R.drawable.family_younger_sister, R.raw.family_younger_sister));
        famillyArray.add(new Words("grandmother ", "ama", R.drawable.family_grandmother, R.raw.family_grandmother));
        famillyArray.add(new Words("grandfather", "paapa", R.drawable.family_grandfather, R.raw.family_grandfather));

        final WordsAdapter famillyAdapter = new WordsAdapter(this, famillyArray, R.color.category_family);
        ListView listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(famillyAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener( ) {
            @Override
            public void onItemClick( AdapterView<?> adapterView, View view, int position, long l ) {
                Words getSong = famillyArray.get(position);
                mediaPlayer = MediaPlayer.create(FamilyActivity.this, getSong.getSongResource());
                releaseMediaPlayer();
                mediaPlayer.start();
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener( ) {
                    @Override
                    public void onCompletion( MediaPlayer mediaPlayer ) {
                        releaseMediaPlayer();
                    }
                });
            }
        });
    }
    private void releaseMediaPlayer(){
        if (mediaPlayer != null){
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}

Note this line of code above, is in the second @Override:

mediaPlayer = MediaPlayer.create(FamilyActivity.this, getSong.getSongResource());

The error is solved by simply putting MediaPlayer of the variable mediaPlayer being like this MediaPlayer mediaPlayer = Media...

But what I don’t understand is: If I already instated the variable as an object of the Mediaplayer class at the beginning of Activity, why do I have to declare it again? If you look closely, in the first line after public class FamillyActivy extends AppCompatActivity { she is already declared.

Thanks for any help that makes me understand the logic of this mistake.

1 answer

4


The error is not in declaring the variable mediaPlayer inside or outside the method onItemClick.

The error is in the method releaseMediaPlayer. Note that this method is called after you instantiate the object MediaPlayer in the global variable of the same name.

mediaPlayer = MediaPlayer.create(FamilyActivity.this, getSong.getSongResource());
releaseMediaPlayer();

Now note that the method releaseMediaPlayer is simply assigning to the global variable mediaPlayer, the value of null.

This method is removing the instance you "just made" before accessing it.

private void releaseMediaPlayer(){
    if (mediaPlayer != null){
        mediaPlayer.release();
        mediaPlayer = null; /* O erro é devido essa linha tornar a variável `mediaPlayer` nula depois de ter sido instanciada */
    }
}

When you set the variable mediaPlayer within the method onItemClick, you stop using the global variable and switch to a local variable.

And since a local variable cannot be changed or accessed outside the method where it was defined, the method releaseMediaPlayer can’t make it null (sending the error NullPointerException).

Despite the error is in mediaPlayer.start();, he is only caused because the variable is being defined as null in the method already mentioned

  • @Marcusdacorréggio but the error is due to the line making it null after it has been instance. I edited my reply to clarify the content I wrote just below the code.

  • @Carlosheuberger yes will generate, but as I explained in my reply. The mistake is happening justly by it instantiates the Mediaplayer object, makes it null in function releaseMediaPlayer and then try to use the method start in a variable that was instance and then set to null again.

  • Vadeir Voce is right. Thank you for explaining the problem clearly. It was very useful for me. I was programming on time and I was already very tired, I let it go unnoticed. But once, thanks for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.