strange java.lang.NullPointerException at onPostExecute - java

Who can help me with this strange error?
I marked the line when I get the error.
Thanks
/************************************************
* setItemsAsReadTask
************************************************/
private class SetItemsAsReadTask extends AsyncTask<ArrayList<FeedItem>, Void, Void> {
#Override
protected void onPreExecute() {
//AGGIORNO LISTVIEW SUBSCRIPTIONS
}
#Override
protected Void doInBackground(ArrayList<FeedItem> ... articoli) {
if(this.isCancelled()==false){
if(articoli.length!=0){
ArrayList<FeedItem> segnaComeLetti = articoli[0];
reader.setMultipleNewsAsRead(segnaComeLetti);
}
}
return null;
}
#Override
protected void onPostExecute(Void v) {
//TODO TRUE O FALSE
if(this.isCancelled()==false){
Log.d(TAG, "chiedo aggiornamento updateUI");
mCallbacks.onSubscriptionsUpdated();
}<---- that's the line of the error
}
}
**UPDATE
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (Callbacks)activity;
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}

Your mCallbacks variable is probably null. Use defensive programming and check for null before calling the method. Also, instead of checking if a boolean value is false, just use the not ! logical operator.
#Override
protected void onPostExecute(Void v) {
if (!this.isCancelled()){
Log.d(TAG, "chiedo aggiornamento updateUI");
if (mCallbacks != null) {
mCallbacks.onSubscriptionsUpdated();
}
}
}

Related

NavigationView with useroffroute MapBox Android

