Here’s my code:
private void makeDialog2() {
AlertDialog.Builder about = new AlertDialog.Builder(getContext());
about.setTitle("You Won!");
about.setPositiveButton("Play Again",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent playIntent2 = new Intent(getContext(),
PracticePlayActivity.class);
playIntent2.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
getContext().startActivity(playIntent2);
((Activity) getContext()).finish();
}
});
about.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg1, int arg2) {
Intent playIntent = new Intent(getContext(),
PlayChooserActivity.class);
playIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
getContext().startActivity(playIntent);
((Activity) getContext()).finish();
}
});
about.show();
}
This code is prompted when the user loses the game and wants to retry. However when i press retry more than 4 times the application crashes. I’m suspecting a memory leak. After some testing in logcat i managed to find out that the activity is still running after retrying.
My plan is to attack this problem with two things. Recycling my drawables and ending the first activity as a whole. However, the first activity is not closing even after i call finish. Any help? (Using getContext() in other parts of my code has worked so far).
EDIT: By ending the activity does it destroy the variables automatically? or do i still need to clear the bitmaps from the Android memory? Any ideas how i can do this?
If
makeDialog2()is declared inside anActivitytry usingthisorYourActivityName.thisinstead ofgetContext(). If it’s not, then try passing theContextto the method as a parameter usingthisorYourActivityName.thisfrom where you call the method.Finishing an
Activityshould destroy it and all related resources. If you start a new instance of theActivitylater on it will re-create all its resources. Unless you use some kind of static variables – they will stay “alive” as long as your app is running.Take a look at the documentation for the
Activity-class.As you can see
Contextis a superclass ofActivity– meaning that everyActivityis aContextbut not everyContextis anActivity. In other words((Activity) getContext()).finish();might cause aClassCastException.What you could do to verify that the
Contextyou get is in fact also anActivityis do a check like this:Add that right before the you call
finish()and check if LogCat agrees that its anActivity.