AbAppletic AbAppletic - 1 month ago 14
Java Question

Activity is restarting onClick of a button

I have this code:

public void onClick(View v) {
if (mp == null)
mp = new MediaPlayer();
try {
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("click.mp3");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalArgumentException | IllegalStateException | IOException e) {
e.printStackTrace();
}
increment(button,key);
v.setEnabled(false);
final View clicked = v;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
clicked.setEnabled(true);
}
};
handler.postAtTime(runnable,System.currentTimeMillis()+100);
handler.postDelayed(runnable,100);

}


The activity is restarting when I call on this method. I've tried:


  • Removing
    mp
    and all its calls

  • Removing the
    Runnable



But it's not working.

When I remove all the code from this method, it works.

I tried to debug. It wasn't activated on any of these lines. It takes me to a bunch of Android files (
such as View.java
). When I "Run to cursor" (skip the next debug breakpoint), it restarts.

Edit: Removing the collapsed
try-catch
es solved it. However, when I call on this method within that method:

@Contract("_, null -> fail")
@SuppressLint("SetTextI18n")
@SuppressWarnings("UnusedAssignment")
public static void increment(final Button button, final String key) {
if (key == null)
throw new NullPointerException("Key cannot be null");
DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("Campaigns").child(key);
int preIncrementUserCount = Integer.parseInt(button.getText().toString());
final int incrementedUserCount = ++preIncrementUserCount;
button.setText(incrementedUserCount + "");
database.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
int totalCount = mutableData.child("count").getValue(int.class);
int newTotalCount = ++totalCount;
mutableData.child("count").setValue(newTotalCount);
mutableData.child("users").child(getUid()).child("count").setValue(incrementedUserCount);
return Transaction.success(mutableData);
}

@Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {

}
});
}


The problem will persist.

Edit: A simple hint on solving this (that helps) will be awarded the bounty.

Answer

I had the increment() method (which does the Transaction) in another class that inherits nothing which I use to store all Firebase methods.

For no obvious reason, removing it from there and putting it in my Activity worked.

Before:

public class FirebaseController{
   //...
   increment(..){
      //...
    }
}

After:

public class MyActivity extends Activity{
   @Override
   public void onCreate(Bundle b){
     //...
     increment(...);
   }
   //...
   public void increment(..){
        //...
     }
}