I'm actually trying to use the useroffroute function but it's not working, I saw this other post and it said to NavigationView, only I don't know how to do it exactly. I am currently using this code to detect if the user has left the route, but he is not calling the useroffroute function. What I'm trying to do is that when the user leaves the route he fires a Toast for the user, but unfortunately I was not successful.
public class mapbox extends AppCompatActivity{
private MapView mapView;
Button button;
private static final String TAG = "resultados";
private MapboxNavigation navigation;
private boolean running;
private NavigationMapboxMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.mapbox_access_token));
setContentView(R.layout.activity_mapbox);
button = findViewById(R.id.button);
MapboxNavigationOptions options = MapboxNavigationOptions.builder().isDebugLoggingEnabled(true).build();
navigation = new MapboxNavigation(getApplicationContext(), getString(R.string.mapbox_access_token), options);
/*
navigation.addOffRouteListener(new OffRouteListener() {
#Override
public void userOffRoute(Location location) {
Toast.makeText(getApplicationContext(), "Off route detected.........", Toast.LENGTH_SHORT).show();
// Make sure you call for a new DirectionsRoute object
// and end by calling MapboxNavigation#startNavigation on a successful
}
});
*/
/*
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
// Map is set up and the style has loaded. Now you can add data or make other map adjustments
}
});
}
});
*/
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// From Mapbox to The White House
Point origin = Point.fromLngLat(-38.62882018, -3.78666528);
Point destination = Point.fromLngLat(-38.56038094, -3.7337361F);
NavigationRoute.builder(mapbox.this)
.accessToken(getString(R.string.mapbox_access_token))
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
Log.i(TAG, response+"");
// Route fetched from NavigationRoute
DirectionsRoute route = response.body().routes().get(0);
// Create a NavigationLauncherOptions object to package everything together
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(route)
.shouldSimulateRoute(false)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(mapbox.this, options);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
//mapView.onStart();
}
#Override
protected void onResume() {
super.onResume();
//mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
//mapView.onPause();
}
#Override
protected void onStop() {
super.onStop();
//mapView.onStop();
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState, #NonNull PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
//mapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
//mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
//mapView.onDestroy();
}
}
After many hours looking for a solution, I finally found one. You have to use NavigationViewer to obtain the parameters that the application passes, so you can listen if the user leaves the route. Here's an example:
public class last extends AppCompatActivity implements OnNavigationReadyCallback,
NavigationListener, RouteListener, ProgressChangeListener {
private NavigationView navigationView;
private boolean dropoffDialogShown;
private Location lastKnownLocation;
private List<Point> points = new ArrayList<>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
Mapbox.getInstance(this, getString(R.string.mapbox_access_token));
setTheme(R.style.Theme_AppCompat_NoActionBar);
super.onCreate(savedInstanceState);
points.add(Point.fromLngLat(-38.62882018, -3.78666528));
points.add(Point.fromLngLat(-38.56038094, -3.7337361));
setContentView(R.layout.activity_last);
navigationView = findViewById(R.id.navigationView);
navigationView.onCreate(savedInstanceState);
navigationView.initialize(this);
}
#Override
public void onStart() {
super.onStart();
navigationView.onStart();
}
#Override
public void onResume() {
super.onResume();
navigationView.onResume();
}
#Override
public void onLowMemory() {
super.onLowMemory();
navigationView.onLowMemory();
}
#Override
public void onBackPressed() {
// If the navigation view didn't need to do anything, call super
if (!navigationView.onBackPressed()) {
super.onBackPressed();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
navigationView.onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
navigationView.onRestoreInstanceState(savedInstanceState);
}
#Override
public void onPause() {
super.onPause();
navigationView.onPause();
}
#Override
public void onStop() {
super.onStop();
navigationView.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
navigationView.onDestroy();
}
#Override
public void onNavigationReady(boolean isRunning) {
fetchRoute(points.remove(0), points.remove(0));
}
#Override
public void onCancelNavigation() {
// Navigation canceled, finish the activity
finish();
}
#Override
public void onNavigationFinished() {
// Intentionally empty
}
#Override
public void onNavigationRunning() {
// Intentionally empty
}
#Override
public boolean allowRerouteFrom(Point offRoutePoint) {
return true;
}
#Override
public void onOffRoute(Point offRoutePoint) {
Toast.makeText(this, "Off route", Toast.LENGTH_SHORT).show();
}
#Override
public void onRerouteAlong(DirectionsRoute directionsRoute) {
}
#Override
public void onFailedReroute(String errorMessage) {
}
#Override
public void onArrival() {
if (!dropoffDialogShown && !points.isEmpty()) {
showDropoffDialog();
dropoffDialogShown = true; // Accounts for multiple arrival events
Toast.makeText(this, "You have arrived!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onProgressChange(Location location, RouteProgress routeProgress) {
lastKnownLocation = location;
}
private void startNavigation(DirectionsRoute directionsRoute) {
NavigationViewOptions navigationViewOptions = setupOptions(directionsRoute);
navigationView.startNavigation(navigationViewOptions);
}
private void showDropoffDialog() {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setMessage(getString(R.string.dropoff_dialog_text));
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.dropoff_dialog_positive_text),
(dialogInterface, in) -> fetchRoute(getLastKnownLocation(), points.remove(0)));
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.dropoff_dialog_negative_text),
(dialogInterface, in) -> {
// Do nothing
});
alertDialog.show();
}
private void fetchRoute(Point origin, Point destination) {
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.alternatives(true)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
DirectionsResponse directionsResponse = response.body();
if (directionsResponse != null && !directionsResponse.routes().isEmpty()) {
startNavigation(directionsResponse.routes().get(0));
}
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
}
});
}
private NavigationViewOptions setupOptions(DirectionsRoute directionsRoute) {
dropoffDialogShown = false;
NavigationViewOptions.Builder options = NavigationViewOptions.builder();
options.directionsRoute(directionsRoute)
.navigationListener(this)
.progressChangeListener(this)
.routeListener(this)
.shouldSimulateRoute(false);
return options.build();
}
private Point getLastKnownLocation() {
return Point.fromLngLat(lastKnownLocation.getLongitude(), lastKnownLocation.getLatitude());
}
}
XML File:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.mapbox.services.android.navigation.ui.v5.NavigationView
android:id="#+id/navigationView"
android:layout_width="0dp"
android:layout_height="0dp"
app:navigationLightTheme="#style/NavigationViewLight"
app:navigationDarkTheme="#style/NavigationViewDark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
When I start navigation with multiple waypoints, the navigation stops after reaching first waypoint.
Please suggest changes.`
try{
NavigationRoute.Builder builder = NavigationRoute.builder(this)
.accessToken("pk." + getString(R.string.gh_key))
.baseUrl(getString(R.string.base_url))
.user("gh")
.alternatives(true);
Location lastKnownLocation = new Location(LocationManager.GPS_PROVIDER);
lastKnownLocation.setLatitude(Double.parseDouble(SharePref.getInstance(MapBoxNavActivity.this).getJavaRXPref(getString(R.string.latitude))));
lastKnownLocation.setLongitude(Double.parseDouble(SharePref.getInstance(MapBoxNavActivity.this).getJavaRXPref(getString(R.string.longitude))));
Point location = Point.fromLngLat(lastKnownLocation.getLongitude(), lastKnownLocation.getLatitude());
if (lastKnownLocation.hasBearing()){
// 90 seems to be the default tolerance of the SDK
builder.origin(location, (double) lastKnownLocation.getBearing(), 90.0);
}
else{
builder.origin(location);
}
try {
if(waypoints.size()>0){
for (int i = 0; i < waypoints.size(); i++) {
Point p = waypoints.get(i);
if (i < waypoints.size() - 1) {
try {
builder.addWaypoint(p);
}catch (Exception e){
e.printStackTrace();
}
} else {
builder.destination(p);
}
}
}
}catch (Exception se){
se.printStackTrace();
}
builder.build().getRoute(new SimplifiedCallback() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
if (validRouteResponse(response)) {
route = response.body().routes().get(0);
try {
MapboxNavigationOptions.Builder navigationOptions = MapboxNavigationOptions.builder();
NavigationViewOptions.Builder options = NavigationViewOptions.builder();
options.navigationListener(MapBoxNavActivity.this);
options.directionsRoute(route);
options.shouldSimulateRoute(false);
options.directionsProfile(DirectionsCriteria.PROFILE_DRIVING_TRAFFIC);
navigationOptions.enableOffRouteDetection(true);
navigationOptions.snapToRoute(true);
options.navigationOptions(navigationOptions.build());
navigationView.startNavigation(options.build());
}catch (Exception e){
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
super.onFailure(call, throwable);
Log.i("Fetch route error",throwable.getMessage());
}
});
}
}
catch ( Exception se){
se.printStackTrace();
}
}
`

