get input alert onBackPressed Android

android back button exit dialog
close dialog on back press android
alert dialog on back pressed android studio
android show alertdialog on back pressed
onbackpressed() ( alertdialog android)
android popup dialog example
dialog logout android
onbackpressed kotlin

I am trying to get an input from custom dialog when the user clicks back from the activity. I override the onBackPressed() method, I see the dialog but the activity closed right after it.

I also tried to move the super.onBackPressed(); to after calling the dialog

@Override
public void onBackPressed() {
    super.onBackPressed();
    if(enableTimer) {
        countDownTimer.cancel();
    }
    if(enableHistorySaving){
        showCustomDialog(vp.getCurrentItem());
        // i want the activity will be closed here after  getting input.
    }
}

showCustomDialogMethod:

public void showCustomDialog(final int position){
    final Dialog dialog = new Dialog(ExerciseActivity.this);
    dialog.setContentView(R.layout.enter_data);
    dialog.setTitle("save your data...");

    Button okButton = (Button) dialog.findViewById(R.id.ok);
    okButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final int numOfSets = Integer.valueOf(((EditText)dialog.findViewById(R.id.numOfSetsDialog)).getText().toString());
            final String wights = ((EditText)dialog.findViewById(R.id.wights)).getText().toString();
            saveToExcelFile(dayExercises.get(position),wights,numOfSets);
            dialog.dismiss();
        }
    });
    Button cencelButton = (Button) dialog.findViewById(R.id.cencel);
    cencelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    dialog.show();
}

It seems you are showing a dialog to save user data before exiting.

Add this line super.onBackPressed(); in setOnClickListener methods of the dialog buttons

Note: It must be the last line in the listener method

Display Alert on Back Button Pressed in Android Studio, I am trying to get an input from custom dialog when the user clicks back from the activity. I override the onBackPressed() method, I see the dialog but the activity  Display Alert on Back button pressed in Android Studio. April 12, 2015July 27, 2017. Some time in your application, it is needed to prompt user before taking back him to previous page or exit from application. In this article, we will see how you can prompt user on pressing back button. Alert means to get user’s input when needed.

you can use fragment to show alert with this code

@Override
public void onBackPressed() {
    doubleBackToExitPressed(R.id.content_dashboard);
}

