Boardy
Boardy

Reputation: 36237

Return string from AlertDialog

I am working on android project and I am trying to show an AlertDialog which contains a CharSequence array, and when clicked, it supposed to return the string.

Below is the code I am using

String fileName = "";
        //Collect the files from the backup location
        String filePath = Environment.getExternalStorageDirectory().getPath() + "/BoardiesPasswordManager";
        File f = new File(filePath);

        File[] files = f.listFiles();
        final CharSequence[] fileNames = new CharSequence[files.length];
        if (files.length > 0)
        {
            for (int i = 0; i < files.length; i++)
            {
                fileNames[i] = files[i].getName();
            }
        }

        String selectedFile = "";
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("Choose Backup File");
        builder.setItems(fileNames, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int item) {
                fileName = fileNames[item].toString();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();

        return fileName;

As you can see, I am trying to set the fileName to be the selected item within the Array, but Eclipse keeps saying that String fileName needs to be final type, but obviously then I can't set it to the value of the selected string. How can I set the variable so I can return the string.

Thanks for any help you can provide.

Upvotes: 0

Views: 872

Answers (1)

newbyca
newbyca

Reputation: 1513

The problem here is a misunderstanding of when 'return fileName' will be executed. Obviously it would only be valid to execute this code after the user has made a selection. However, it will actually execute before. In fact, it will execute immediately after you call alert.show().

Better would be to remove fileName from the scope of your function and add a function call inside your click event, something like:

public void onClick(DialogInterface dialog, int item){
    String fileName = fileNames[item].toString();
    doSomethingWithTheFile(fileName);
}

Also, your original function would no longer returns anything, it would just set up your dialog.

Upvotes: 1

Related Questions