Search code examples
javaandroidmethodsintreturn

My Method always return 0 ignoring the condition


I have read some related questions like this and this but there the problem is int can't hold much bigger value. In my case its not that.

I'm calling the below method in OnClick of button but it return always 0

public int showRadioAlertDialog(final Button button, String title,
                                    final List<String> list, int selectedIndex) {

        final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle(title);
        builder.setCancelable(false);

        builder.setSingleChoiceItems(list.toArray(new String[list.size()]),
                selectedIndex, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which > -1) {
                            position = which;
                        }
                    }
                });
        builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                printLog("List position = " + list.get(position));
                if (position > -1) {
                    button.setHint(list.get(position));
                }
            }
        });
        builder.setNegativeButton("Cancel", null);
        AlertDialog dialog = builder.create();
        dialog.show();

        if (position > -1) {
            return position;
        } else {
            return -1;
        }
    }

position is a global variable.
What I'm expecting is it should return -1 or the index of selected position.

  1. First thing that I noticed is it return value before user select an item from single choice, it should not return anything before user select an item.

  2. Second if it return before selection the I have a check at the end so it should be -1 why 0.

Please explain a bit why its 0. Any effort would be appreciated.


Solution

  • You call this:

    if (position > -1) {
        return position;
    } else {
        return -1;
    }
    

    After setting the onClickListeners. The thing is that the onClickListeners are invoked from a different thread when the event happens, meaning by the time position is set, the value has been returned already.

    You can't get proper return methods when you use onClickListeners, as they are called as inner classes (or a method if you extend onCLickListener). Use callback methods instead (the following is pseudocode and isn't valid. Don't copy-paste and expect it to work):

    ... onClick(){
        callback(position);
    }
    ...
    
    
    void callback(position){
        do whatever with the variable
    }