[Solved] What’s wrong with my code, please help me [duplicate]


Firstly, your MediaPlayer instance should reside within MainActivity, not MyListener, and MyListener should not extend an activity. In fact, you should move all of your code from MyListener into MainActivity, I don’t really see a purpose for it in the snippet you’ve provided.

Secondly, You’re creating your MediaPlayer outside of the Activity Lifecycle, while still trying to pass a Context to it:

public class MainActivity extends AppCompatActivity {

    MediaPlayer musicPlayer = MediaPlayer.create(this, R.raw.sound_file);
    ...
}

The activity has no Context (this) until the Activity Lifecycle has started, the way you’ve written it above is equivalent to defining musicPlayer in a constructor:

public class MainActivity extends AppCompatActivity {

    MediaPlayer musicPlayer; 

    public MyListener() {
        musicPlayer = MediaPlayer.create(this, R.raw.sound_file);
    }
    ...
}

This will also fail as the Activity Lifecycle has not yet started. What you need to do is declare musicPlayer as a member of the class, and then create an instance in onCreate() where the Context will have been initialsed:

public class MainActivity extends AppCompatActivity {

    MediaPlayer musicPlayer; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_listener);
        musicPlayer = MediaPlayer.create(this, R.raw.sound_file);
    }
    ...
}

To address your comment, here’s an example of how it could all fit in to your MainActivity using lambdas:

public class MainActivity extends AppCompatActivity {

    int currentPosition;
    MediaPlayer musicPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        musicPlayer = MediaPlayer.create(this, R.raw.sound_file);

        Button startButton = (Button) findViewById(R.id.start);
        startButton.setOnClickListener(view -> musicPlayer.start());

        Button pauseButton = (Button) findViewById(R.id.pause);
        pauseButton.setOnClickListener(view -> musicPlayer.pause());
    }
}

4

solved What’s wrong with my code, please help me [duplicate]