OnOptionsItemSelected - Pressing one button executes the action of the other

Alex Bingham :

I have an onOptionsItemSelected method with two buttons that allow me to change the value of a child by clicking either of them.

One button is "complete" and the other is "inprogress".

I click on the complete button it changes the child value properly and then changes the value to "In-progress" without even clicking the "In-progress" button.

I can't find any similar issues to mine, any help would be much appreciated.

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        case R.id.complete:
            Log.d(TAG, "Complete button tapped");
            Intent intent = getIntent();

            final String key = intent.getStringExtra("passKey");

            status.setText(R.string.Complete);

            DatabaseReference ref = database.child(key);
            final DatabaseReference statusRefComplete = ref.child("Status");

            statusRefComplete.setValue("Complete").addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        Toast.makeText(edit_task.this, "Task Complete", Toast.LENGTH_SHORT).show();
                    }
                }
            });

        case R.id.inprogress:
            Log.d(TAG, "In-Progress button tapped");
            Intent intent2 = getIntent();

            final String key2 = intent2.getStringExtra("passKey");

            status.setText(R.string.Inprogress);

            DatabaseReference ref2 = database.child(key2);
            final DatabaseReference statusRefInProgress = ref2.child("Status");

            statusRefInProgress.setValue("In-Progress").addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        Toast.makeText(edit_task.this, "Task In-Progress", Toast.LENGTH_SHORT).show();
                    }//if
                }//OnComplete
            });


    }
    return super.onOptionsItemSelected(item);
}
W0rmH0le :

You forgot to add the break for every condition:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    ...
    switch (item.getItemId()) {

        case R.id.complete:
            ....
            break; // -> You must add this line.
        case R.id.inprogress:
            ...
            break; // -> You must add this line.
    }
    ...
}

If you don't add that, the code will execute the code for R.id.complete but it won't stop. It will keep executing and will run the code for R.id.inprogress. So, just the the "break" point!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=150965&siteId=1