Nikhil Agrawal
Nikhil Agrawal

Reputation: 26538

Getting return value from onClickListener of Android

Can I set variable into context like session in web development?

Here is my code to in which I am developing an confirmation box as soon as the Android application get started:

package com.example.alertboxandloadingwidgets;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Boolean result = showConfirmationBox("Are you sure you want to do this",
        this);
    }
    public Boolean showConfirmationBox(String messageToShow, final Context context) {
        // prepare the alert box
        AlertDialog.Builder alertbox = new AlertDialog.Builder(context);
        // set the message to display
        alertbox.setMessage(messageToShow);
        // set a positive/yes button and create a listener
        alertbox.setPositiveButton("Yes",
        new DialogInterface.OnClickListener() {
            // do something when the button is clicked
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(context,
                    "'Yes' button clicked", Toast.LENGTH_SHORT)
                    .show();
            }
        });
        // set a negative/no button and create a listener
        alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
            // do something when the button is clicked
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(context, "'No' button clicked",
                Toast.LENGTH_SHORT).show();
            }
        });
        // display box
        alertbox.show();
    }
}

But I want that if the yes button is clicked then it has to return true and if no button is clicked then it has to return false.

But I am not able to do so because return type of onClickListener is void.

Update

But the problem is that I have make it generic means This method I have to write in a CommonUtilities Class From where any of the activity can use this method. So I have to set or reset the value the result parameter from where I am calling this method.

Upvotes: 2

Views: 23915

Answers (9)

Aleks G
Aleks G

Reputation: 57336

Android dialogs are asynchronous, therefore you need to refactor your code to deal with this. I'm guessing you were planning to do something like this:

boolean result = showConfirmation(...);
if(result) {
    //do something
}
else {
    //do something else
}

You can achieve the same result with something like this:

public class MainActivity extends Activity {
    private boolean result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showConfirmationBox("Are you sure you want to do this", this);
    }

    private doOnTrueResult() {
        result = true;
        //do something
    }

    private doOnFalseResult() {
        result = false;
        //do something else
    }

    public void showConfirmationBox(String messageToShow, final Context context) {

        // prepare the alert box
        AlertDialog.Builder alertbox = new AlertDialog.Builder(context);

        // set the message to display
        alertbox.setMessage(messageToShow);

        // set a positive/yes button and create a listener
        alertbox.setPositiveButton("Yes",
        new DialogInterface.OnClickListener() {

            // do something when the button is clicked
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(context,
                    "'Yes' button clicked", Toast.LENGTH_SHORT)
                    .show();
                doOnTrueResult();
            }
        });

        // set a negative/no button and create a listener
        alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {

            // do something when the button is clicked
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(context, "'No' button clicked",
                Toast.LENGTH_SHORT).show();
                doOnFalseResult();
            }
        });

        // display box
        alertbox.show();
    }
}

Upvotes: 7

Ankitkumar Makwana
Ankitkumar Makwana

Reputation: 3485

this may helps you

public class MainActivity extends Activity {
     Boolean mresult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

          Boolean result = showConfirmationBox("Are you sure you want to do this",this);
          Toast.makeText(getApplicationContext(), ""+result, Toast.LENGTH_LONG).show();


    }

     public Boolean showConfirmationBox(String messageToShow, final Context context) {       

            AlertDialog.Builder alertbox = new AlertDialog.Builder(context);
            // set the message to display
            alertbox.setMessage(messageToShow);
            // set a positive/yes button and create a listener
            alertbox.setPositiveButton("Yes",
            new DialogInterface.OnClickListener() {
                // do something when the button is clicked
                public void onClick(DialogInterface arg0, int arg1) {
                    Toast.makeText(context,
                        "'Yes' button clicked", Toast.LENGTH_SHORT)
                        .show();

                    mresult = true;
                }
            });
            // set a negative/no button and create a listener
            alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
                // do something when the button is clicked
                public void onClick(DialogInterface arg0, int arg1) {
                    Toast.makeText(context, "'No' button clicked",
                    Toast.LENGTH_SHORT).show();

                    mresult = false;
                }
            });
            // display box
            alertbox.show();
            return mresult;
        }


}

Upvotes: 0

Cornholio
Cornholio

Reputation: 985

One simple way you could do it:

public class MainActivity extends Activity {
    public static boolean result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showConfirmationBox("Are you sure you want to do this", this);

    }

    public Boolean showConfirmationBox(String messageToShow, final Context context) {
        AlertDialog.Builder alertbox = new AlertDialog.Builder(context);
        alertbox.setMessage(messageToShow);
        alertbox.setPositiveButton("Yes",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(context, "'Yes' button clicked", Toast.LENGTH_SHORT).show();
                MainActivity.result = true;
            }
        });

    // set a negative/no button and create a listener
    alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {

        // do something when the button is clicked
        public void onClick(DialogInterface arg0, int arg1) {
            Toast.makeText(context, "'No' button clicked",
            Toast.LENGTH_SHORT).show();
            MainActivity.result = false;
        }
    });

    // display box
    alertbox.show();

    }
}

Upvotes: 1

krishna
krishna

Reputation: 142

one of the option would be using the

public Button getButton (int whichButton)
Gets one of the buttons used in the dialog.

this Returns
The button from the dialog, or null if a button does not exist.

for more information check the link http://developer.android.com/reference/android/app/AlertDialog.html

Upvotes: 0

nano_nano
nano_nano

Reputation: 12524

You have to pass the value from onClickListener to a global variable or another method. As you have correctly recognized the return type of onClickListener is void. For a more complex solution take a look to this post

Upvotes: 1

RobinDeCroon
RobinDeCroon

Reputation: 331

Create a setter for the result value, and change the value to the selected value in your onClick() methods.

Make showConfirmationBox void ;-)

Upvotes: 1

Linga
Linga

Reputation: 10573

This is how I've always handled data from dialog boxes

alertbox.setPositiveButton("Yes",
    new DialogInterface.OnClickListener() {

        // do something when the button is clicked
        public void onClick(DialogInterface arg0, int arg1) {
            Toast.makeText(context,
                "'Yes' button clicked", Toast.LENGTH_SHORT)
                .show();
               myFunction(item);
        }
    });

private void myFunction(int result){
// Now the data has been "returned" (that's not
// the right terminology)
}

Similarly, use another function for other Button

Upvotes: 3

nidhi_adiga
nidhi_adiga

Reputation: 1124

You can't do that but u can create a boolean variable and store true if yes and False if no and then u can use that variable accordingly

Upvotes: 1

Robin
Robin

Reputation: 10368

If the function

public Boolean showConfirmationBox(String messageToShow, final Context context)

need to be called in the main thread, you cannot do it. You will never wait for user input on the main thread. That will cause ANR.

If the function can be called in background thread, you can send a message to main thread to show the alert box, and then wait for the result. Make good use of "Handler".

Upvotes: 1

Related Questions