Alex Rivera | Logout

How do I start an Intent from an OnClickListener

Asked 2011-05-23T22:59:59.747
15

My Main Activity extends ListActivity and displays a List. I am using custom Listitems defined in a class named DefinitionAdapter. I also have a seperate class that implements OnClickListener.

In the class DefinitionAdapter I set the OnClickListener to the ListItems:

   public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)getContext().getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.row, null);
        }
...

        v.setOnClickListener(new OnItemClickListener(position) );

        return v;
   }

My custom OnClickListener is supposed to start another activity.

public class OnItemClickListener implements OnClickListener extends Activity {


    private int position;

    public OnItemClickListener(int p) {

        position = p;   
    }

    @Override
    public void onClick(View v) {

        Intent intent = new Intent(this, ShowDefinition.class);
        startActivity(intent);

    }

}

I am not sure that I am doing that right. I added my new activity to the manifest, as well as the activity i extended the listener with:

<activity android:name="ShowDefinition" android:label="@string/app_name">
</activity>
<activity android:name="OnItemClickListener" android:label="@string/app_name">
</activity>    

Nonetheless, if I click on an Item in my List, the application always breaks with a NullPointerException. I think I am using the intent wrong... any Ideas?

In regard to Nikita Beloglazov's comment:

It breaks when I create the Intent:

Intent intent = new Intent(this, ShowDefinition.class);

Here's the stacktrace:

05-23 22:56:46.629: ERROR/AndroidRuntime(258): Uncaught handler: thread ma
Edit
Report

1 Answer

3

There are two ways to implement an onItemClickListener. You don't need to create a new class. Maybe you can try it the easy way for now :)

Have your ListActivity implement AdapterView.OnItemClickListener

public class MyActivity extends ListActivity implements AdapterView.OnItemClickListener

Then in your ListActivity's onCreate set your onClickListener like this :

        ListView lstvwContacts = getListView();
        lstvwContacts.setOnItemClickListener(this);

And then you can react to the click like this :

public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    switch (parent.getId()) {
        case android.R.id.list: {
            Log.v(TAG, "onItemClick");
            Intent intent = new Intent(this, ShowDefinition.class);
            startActivity(intent);
        }    
    }
}

That should do it for clicks. If you need to know when an item is selected you can look into AdapterView.OnItemSelectedListener

-I_Artist

answered 2011-05-23T23:19:02.523

Your Answer