settheline
settheline

Reputation: 3383

Close AlertDialog after onItemClick - custom ListViewDialog

I'm trying to close a dialog after a user clicks on an item in a ListView that resides in a the dialog. Here's my listDialog method that gets called to open the dialog:

public void listDialog() {
LayoutInflater shoppingListInflater = LayoutInflater.from(this);

//volley request to get listview data
getListsRequest();

final View allListsView = shoppingListInflater.inflate(R.layout.list_picker_dialog, null);

listsPickerView = (ListView) allListsView.findViewById(R.id.shopping_lists_all);

shoppingLists = new ArrayList<ShoppingList>();

allListsAdapter = new ShoppingListsAdapter(this, shoppingLists);

listsPickerView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
    @Override public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {

        shopping_list_id = ((TextView) view.findViewById(R.id.list_id)).getText().toString();
        JSONObject listItemData = new JSONObject();

        try {
            listItemData.put("inventory_item_id", inventory_item_id);
            listItemData.put("shopping_list_id", shopping_list_id);
        } catch (JSONException e) {
            e.printStackTrace();
        }

// a volley network call to an api
        createListItemRequest(listItemData);

//where I want to close the dialog - after the network call. Not working currently
        alertD.cancel();
    }
});

listsPickerView.setAdapter(allListsAdapter);

AlertDialog.Builder listsDialog = new AlertDialog.Builder(this);

listsDialog.setView(allListsView);

listsDialog.setCancelable(false)
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });

    AlertDialog alertD = listsDialog.create();

    alertD.show();

}

Everything works except for the dialog cancel. Because alertD is not in the ItemClickListener, I can't reference it. How can I close this dialog after the network call - referenced above?

Upvotes: 0

Views: 254

Answers (1)

user2808624
user2808624

Reputation: 2530

In contrast to JavaScript, the scope of Java variables starts at the place where they are defined. So you can not refer to alertD, before it is defined.

Just move the call to listsPickerView.setOnItemClickListener behind the definition of alertD and in addition declare alertD as final:

 final AlertDialog alertD = listsDialog.create();

 listsPickerView.setOnItemClickListener(....);

 alertD.show();

Upvotes: 1

Related Questions