Is there a way to store the ListView item number in an int in Android?

Viewed 143

I imported a text file into a ListView in android.

If I click an item in listView, it's line number should be stored in an int.

For example (this is a ListView (text file)):

Corn (1)
Apple (2)
Melon (3)

If a line is clicked for example Melon, it's line number (3) should be stored in an int.

The code:

// returns index to -1

  list.setOnItemClickListener(new AdapterView.OnItemClickListener() {


                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {



                        boolean co = true;

                        int lineNumber = list.getSelectedItemPosition();

                        Toast.makeText(MainActivity.this, String.valueOf(lineNumber), Toast.LENGTH_SHORT).show();

                    }
                });

Is that possible?

3 Answers
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Toast.makeText(MainActivity.this,"Item No:"+position,Toast.LENGTH_SHORT).show();
            }
        });

Note Item index start with 0.

Method like this may also help you

listView.getSelectedItemPosition()
listView.getCheckedItemPosition()

Note: This above two line is not meant for item click.

First of all, ListView index starts from zero, so the index should be like this

Corn (0)
Apple (1)
Melon (2)

And easily you can get the position of the selected item as it's declared as a parameter in

public void onItemClick(AdapterView<?> parent, View view, int position, long id)

And also you can get the name of the selected item by this line in onItemClick()

                @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                // TODO: Implement this method
                String title = parent.getItemAtPosition(position);
            }

I just used int position included in the method:

 public void onItemClick(AdapterView<?> parent, View view,
                                             int position, long id)

Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_SHORT).show();
Related