onPreExexute method is not called

I'm trying to display a Toast when I call the AsyncTask class with new saveWithStickers(BaseActivity.this).execute(); to notify the user that the save process being started, when I run the code below the onPreExecute() method for some logical reason is not called so the Toast does not appear as well,is runOnUiThread the reason for this behavior?
#SuppressLint("StaticFieldLeak")
public class saveWithStickers extends AsyncTask<Void, File, File> {
File fileSaved;
Context mContext;
saveWithStickers(Context context) {
mContext = context;
}
#Override
protected File doInBackground(Void... voids) {
fileSaved = FileUtil.getNewFile(BaseActivity.this, "VAPOGRAM");
if (fileSaved != null)
runOnUiThread(() -> {
stickerView.save(fileSaved, true);
});
return fileSaved;
}
#SuppressLint("SetTextI18n")
#Override
protected void onPreExecute() {
super.onPreExecute();
content.setVisibility(View.GONE);
Toast.makeText(mContext, "saving ...", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(File file) {
super.onPostExecute(file);
}
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckPermissionUtil checkPermissionUtil = new CheckPermissionUtil(BaseActivity.this);
if (Build.VERSION.SDK_INT >= 23) {
if (checkPermissionUtil.checkPermission(1812)) {
new saveWithStickers(BaseActivity.this).execute();
} else
checkPermissionUtil.requestPermission(1812);
} else {
new saveWithStickers(BaseActivity.this).execute();
}
}
});
Replace your code with this
#SuppressLint("StaticFieldLeak")
public class saveWithStickers extends AsyncTask<Void, File, File> {
File fileSaved;
Context mContext;
saveWithStickers(Context context) {
mContext = context;
}
#Override
protected File doInBackground(Void... voids) {
fileSaved = FileUtil.getNewFile(BaseActivity.this, "PHOTO EDITOR");
if (fileSaved != null)
runOnUiThread(() -> stickerView.save(fileSaved, true));
return fileSaved;
}
#SuppressLint("SetTextI18n")
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(mContext, "Saving ...", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(File file) {
super.onPostExecute(file);
}
}
To access to the context you need to pass it or use WeakRerefence to your parent activity

Android Beacon - Issue with bind/unbind(this)

I'm trying to create my own "BeaconManager" to develop different actions more easily.
So I've created a new class and I've implement "BeaconConsumer" and its functions :
public class MybeaconManager implements BeaconConsumer{
private BeaconManager beaconManager;
private final String TAG = "MybeaconManager";
private boolean mEnterArea = false;
private boolean mAlreadyArea = false;
public MybeaconManager(Context ctx){
beaconManager = BeaconManager.getInstanceForApplication(ctx);
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
beaconManager.bind(this);
}
public void bindBeacon(BeaconConsumer consumer){
beaconManager.bind(consumer);
}
public void unBindBeacon(BeaconConsumer consumer){
beaconManager.unbind(consumer);
}
public boolean isEnterInArea() {
return mEnterArea;
}
public boolean isAlreadyInArea() {
return mAlreadyArea;
}
public void sendNotification(String Notif) {
}
#Override
public void onBeaconServiceConnect() {
beaconManager.addMonitorNotifier(new MonitorNotifier() {
#Override
public void didEnterRegion(Region region) {
mEnterArea = true;
}
#Override
public void didExitRegion(Region region) {
mEnterArea = false;
}
#Override
public void didDetermineStateForRegion(int i, Region region) {
}
});
}
Next to this, I have my MainActivity :
public class MainActivity extends Activity {
MybeaconManager mybeaconManager;
BeaconManager beaconManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mybeaconManager = new MybeaconManager(this);
if (mybeaconManager.isEnterInArea()){
Log.i("BeaconTest", "I'm detecting a Beacon");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mybeaconManager.unBindBeacon((BeaconConsumer) this);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
}
So as you can see, I'm trying to use the functions didEnterRegion/didExitRegion more easily in a way that I only have to use on line in my MainActivity code.
The problem is, the bind/unbind(this) don't compile well and I think it's because I don't implement "BeaconConsumer" on the MainActivity because he can't get the consumer right.
It's telling me : "Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference" and return me on the bind thing.
So do you have any ideas on how I can deal with this in a way that I keep my beaconManager ?
Thank you in advance.
PS : Sorry if my English is not perfect
BeaconConsumer interface is designed to be implemented by an Activity or Service class. If you want to implement this interface in a POJO as shown in the question, you need to chain the method definitions shown below.
#Override
public Context getApplicationContext() {
return getActivity().getApplicationContext();
}
#Override
public void unbindService(ServiceConnection serviceConnection) {
getActivity().unbindService(serviceConnection);
}
#Override
public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
return getActivity().bindService(intent, serviceConnection, i);
}
I suspect your code already has empty implementations of these methods, otherwise your code would not compile. Make sure you have provided full implementations as shown above.

Android AsyncTask runs multiple times

In my app ,there is an one button which get input from database.When I press it more than one in a short time it crashes.
How can i avoid this error with using asynctask?
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showinf();
}
});
}
private String[] columns={"name","surname"};
private void showinf(){
SQLiteDatabase db=v1.getReadableDatabase();
Cursor c=db.query("infos",columns,null,null, null,null,null);
Random mn2=new Random();
int count=c.getCount();
String mn=String.valueOf(count);
int i1=mn2.nextInt(count+1);
c.move(i1);
t1.setText(c.getString(c.getColumnIndex("name")));
t2.setText(c.getString(c.getColumnIndex("surname")));
}
thanks...
You can create a boolean flag (let's say bDiscardButtonAction), and set it to true in onPreExecute() and set it to false in onPostExecute(), something like:
public class FooTask extends AsyncTask<Foo, Foo, Foo>
{
private static boolean bDiscardButtonAction = false;
private boolean isDiscareded = false;
#Override
public void onPreExecute()
{
if(bDiscardButtonAction)
{
isDiscareded = true;
return;
}
bDiscardButtonAction = true;
}
#Override
public Foo doInBackground(Foo... params)
{
if(isDiscareded) return;
// ...
}
#Override
public void onPostExecute(Void result)
{
if(!isDiscareded) bDiscardButtonAction = false;
}
#Override
public void onCancelled(Foo result)
{
if(!isDiscareded) bDiscardButtonAction = false;
}
}
disable the show button in onPreExecute() and enable it back onPostExecute().
public class getAsyncDataTask extends AsyncTask<Void, Void, Void>
{
#Override
public void onPreExecute()
{
show.setAlpha(0.5);
show.setEnable(false);
}
#Override
public void doInBackground(Void... params)
{
//retrieve the data from db;
}
#Override
public void onPostExecute()
{
show.setAlpha(1.0);
show.setEnable(true);
}
}
I hope this code will help u out.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
new AsynchTaskManualLocation().execute();
});
public class AsynchTaskGetData extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... url) {
//showinf(); this method contains operation of getting data from //database OR ur logic to getdata
return showinf();
}
#Override
protected void onPostExecute(String result) {
//here u get result in resul var and process the result here
}
}
}

