How to return value from inner class?

My code is here:

public static boolean showConfirmationDialog(Context context, String title, String dialogContent) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setTitle(title); builder.setMessage(dialogContent); builder.setPositiveButton("Confirm", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // what to do ? } }); 

right now, I want to return true after I clicked the confirm button. since I can return "true" from the inner class - OnClickListener for the method.

Need help, thanks.

+4
source share
3 answers

You cannot return items from the inner class. In this case, it does not make much sense. Is it supposed that the program will wait inside your onClick function until it returns? This is not how listeners work. What you need to do is take the code that you plan to execute if "true" was returned and placed in your inner class.

+9
source

You either need to set the return to the instance variable (not inside the method), but this can lead to problems with concurrency or use the container object. Pass or use the "final" method variable on which you can set the return value that you want to return. However, I use the term β€œreturn” freely, at least in your example, this code will not be executed immediately, so you really need to do the processing that interests you inside the inner class.

+2
source

OnClickListeners do not return a value. Not knowing what exactly you need to do when the click listener fires, I cannot give you any details, but

 private boolean classBoolean = false; public static boolean showConfirmationDialog(Context context, String title, String dialogContent) { //local variables must be declared final to access in an inner anonymous class final boolean localBoolean = false; AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setTitle(title); builder.setMessage(dialogContent); builder.setPositiveButton("Confirm", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // what to do ? //you can't change a local var since to access it it needs to be final //localBoolean = true; can't do this //so you can change a class var classBoolean = true; //or you can also call some method to do something someMethod(); } }); 
+2
source

Source: https://habr.com/ru/post/1383536/


All Articles