-1

I have a Mainactivity extends fragmentActivity (not sure if relevant) and it plays a background music fine. I want the music to stop when you leave the activity. I minimized the codes below. I am getting a nullpoint exception on the onPause() lifecycle of the Activity.

public class MainActivitytest extends FragmentActivity implements
    ActionBar.TabListener{

private String[] tabs = {"Colors and Shapes", "Letters and Numbers", "CVC and Sight Words", "Adjectives", "Simple Sentences", "Reading Comprehension"};
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private int myShuffledSize;
private Context context;
public static final String PREFS_NAME = "MyPrefsFile";
public MediaPlayer player;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    Intent intent = new Intent(this, MusicService.class);
    startService(intent);

    new SetupViews().invoke();  //setup fragment views
}

public void onResume() {
    super.onResume();
    MediaPlayer player = MediaPlayer.create(MainActivitytest.this, R.raw.bgmusic3);
    player.setLooping(true);
    player.setVolume(100, 100);
    player.start();

}
public void onPause(){
    super.onPause();
    //player.stop();  //causes null pointer exception
}
Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
Mark Ligot
  • 67
  • 7
  • 1
    Like your [question from yesterday](https://stackoverflow.com/questions/41587155/starting-a-3rd-activity-setting-up-interfaces-and-listeners) which was closed, the problem is from not understanding Android Activity lifecycle. Have you read the official documentation for activities yet (suggested in closed question)? You shouldn't just expect to just copy and paste examples together from the internet without understanding the concepts behind it. Please spend some time understanding Activity lifecycles and post a [mcve], otherwise the question is off topic and will tend to be downvoted – David Rawson Jan 13 '17 at 00:47
  • @DavidRawson I have read and watched the link you shared. With what I've learned I think the prob is that fragments are attached to the life cycle of activity classes. Now if I can just ask you how to research further b/cI tried to put the player to stop at the onPause (activity and fragment) but still I keep getting a null exception error. At what life cycle (activity or fragment or both) should i put the command for the player to stop? I don't mean to be off topic, maybe I just don't know how to ask the right question. – Mark Ligot Jan 13 '17 at 14:11
  • 1
    That's great you have learned from the video. Now perhaps edit your question to include the information you mentioned. So, player is stopping at [lifecycle here e.g,. onStart()] or, I am getting [nullpointerexception] at [lifecycle here]. If you do that it makes it easier for people to quickly diagnose the problem without having to read through all the code – David Rawson Jan 13 '17 at 21:20

1 Answers1

0

After doing much more research, I accomplished what I want with service, something new I learned. Here is the code i used

public class MainActivitytest extends FragmentActivity implements
    ActionBar.TabListener {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
public final static String MUSIC_BACKGROUND = "com.example.myfirstapp.MESSAGE";

private String[] tabs = {"Colors and Shapes", "Letters and Numbers", "CVC and Sight Words", "Adjectives", "Simple Sentences", "Reading Comprehension"};
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private Context context;
public static final String PREFS_NAME = "MyPrefsFile";

private boolean mIsBound = false;
private MusicService mServ;
private ServiceConnection Scon =new ServiceConnection(){

    public void onServiceConnected(ComponentName name, IBinder
            binder) {

        mServ = ((MusicService.ServiceBinder)binder).getService();
    }

    public void onServiceDisconnected(ComponentName name) {
        mServ = null;
    }
};

void doBindService(){
    bindService(new Intent(this,MusicService.class),
            Scon,Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

void doUnbindService()
{
    if(mIsBound)
    {
        unbindService(Scon);
        mIsBound = false;
    }
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    Intent intent = new Intent(this, MusicService.class);
    startService(intent);

    new SetupViews().invoke();  //setup fragment views
}

    public void onPause(){
    super.onPause();
    Intent intent = new Intent(this, MusicService.class);
    stopService(intent);

Now my service class

package info.androidhive.tabsswipe;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

public class MusicService extends Service  implements MediaPlayer.OnErrorListener {
private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
private int length = 0;

public MusicService() {
}

public class ServiceBinder extends Binder {
    public MusicService getService() {
        return MusicService.this;
    }

}

@Override
public IBinder onBind(Intent arg0) {
    return mBinder;
}

@Override
public void onCreate() {
    super.onCreate();

    mPlayer = MediaPlayer.create(this, R.raw.bgmusic3);
    mPlayer.setOnErrorListener(this);

    if (mPlayer != null) {
        mPlayer.setLooping(true);
        mPlayer.setVolume(100, 100);
    }


    mPlayer.setOnErrorListener(new OnErrorListener() {

        public boolean onError(MediaPlayer mp, int what, int
                extra) {

            onError(mPlayer, what, extra);
            return true;
        }
    });
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    mPlayer.start();
    return START_STICKY;
}

public void pauseMusic() {
    if (mPlayer.isPlaying()) {
        mPlayer.pause();
        length = mPlayer.getCurrentPosition();

    }
}

public void resumeMusic() {
    if (mPlayer.isPlaying() == false) {
        mPlayer.seekTo(length);
        mPlayer.start();
    }
}

public void stopMusic() {
    mPlayer.stop();
    mPlayer.release();
    mPlayer = null;
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (mPlayer != null) {
        try {
            mPlayer.stop();
            mPlayer.release();
        } finally {
            mPlayer = null;
        }
    }
}

public boolean onError(MediaPlayer mp, int what, int extra) {

    Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
    if (mPlayer != null) {
        try {
            mPlayer.stop();
            mPlayer.release();
        } finally {
            mPlayer = null;
        }
    }
    return false;
}


}

Include this in the manifest

    <service android:name=".MusicService" />
    <activity
        android:name="info.androidhive.tabsswipe.MainActivitytest"
        android:label="@string/app_name" >


        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

This works even on my fragmented view. I learned a lot today. Hope this helps someone else like me.

Mark Ligot
  • 67
  • 7