How to destroy activity without crashing the app - android-studio

I`v been trying for a while to destroy activity when the home button is pressed or when the app is in background and I manage to do something with this code
#Override
protected void onPause() {
this.finish();
super.onPause();
}
and when the app runs it does not crash but after a while playing in the activity the app just goes background and crashes.
This is the activity that I`m talking about:
public class Playing extends AppCompatActivity implements View.OnClickListener {
final static long INTERVAL=1154;//1 second
final static long TIMEOUT=7000;
int progressValue = 0;
CountDownTimer mcountDown;
List<Question> questionPlay = new ArrayList<>();
DbHelper db;
int index=0 , score =0,thisQuestion=0,totalQuestion,CorrectAnswer;
String mode = "";
ProgressBar progressBar;
ImageView imageView;
Button btnA, btnB, btnC,btnD;
TextView txtScore,txtQuestion;
#Override
protected void onPause() {
this.finish();
super.onPause();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playing);
Bundle extra = getIntent().getExtras();
if(extra!=null)
mode =extra.getString("MODE");
db = new DbHelper(this);
txtScore = (TextView)findViewById(R.id.txtScore);
txtQuestion =(TextView)findViewById(R.id.txtQuestion);
progressBar=(ProgressBar) findViewById(R.id.progreessBar);
btnA = (Button) findViewById(R.id.btnAnswerA);
btnB =(Button)findViewById(R.id.btnAnswerB);
btnC = (Button)findViewById(R.id.btnAnswerC);
btnD = (Button)findViewById(R.id.btnAnswerD);
imageView = (ImageView)findViewById(R.id.question_bike);
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
btnC.setOnClickListener(this);
btnD.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
questionPlay = db.getQuestionMode(mode);
totalQuestion = questionPlay.size();
mcountDown = new CountDownTimer(TIMEOUT, INTERVAL) {
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mcountDown.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
private void showQuestion(int index) {
if (index < totalQuestion){
thisQuestion++;
txtQuestion.setText(String.format("%d %d",thisQuestion,totalQuestion));
progressBar.setProgress(0);
progressValue = 0;
int ImageID = this.getResources().getIdentifier(questionPlay.get(index).getImage().toLowerCase(),"drawable",getPackageName());
imageView.setBackgroundResource(ImageID);
btnA.setText(questionPlay.get(index).getAnswerA());
btnB.setText(questionPlay.get(index).getAnswerB());
btnC.setText(questionPlay.get(index).getAnswerC());
btnD.setText(questionPlay.get(index).getAnswerD());
mcountDown.start();
}
else {
Intent intent = new Intent(this,Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL",totalQuestion);
dataSend.putInt("CORRECT",CorrectAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
#Override
public void onClick(View v) {
mcountDown.cancel();
if (index < totalQuestion){
Button clickedButton = (Button)v;
if(clickedButton.getText().equals(questionPlay.get(index).getCorrectAnswer())){
score+=1;
CorrectAnswer++;
showQuestion(++index);
}
else showQuestion(++index);
txtScore.setText(String.format("S:%d",score));
}
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Playing.this ,MainActivity.class) ;
startActivity(intent) ;
finish() ;
}
}
I`v tried and with this code
#Override
protected void onDestroy(){
super.onDestroy;
finish();
}
but then the second activity does not start and the app crashes again.
So what to do?

Related

I want to know how to randomly display images in gridview through SwipeRefreshLayout

SwipeRefreshLayout refreshLayout = findViewById(R.id.refresh_grid);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getImages();
refreshLayout.setRefreshing(false);
}
});
getImages();
}
I want to know how to randomly display images in gridview through SwipeRefreshLayout
I want a UI like the site https://www.pinterest.com
I want to show random images on refresh to show a lot of images, can you tell me how?
thank you in advance
Below is the full code.
public class MainActivity extends AppCompatActivity {
private List<String> mImagesLinks = new ArrayList<>();
private GridView mGridView;
FloatingActionButton option_01;
FloatingActionButton option_02;
FloatingActionButton option_03;
FloatingActionButton option_04;
static final int PERMISSIONS_REQUEST = 0x0000001;
//종료팝업 전면광고 추가
private static final String TAG = "ted";
TedAdmobDialog nativeTedAdmobDialog;
int nCurrentPermission = 0;
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, getString(R.string.admob_app_id));
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
checkPermission();
mGridView = findViewById(R.id.grid_view);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
startActivity(new Intent(MainActivity.this, ImageActivity.class)
.putExtra("Link", mImagesLinks.get(i)));
}
});
option_01 = findViewById(R.id.option_01);
option_01.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName()));
startActivity(intent);
});
option_02 = findViewById(R.id.option_02);
option_02.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/developer?id=Project+J+Lab"));
startActivity(intent);
});
option_03 = findViewById(R.id.option_03);
option_03.setOnClickListener(v -> {
Intent myintent = new Intent(Intent.ACTION_SEND);
myintent.setType("text/plan");
String shereBoday = "Your Boday Here";
String shereSub = "\"http://play.google.com/store/apps/details?id=" + getPackageName();
myintent.putExtra(Intent.EXTRA_SUBJECT, shereBoday);
myintent.putExtra(Intent.EXTRA_TEXT, shereSub);
startActivity(Intent.createChooser(myintent, "shere Using"));
});
option_04 = findViewById(R.id.option_04);
option_04.setOnClickListener(v -> {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("plain/text");
String[] address = {"dhsthdwjd1#gmail.com"};
email.putExtra(Intent.EXTRA_EMAIL, address);
email.putExtra(Intent.EXTRA_SUBJECT, getPackageName());
email.putExtra(Intent.EXTRA_TEXT, "text");
startActivity(email);
});
SwipeRefreshLayout refreshLayout = findViewById(R.id.refresh_grid);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getImages();
refreshLayout.setRefreshing(false);
}
});
getImages();
}
private void getImages() {
Call<List<String>> imagesResponse = NetworkUtils.getInterface().loadImages();
imagesResponse.enqueue(new Callback<List<String>>() {
#Override
public void onResponse(Call<List<String>> call, Response<List<String>> response) {
if (response.isSuccessful()) {
mImagesLinks = response.body();
ImagesAdapter imagesAdapter = new ImagesAdapter(MainActivity.this, mImagesLinks);
mGridView.setAdapter(imagesAdapter);
imagesAdapter.notifyDataSetChanged();
} else {
Toast.makeText(MainActivity.this, R.string.error_response, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<List<String>> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onBackPressed() {
//종료팝업 전면광고 추가
nativeTedAdmobDialog = new TedAdmobDialog.Builder(MainActivity.this, TedAdmobDialog.AdType.NATIVE, getString(R.string.banner_ad_unit_id_native))
.setOnBackPressListener(new OnBackPressListener() {
#Override
public void onReviewClick() {
}
#Override
public void onFinish() {
finish();
}
#Override
public void onAdShow() {
log("onAdShow");
nativeTedAdmobDialog.loadNative();
}
})
.create();
nativeTedAdmobDialog.show();
}
//종료팝업 전면광고 추가
private void log(String text) {
Log.d(TAG, text);
}
private void checkPermission() {
PermissionListener permissionlistener = new PermissionListener() {
#Override
public void onPermissionGranted() {
}
#Override
public void onPermissionDenied(List<String> deniedPermissions) {
}
};
TedPermission.with(this)
.setPermissionListener(permissionlistener)
.setPermissions(
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.SET_WALLPAPER,
Manifest.permission.READ_CONTACTS)
.check();
}
}
Just use Collections.shuffle(list); in your getImages() function.
Refer this for more information : https://www.geeksforgeeks.org/shuffle-or-randomize-a-list-in-java/

How do i update my firebase adapter with new items without repopulating the entire list

I'm trying to implement endless scrolling in my firebase recycler view.I limit my query to 5 items then the users scrolls to the end of the list the query is updated and the limit is increased my another 5. But the adapter only updates when i leave and return to the activity. I tried notifydatasetchange(), but that doesn't work. I tried recyclerview.setadapter(). It works but it also resets the scroll position of my recycler view.Nothing else seems to work.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view=inflater.inflate(R.layout.card_view,container,false);
mDatabase= FirebaseDatabase.getInstance().getReference().child("Posts");
mDatabaseUpvote= FirebaseDatabase.getInstance().getReference().child("Upvote");
mAuth=FirebaseAuth.getInstance();
recyclerView = (RecyclerView) view.findViewById(R.id.recycleview_new);
recyclerView.setHasFixedSize(true);
mLayoutManager=(new LinearLayoutManager(getActivity()));
recyclerView.setLayoutManager(mLayoutManager);
mDatabaseUpvote.keepSynced(true);
mDatabase.keepSynced(true);
query=mDatabase.limitToFirst(count);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
firstItem=mLayoutManager.findLastVisibleItemPosition();
ItemCount=recyclerView.getChildCount();
TotalItemCount=mLayoutManager.getItemCount();
if (loading){
if (TotalItemCount>prevTotal){
loading=false;
prevTotal=TotalItemCount;
}
}
if (!loading && (TotalItemCount-firstItem) <= (firstItem+visthresh)){
count=count+2;
query=mDatabase.limitToFirst(count);
Toast.makeText(getActivity(), "ThresholdReached", Toast.LENGTH_SHORT).show();
loading=true;
}
}
});
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Cards, Postviewholder>(
Cards.class,
R.layout.cards,
Postviewholder.class,
query
) {
#Override
protected void populateViewHolder(final Postviewholder viewHolder, Cards model, final int position) {
final String postKey=getRef(position).getKey();
viewHolder.setUsername(model.getUsername());
viewHolder.setImage(getActivity(),model.getImage());
viewHolder.setimage_icon(getActivity(),model.getImageicon());
viewHolder.setTitle(model.getTitle());
viewHolder.setTextColor(model.getTextColor());
viewHolder.setUpvote(postKey);
viewHolder.post_Image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent2= new Intent(getActivity(),View_post.class);
intent2.putExtra("Userprofile",postKey);
startActivity(intent2);
}
});
viewHolder.imageicon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent2= new Intent(getActivity(),UserActivity_2.class);
intent2.putExtra("Userprofile",postKey);
startActivity(intent2);
}
});
viewHolder.upvote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProcessUpvote = true;
mDatabaseUpvote.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (ProcessUpvote) {
if (dataSnapshot.child(postKey).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseUpvote.child(postKey).child(mAuth.getCurrentUser().getUid()).removeValue();
ProcessUpvote = false;
} else {
mDatabaseUpvote.child(postKey).child(mAuth.getCurrentUser().getUid()).setValue("RandomValue");
ProcessUpvote = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
if (sharedPreferences != null) {
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(getActivity());
Posit=(preferences.getInt(RV_POS_INDEX,0));
mRvTopView=(preferences.getInt(RV_TOP_VIEW,0));
Toast.makeText(getActivity(), "RestoreState", Toast.LENGTH_SHORT).show();
firebaseRecyclerAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
public void onItemRangeInserted(int positionStart, int itemCount) {
mLayoutManager.scrollToPositionWithOffset(Posit, mRvTopView);
}
});
}
return view;
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Posit = mLayoutManager.findFirstVisibleItemPosition();
View startView = recyclerView.getChildAt(0);
mRvTopView = (startView == null) ? 0 : (startView.getTop() - recyclerView.getPaddingTop());
Toast.makeText(getActivity(), "SaveState", Toast.LENGTH_SHORT).show();
sharedPreferences= PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt(RV_POS_INDEX,Posit);
editor.putInt(RV_TOP_VIEW,mRvTopView);
editor.apply();
}
public static class Postviewholder extends RecyclerView.ViewHolder {
View mView;
ImageView upvote;
ImageView imageicon;
ImageView post_Image;
private DatabaseReference mDatabaseUpvote;
private FirebaseAuth mAuth;
public Postviewholder(View itemView) {
super(itemView);
mView = itemView;
imageicon = (ImageView) mView.findViewById(R.id.Post_imiageicon);
post_Image = (ImageView) mView.findViewById(R.id.CardImage);
upvote = (ImageView) mView.findViewById(R.id.upvote);
mDatabaseUpvote = FirebaseDatabase.getInstance().getReference().child("Upvote");
mAuth = FirebaseAuth.getInstance();
}
public void setUpvote(final String postKey) {
mDatabaseUpvote.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(postKey).hasChild(mAuth.getCurrentUser().getUid())) {
upvote.setImageResource(R.drawable.ic_thumb_up_black_24dp2);
} else {
upvote.setImageResource(R.drawable.ic_thumb_up_black_24dp);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void setImage(final Context ctx, final String image) {
final ImageView imageView = (ImageView) mView.findViewById(R.id.CardImage);
Glide.with(ctx)
.load(image)
.into(imageView);
}
public void setTitle(String title) {
TextView cardtitle = (TextView) mView.findViewById(R.id.cardTitle);
cardtitle.setText(title);
}
public void setUsername(String username) {
TextView post_username = (TextView) mView.findViewById(R.id.post_username);
post_username.setText(username);
}
public void setimage_icon(final Context ctx, final String imageicon) {
final ImageView image_icon = (ImageView) mView.findViewById(R.id.Post_imiageicon);
Glide.with(ctx)
.load(imageicon)
.into(image_icon);
}
public void setTextColor(int TextColor) {
CardView cardView= (CardView)mView.findViewById(R.id.Cardview_card);
TextView post_username = (TextView) mView.findViewById(R.id.post_username);
TextView cardtitle = (TextView) mView.findViewById(R.id.cardTitle);
int textcolr=getContrastColor(TextColor);
int white=Color.WHITE;
int resultColor = blendARGB(TextColor,white,0.1f);
cardView.setCardBackgroundColor(resultColor);
cardtitle.setTextColor(textcolr);
post_username.setTextColor(textcolr);
}
}
}

Counting number of times android app goes into background

I'm developing an app which counts number of times the app goes to the background. It also retains the values when the orientation is changed. Though I have it working of all use cases, I have one use case which does not work.
Case : When I press the home button, change the phone's orientation and reopen the app, It does open in landscape mode but, the background count does not increase.
I have tried setting values in all the life cycle methods. It doesn't work. Hope somebody can help me with this.
`
public class MainActivity extends AppCompatActivity {
private int clickCount =0, backgroundCount = 0;
TextView tvClickCountValue, tvBackgroundCountValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if( savedInstanceState != null){
clickCount = savedInstanceState.getInt("COUNT");
backgroundCount = savedInstanceState.getInt("BGCOUNT");
}
setContentView(R.layout.activity_main);
tvClickCountValue = (TextView) this.findViewById(R.id.tvClickCountValue);
tvBackgroundCountValue = (TextView) this.findViewById(R.id.tvBackgroundCountValue);
setView(MainActivity.this);
}
public void onClick(View v){
clickCount += 1;
tvClickCountValue.setText(Integer.toString(clickCount));
}
public void setView(Context ctx){
tvClickCountValue.setText(Integer.toString(clickCount));
tvBackgroundCountValue.setText(Integer.toString(backgroundCount));
}
#Override
protected void onStop() {
super.onStop();
backgroundCount += 1;
}
#Override
protected void onResume() {
super.onResume();
tvClickCountValue.setText(Integer.toString(clickCount));
tvBackgroundCountValue.setText(Integer.toString(backgroundCount));
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("COUNT", clickCount);
outState.putInt("BGCOUNT", backgroundCount);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
clickCount = savedInstanceState.getInt("COUNT");
backgroundCount = savedInstanceState.getInt("BGCOUNT");
}
}
This article contains useful information: https://developer.android.com/guide/topics/resources/runtime-changes.html especially in the section about Handling The Change.
Try handling it on onConfigurationChanged() of you have disabled Activity restarts on orientation changes. Otherwise, probably through this article you will find which case applies to your scenario.
By reading the problem description, I am assuming that if you don't rotate the device the application works as intended.
you need to persist the count in the SharedPreferences. each time you reopen the app read the last value from the SharedPreferences. And increment and save to SharedPreferences each time the app is hidden.
Then you can count the with #kiran code:
public class BaseActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
public static boolean isAppInFg = false;
public static boolean isScrInFg = false;
public static boolean isChangeScrFg = false;
#Override
protected void onStart() {
if (!isAppInFg) {
isAppInFg = true;
isChangeScrFg = false;
onAppStart();
}
else {
isChangeScrFg = true;
}
isScrInFg = true;
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (!isScrInFg || !isChangeScrFg) {
isAppInFg = false;
onAppPause();
}
isScrInFg = false;
}
public void onAppStart() {
// app in the foreground
// show the count here.
}
public void onAppPause() {
// app in the background
// start counting here.
}
}

Android studio pause and resume countdown timer for progress bar

I am using a countdown timer which updates my progress bar which decreases from 100 (full) to 0(empty) but when the app is paused would like to pause the timer and then restart it upon resuming the app. I implement the count down timer like so:
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
int progress = (int) (millisUntilFinished / 100);
progressBar.setProgress(progress);
}
#Override
public void onFinish() {
progressBar.setProgress(0);
Intent intent = new Intent(getApplicationContext(), GameOver.class);
startActivity(intent);
finish();
}
}
And in my on create:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_screen);
progressBar = (ProgressBar)findViewById(R.id.timerBar);
progressBar.setProgress(100);
myCountDownTimer = new MyCountDownTimer(10000, 10);
myCountDownTimer.start();
}
You can add a boolean in your MyCountDownTimer class that will change in the onPause and onResume methods of your Activity. Check the // ADDED comments to see the changes you have to make to make this work.
public class MyActivity extends Activity {
MyCountDownTimer myCountDownTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_screen);
progressBar = (ProgressBar)findViewById(R.id.timerBar);
progressBar.setProgress(100);
myCountDownTimer = new MyCountDownTimer(10000, 10);
myCountDownTimer.start();
}
// ADDED
#Override
public void onPause() {
super.onPause(); // Always call the superclass method first
myCountDownTimer.pause();
}
// ADDED
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
myCountDownTimer.resume();
}
}
public class MyCountDownTimer extends CountDownTimer {
// ADDED
private boolean pause;
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
// ADDED
public void pause() {
pause = true;
}
// ADDED
public void resume() {
pause = false;
}
#Override
public void onTick(long millisUntilFinished) {
int progress = (int) (millisUntilFinished / 100);
// ADDED
if (!pause) {
progressBar.setProgress(progress);
}
}
#Override
public void onFinish() {
// ADDED
isRunning = false;
progressBar.setProgress(0);
Intent intent = new Intent(getApplicationContext(), GameOver.class);
startActivity(intent);
finish();
}
}