public void doubleBackToExitPressed(int content) {
        if (getFragmentManager().getBackStackEntryCount() > 1) {
            FragmentManager manager = getFragmentManager();
            manager.beginTransaction()
                    .remove(manager.findFragmentById(content))
                    .commit();
            manager.popBackStack();
        } else {
            getFragmentManager().beginTransaction()
                    .add(content, Question.newInstance()
                    .addToBackStack(null).commit();
        }
    }

main_activity.xml :

        <FrameLayout
            android:id="@+id/content_dashboard"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

question.xml :

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/question_layout"
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:layout_marginLeft="@dimen/dimen_40dp"
    android:layout_marginRight="@dimen/dimen_40dp"
    android:layout_marginTop="@dimen/dimen_16dp"
    android:background="@color/white"
    android:clickable="true"
    android:orientation="vertical"
    android:tag="question"
    app:cardBackgroundColor="@color/colorPrimaryDark">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="100">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="20"
            android:background="@color/colorPrimaryDark"
            android:weightSum="100">


        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="20"
            android:background="@color/colorGrayLight"
            android:orientation="vertical"
            android:weightSum="100">

            <TextView
                android:id="@+id/txt_title_dialog"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginRight="@dimen/dimen_16dp"
                android:layout_weight="32"
                android:clickable="true"
                android:gravity="center_vertical"
                android:text="@string/is_login_or"
                android:textColor="@color/black"
                android:textSize="16sp" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="40"
                android:clickable="true"
                android:orientation="horizontal"
                android:paddingLeft="12dp"
                android:weightSum="100">

                <TextView
                    android:id="@+id/txt_cancel_question_answer"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="40"
                    android:gravity="center"
                    android:text="@string/no"
                    android:textColor="@color/black"
                    android:textSize="12sp" />

                <TextView
                    android:id="@+id/txt_ok_question_answer"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="40"
                    android:gravity="center"
                    android:text="@string/yes"
                    android:textColor="@color/black"
                    android:textSize="12sp" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="20" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="28" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="40" />

    </LinearLayout>

</android.support.v7.widget.CardView>

question.java :

public class Question extends Fragment {

    @BindView(R.id.user_question)
    LottieAnimationView user_question;
    @BindView(R.id.txt_title_dialog)
    TextView txt_title_dialog;
    @BindView(R.id.txt_cancel_question_answer)
    TextView txt_cancel_question_answer;
    @BindView(R.id.txt_ok_question_answer)
    TextView txt_ok_question_answer;

    public static Question newInstance() {
        Question question = new Question();
        return question;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.question, parent, false);
        ButterKnife.bind(this, view);

        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {    
    }

    @OnClick(R.id.txt_cancel_question_answer)
    public void setTxt_cancel_question_answer() {
        removeQuestion();

// you can set action for cancel this is



    }

    @OnClick(R.id.txt_ok_question_answer)
    public void setTxt_ok_question_answer() {
        removeQuestion();
// you can set action for ok this is

    }

    public void removeQuestion() {
        FragmentManager manager = getFragmentManager();
        manager.beginTransaction()
                .remove(manager.findFragmentById(content))
                .commit();
        manager.popBackStack();
    }
}

I'm use butter Knife you can see website and learn ! http://jakewharton.github.io/butterknife/

Display Alert on Back button pressed in Android Studio, Alert means to get the user's input when needed. Most of us have played games and when we try to exit it by pressing the "Back" button on an  the same activity is displayed again when i press positive button as if we pressed negative button.but sometimes it is working – user3849690 Aug 1 '14 at 13:59. finish(); should finish your activity.

You can call finish() method. That will finish the activity on press of ok button after accepting the input from user.

@Override
public void onBackPressed() 
{
if(enableTimer)  
{
    countDownTimer.cancel();
}
if(enableHistorySaving)
{
    showCustomDialog(vp.getCurrentItem());

}
}

public void showCustomDialog(final int position){
final Dialog dialog = new Dialog(ExerciseActivity.this);
dialog.setContentView(R.layout.enter_data);
dialog.setTitle("save your data...");

Button okButton = (Button) dialog.findViewById(R.id.ok);
okButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        final int numOfSets = Integer.valueOf(((EditText)dialog.findViewById(R.id.numOfSetsDialog)).getText().toString());
        final String wights = ((EditText)dialog.findViewById(R.id.wights)).getText().toString();
        saveToExcelFile(dayExercises.get(position),wights,numOfSets);
        dialog.dismiss();
        finish();
    }
});
Button cencelButton = (Button) dialog.findViewById(R.id.cencel);
cencelButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        dialog.dismiss();
    }
});
dialog.show();

}

This is updated answer. Please have a look @keiloda

Dialog, Alert means to get user's input when needed. Most of us played games and when we try to exit it by pressing “Back” button in Android phone,  Below are the steps for Creating the Alert Dialog Android Application: Step 1: Create a new project. After that, you have java and XML file. Step 2: Open your XML file and then add TextView for message as shown below (you can change it accordingly). Step 3: Now, open up the activity java file. After, on create method declaration, the onbackpressed method is called when you click the back button of your device.

Provide custom back navigation, Retrieve the ActionBar attached to this dialog, if present. void, onBackPressed​() Generic motion events describe joystick movements, mouse hovers, track pad touches, scroll wheel movements and other input events. It works fine in this is displays the alert (I have the necessary permissions). The problem is that instead of "OnBackPressed" being entered when the back button is pressed I get the message: Attempted to finish an input event but the input event receiver has already been disposed.

Handle Activity State Changes, Contents; Implement Custom Back Navigation; Activity onBackPressed() which you can retrieve by calling getOnBackPressedDispatcher() . CASE: My data was ready to be processes after a preference change listener event and I needed to add a String queried from user. It doesn’t appear possible to pop an alert dialog while the options menu is open…so I had to wait.

DialogFragment, Each activity is given a window in which to draw its user interface… Activity or dialog appears in foreground; User taps Back button Other cases that can cause configuration changes include changes to language or input device. If a new activity or dialog appears in the foreground, taking focus and  Prompt User Input with an AlertDialog. This code creates an input-dialog with AlertDialog.Builder where a user can enter text in an EditText field and press on "Ok" and "Cancel".

Comments
  • Don't do this. Your users will hate it. Just autosave when the user leaves. And if your intent is to save when the user leaves your app, "on back" isn't going to catch cases where the user presses home or another activity is raised on top of yours, or the user taps on a notification with an action.
  • Did you add it after dialog.dismiss(); line in the onClick() of dialog buttons?
  • no. now it works. but i should add finish() instead super. because i couldn't call super from this inner class. tnx
  • Mark the answer as accepted if it solved your problem. Happy coding.!
  • This will not work, super.onBackPressed(); will close the activity