MediaPlayer error-getCurrentPosition

Please teach me how can I solve a MediaPlayer error. I have Mediaplayer, MediaController and listview. When I touch the list, a song starts with MediaController, but when I touch keycode_home and restart my app, the error occurs. Here is my code and error.
java.lang.RuntimeException: Unable to resume activity {}:
java.lang.IllegalStateException
Caused by: java.lang.IllegalStateException at android.media.MediaPlayer.getCurrentPosition(Native Method)
int si[]={R.raw.sample1,R.raw.sample2,R.raw.sample3};
onCreate
ItemBean IB1 = new ItemBean();
IB1.setName("sample1");
IB1.setUrl("http~");
ItemBean IB2 = new ItemBean();
IB2.setName("sample2");
IB2.setUrl("http~");
ItemBean IB3 = new ItemBean();
IB3.setName("sample3");
IB3.setUrl("http~");
List<ItemBean> list = new ArrayList<ItemBean>();
list.add(IB1);
list.add(IB2);
list.add(IB3);
mp = new MediaPlayer();
controller = new MediaController(this);
controller.setAnchorView(findViewById(R.id.mediaController));
controller.setMediaPlayer(this);
list2 = (ListView) findViewById(R.id.song_list);
SonglistAdapter_test adapter = new SonglistAdapter_test(getApplicationContext(),list);
list2.setAdapter(adapter);
list2.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
try {
mp.reset();
mp.release();
mp = MediaPlayer.create(SongsActivity.this,si[position]);
} catch (Exception e) {}
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
handler.post(new Runnable() {
#Override
public void run() {
controller.setEnabled(true);
controller.show(mp.getDuration());
mp.start();
try {
Method m = android.widget.MediaController.class.getDeclaredMethod("updatePausePlay");
m.setAccessible(true);
m.invoke(controller);
} catch (Exception e) {
}
}
});
}
});
}
#Override
public void start(){
mp.start(); }
#Override
public void pause(){
mp.pause(); }
#Override
public int getDuration(){
return mp.getDuration(); }
#Override
public int getCurrentPosition(){
return mp.getCurrentPosition(); }
#Override
public void seekTo(int pos){
mp.seekTo(pos); }
#Override
public boolean isPlaying(){
return mp.isPlaying(); }
#Override
public int getBufferPercentage(){
return 0; }
#Override
public boolean canPause(){
return true; }
#Override
public boolean canSeekBackward(){
return true; }
#Override
public boolean canSeekForward(){
return true; }
#Override
public int getAudioSessionId(){
return 0; }
#Override
protected void onPause(){
super.onPause();
}
#Override
protected void onResume(){
super.onResume();
}
#Override
protected void onStop(){
super.onStop();
controller.hide();
mp.stop();
mp.release();
}
#Override
public void onRestart(){
super.onRestart();
controller.show();
}
#Override
protected void onDestroy(){
super.onDestroy();
finish();
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
finish();
}
return super.dispatchKeyEvent(event);
}
The problem is in your onStop() method -- you are releasing your media player there and not recreating it before you show the controller during onRestart(). The onStop() method is not the same as onDestroy() -- onStop() doesn't mean that your activity will necessarily run through onCreate() again when it is resumed.
You should have a look at the Activity Lifecycle to get a better understanding of when these events occur.

Categories