gc freed xxxx objects and than freeze application

I'm trying to create simple app which contains of ten activities. Each activity look pretty much the same, it has four buttons (different color) and when one particular button is clicked it's open next activity. OnCreate method of every activity has mediaplayer that play name of that activity. After some time I see in LogCat that gc freed some objects and at that time Activity don't play any sound and buttons are disabled.
Do you have any advice or suggestions how to resole that?
Here is code of one Activity:
public class Green extends Activity {
int buttonActive = 0;
int buttonWrong = 0;
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_green);
buttonWrong = 0;
playSound();
Button btn = (Button)findViewById(R.id.button1);
Button btn2 = (Button)findViewById(R.id.button2);
Button btn3 = (Button)findViewById(R.id.button3);
Button btn4 = (Button)findViewById(R.id.button4);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(buttonActive == 1){
playSoundCorrect();
Intent intent = new Intent(v.getContext(),Blue.class);
startActivity(intent);
}
}
});
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(buttonActive == 1 && buttonWrong == 0){
buttonWrong = 1;
playSoundWrong();
}
}
});
btn3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(buttonActive == 1 && buttonWrong == 0){
buttonWrong = 1;
playSoundWrong();
}
}
});
btn4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(buttonActive == 1 && buttonWrong == 0){
buttonWrong = 1;
playSoundWrong();
}
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
private void playSound(){
MediaPlayer player = MediaPlayer.create(this, R.raw.green);
player.start();
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
buttonActive = 1;
}
});
}
private void playSoundWrong(){
player = MediaPlayer.create(this, R.raw.wrong2);
if(!player.isPlaying()){
player.start();
}
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
buttonWrong = 0;
}
});
}
private void playSoundCorrect(){
MediaPlayer player = MediaPlayer.create(this, R.raw.correct);
player.start();
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
}
It looks like in private void playSound you're masking the class's player property. If you say player = MediaPlayer.create then the class's player property will be set to the new MediaPlayer, and the player will be reachable so long as the class is reachable. Instead you're saying MediaPlayer player = MediaPlayer.create, which is creating a new player variable that is scoped to the playSound method - once the method terminates the player is no longer reachable and will be garbage-collected, even if the class is still reachable.

Resources