tabia
tabia

Reputation: 635

OnItemClickListener() not working with List Adapter

I am fetching data in to list adapter through calling a function named getAllDishes(). Now I want to add OnItemClickListener() on list when I click on a particular item, it opens another activity and pass the id of selected item. I am new to android. All suggestions are welcome.

Main Activity

public class MainActivity extends ListActivity   {

 private DishOperation dishDBoperation;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Button   btListe;

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dishDBoperation = new DishOperation(this);
        dishDBoperation.open();

        List values = dishDBoperation.getAllDishes();


        final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, values);
        setListAdapter(adapter);

//This is what i tried
 OnItemClickListener listener = new OnItemClickListener() {
  @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(MainActivity.this, Result.class);

                startActivity(intent);
                finish();
            }
         }

Upvotes: 3

Views: 345

Answers (4)

Akshay Bhat &#39;AB&#39;
Akshay Bhat &#39;AB&#39;

Reputation: 2700

Set the ItemClickListener to list view :

listview.setOnItemClickListener(listener);

Upvotes: 2

IntelliJ Amiya
IntelliJ Amiya

Reputation: 75788

Try this way , You can use this

    ListView listView = getListView();

    listView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // Do your Staff Here 

          Intent intent = new Intent(MainActivity.this, Result.class);
          startActivity(intent);
        }
    });

Or

You can use

getListView().setOnItemClickListener(listener);

After setListAdapter(adapter);

Upvotes: 7

npace
npace

Reputation: 4258

You need to actually set the click listener to the ListView. In your onCreate, after the call to setAdapter(adapter), call getListView().setOnItemClickListener(listener);

Upvotes: 1

walkmn
walkmn

Reputation: 2391

In your case, add this line: getListView().setOnItemClickListener(listener);

like this:

OnItemClickListener listener = new OnItemClickListener() {
  @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(MainActivity.this, Result.class);

                startActivity(intent);
                finish();
            }
         }
getListView().setOnItemClickListener(listener);

Upvotes: 1

Related Questions