Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android AlertDialog inside an anonymous function

I'm trying to create an AlertDialog that opens when an item is click in my listview. However, the constructor of the AlertDialog requires a context, but "this" won't work because it points to the anonymous function. I tried "getApplicationContext()" and "getBaseContext()" but the application crashes.

Any ideas?

    // Open stored preferences page
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

    // Load stored data key/value pairs
    Map<String, String> savedData = (Map<String, String>) settings.getAll();

    // Populate the list view in the activity with the stored data keys
    ListView lSavedData = (ListView) findViewById(R.id.lDataList);

    ArrayAdapter arrAdap = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, savedData.keySet().toArray(new String[0]) );
    lSavedData.setAdapter( arrAdap );

    lSavedData.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            // Prepare a function selection menu for when the user selects a data item 
            AlertDialog.Builder alertBuilder = new AlertDialog.Builder( this );

            alertBuilder.setTitle("What would you like to do?");

            final CharSequence[] dialogOptions =  {"Load", "Delete"};

            alertBuilder.setItems( dialogOptions, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                    //Toast.makeText(getApplicationContext(), dialogOptions[item], Toast.LENGTH_SHORT).show();
                }
            });

            AlertDialog functionDialog = alertBuilder.create();

            functionDialog.show();
            Toast.makeText(getApplicationContext(), "Loaded " + ((TextView) arg1).getText() + " data", Toast.LENGTH_SHORT).show();

        }
    });
}
like image 422
Iyad K Avatar asked Jul 14 '26 04:07

Iyad K


1 Answers

Use YourActivityClassName.this, this should work.

like image 121
Egor Avatar answered Jul 20 '26 19:07

Egor