Ali
Ali

Reputation: 39

ListView for option list in AlertDialog

I'm trying to insert a listview inside an AlertDialog to display some options but I'm getting an error with the constructor: ArrayAdapter(this, R.layout.option_list, R.id.option, option_items); It says cannot resolve constructor. The code is below.

private void LongClick() {
    myList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View viewClicked, int position, long IDinDB) {
            Cursor res = myDb.GetRow(IDinDB);
            if (res.moveToFirst()) {
                long idDB = res.getLong(DatabaseHelper.ROWID);
            }

            String[] option_items = {"Delete"};
            ArrayAdapter<String>  adapter = new ArrayAdapter<String>(this, R.layout.option_list, R.id.option, option_items);
            optionList.setAdapter(adapter);
            optionList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    ViewGroup vg = (ViewGroup) view;
                    TextView txt = (TextView) vg.findViewById(R.id.option);
                    Toast.makeText(ViewActivity.this, txt.getText().toString(), Toast.LENGTH_LONG).show();
                }

            });

            return true;
        }

    });

}

Any help will be appreciated.

Upvotes: 0

Views: 36

Answers (1)

aelimill
aelimill

Reputation: 1015

When you write this it means the current object instance class you write in. When you wrote new AdapterView.OnItemLongClickListener() you create a new anonymous class, so the word this inside its methods will refer to this newly created class object. ArrayAdapter needs context instance in constructor, not a AdapterView.OnItemLongClickListener. So you need to reference the context object. You can get it:

a) from method parameter viewClicked object (viewClicked.getContext())

or

b) as ViewActivity.this as you did in onItemClick

Upvotes: 1

Related Questions