cnfw
cnfw

Reputation: 800

I have an issue with onClick methods for ListView items

I have an application which shows a list view. I am planning to make it so that when a user clicks on a listview item, a dialogue box appears showing an XML layout. But I am having just on little problem.

I have the list view up and running, and working. Here is the code in the activity class for the onclick listener.

 final ListView lv1 = (ListView) findViewById(R.id.listV_main);
        lv1.setAdapter(new ItemListBaseAdapter(this, image_details));

        lv1.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> a, View v, int position, long id) { 
                Object o = lv1.getItemAtPosition(position);
                ItemDetails obj_itemDetails = (ItemDetails)o;
                Toast.makeText(VanillaBlockList.this, "Loading details for: " + " " + obj_itemDetails.getName(), Toast.LENGTH_LONG).show();

                if(obj_itemDetails.getPrice().equals("ID - 1")){

                    // custom dialog
                    final Dialog dialog = new Dialog(Context);
                    dialog.setContentView(R.layout.va_type1);
                    dialog.setTitle("Information");

                    dialog.show();

                }

                if(obj_itemDetails.getPrice().equals("ID - 2")){
              /* Stuff here*/ }
            } 

        });
    } 

The problem is this part of the above code:

if(obj_itemDetails.getPrice().equals("ID - 1")){

                    // custom dialog
                    final Dialog dialog = new Dialog(Context);
                    dialog.setContentView(R.layout.va_type1);
                    dialog.setTitle("Stone");

                    dialog.show();

                }

The line that creates the new dialog is giving me an error. In Eclipse, the "new Dialog(Context)" has the "Context" part underlined in red, indicating an error.

Does anyone know how to fix this?

Thanks

Upvotes: 0

Views: 114

Answers (3)

D-32
D-32

Reputation: 3255

You can only pass objects to Methods / Constructors. "Context" isn't an object. Instead of new Dialog(Context) try getApplicationContext() or getActivityContext():

final Dialog dialog = new Dialog(getApplicationContext());

Upvotes: 0

camdroid
camdroid

Reputation: 524

Could you tell us what the error is, instead of just where it is?

I haven't worked much with Context or Dialog besides the very basics, but try passing in a Context object, not just the class. In the onActivityCreate method, call

Context c = this;

and then

final Dialog dialog = new Dialog(c);

Upvotes: 2

Helal Khan
Helal Khan

Reputation: 887

final Dialog dialog = new Dialog(Context); May be problem is using Context.You use your activity name.this or getApplicationContext().

Upvotes: 0

Related Questions