How to extract the text from the selected item on the listView
Asked Answered
B

14

45

I have a listview with some items. I would like to get the text from the selected item.

Here is my list adapter and the onItemClickListener:

ListView lv = (ListView)findViewById(R.id.listView1);
    lv.setAdapter(new ArrayAdapter<Country>(
            this,R.layout.list_black_text,R.id.list_content, values));


    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
??????
    }});
        }

Could you tell me please how to get the String from the selected item.

the method ((TextView) view).getText() does not work, i have a

ClassCastException: android.widget.LinearLayout

I have found the solution, maybe somebody will need it:

ListView lv = (ListView)findViewById(R.id.listView1);
    lv.setAdapter(new ArrayAdapter<Country>(
            this,R.layout.list_black_text,R.id.list_content, values));

    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
            TextView textView = (TextView) view.findViewById(R.id.list_content);
            String text = textView.getText().toString(); 
            System.out.println("Choosen Country = : " + text);

    }});
Barcus answered 9/2, 2012 at 10:6 Comment(0)
I
70

Use this:

String selectedFromList = (String) (lv.getItemAtPosition(position));

Whatever the datatype you are having in your list, cast accordingly.

Hope it will help. :)

Infuse answered 9/2, 2012 at 10:15 Comment(4)
Nice and simple Answer ! =)Arrant
If you have just strings being put in to your adapter then you should have no problem doing the above, just cast it as a string to avoid any errors. String alloy = (String) lv.getItemAtPosition(position);Sporty
Edit: String selectedFromList = (String) lv.getItemAtPosition(position);Hardbitten
@AliObeid edited as per your suggestion. @ ColossalChrisInfuse
V
17

For this you need to write the following:

lv.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
        TextView textView = (TextView) view.findViewById(R.id.list_content);
        String text = lv.get(position).toString().trim();
        System.out.println("Chosen Country = : " + text);

}});
Vicar answered 9/2, 2012 at 10:18 Comment(0)
S
6

The other answers look good, but I thought I'd wrap everything up into one complete answer.

There are multiple ways to achieve this and it also depends on whether you are getting text from simple listView or from Custom ListView(with custom_list_item.xml).

For Simple ListView

lv.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
        String text = lv.get(position).tostring().trim();//first method 
        final String text = ((TextView)view).getText();// second method
}});

For Custom ListView

lv.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
        TextView textView = (TextView) view.findViewById(R.id.list_content);
//where list_content is the id of TextView in listview_item.xml

}});

Problem with others Answers

@Android Killer string Casting is missing.

@Rishi doesn't give detail about using R.id.list_content

Schizopod answered 12/2, 2015 at 14:9 Comment(2)
why is "get" in red?Valuable
@Valuable you need to use lv.getItemAtPosition(position) insteadJennette
O
3

Hello I'm using a CustomListView with Registered Context Menu. In this case the way to access a item inside a custom list row will be:

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    switch (item.getItemId()) {
        case R.id.add:
                TextView textView = (TextView) info.targetView.findViewById(R.id.yourItem);
                String text = textView.getText().toString();
                Toast.makeText(getApplicationContext(), "Selected " + text, Toast.LENGTH_LONG).show(); 
        default:
                return super.onContextItemSelected(item);
    }
}

Where R.id.yourItem is the textView inside the custom Row

PS: It's my first post, Hope it helps ;-)

Oppress answered 1/9, 2016 at 16:34 Comment(0)
E
2

Here's for future reference for anyone that stumbles on this. In my case I had a custom adapter class, with type as a POJO class I had. Also the items I wanted to pass to the adapter and display in my ListView where of the util.List class.

I successfully passed the data to the ListView, but also wanted to get the text of the currently selected.

Eg: the data I passed was a list of schools that a lecturer taught at, so he had to select the particular school he wanted to work with at that time, and on logging in I wanted to pass an intent to a new Activity with the current school the lecturer had selected.

Thus my ListView onClick():

private void loginSuccess() {
    progressDialog.dismiss();
    if (mySchoolsList.size() > 1) {
        schoolsListView = new ListView(MainActivity.this);
        schoolsArrayAdapter = new SchoolListAdapter(MainActivity.this, android.R.layout.simple_list_item_1, mySchoolsList);
        schoolsListView.setAdapter(schoolsArrayAdapter);

        dialog = new Dialog(MainActivity.this);
        dialog.setContentView(schoolsListView);
        dialog.setTitle("Welcome " + staff.getFullName());
        dialog.show();


        schoolsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //the .getName() is accessed from the School POJO class.
                String schoolName = schoolsArrayAdapter.getItem(position).getName();
                intent = new Intent(MainActivity.this, NavMainActivity.class);
                intent.putExtra("sentIntent", schoolName);
                startActivity(intent);
            }
        });

    } else {
        intent = new Intent(MainActivity.this, NavMainActivity.class);
        intent.putExtra("sentIntent", recieveName);
        startActivity(intent);
    }
}

Hope this saves someone someday, because all the solutions here didn't work for me. Cheers!

Evelinaeveline answered 5/5, 2016 at 14:47 Comment(0)
D
2

It will definitly works!Hope you Satisfied!

ListView lv=(ListView)findViewById(R.id.listView1);

lv.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        // TODO Auto-generated method stub
        String text = (String) lv.getItemAtPosition(arg2);
        Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();

    }
});
Donata answered 14/6, 2016 at 14:4 Comment(0)
T
0

If you are using a List to populate the ListView in your onItemClick() method.

String s = list.get(position);

You need to be able to access this list within the inner class

Trilbee answered 9/2, 2012 at 10:14 Comment(1)
Unfortunetly, I am using a database query to populate my list. I have found the solution and edited the question.Barcus
I
0

try doing it by this, insert it into onItemClickListener, i am not sure what does your Country class look like:

String s = values.get(position).getCountryName();
Log.e("LISTVIEW", "selected item text = "+s);

  or

String s = values.get(position).toString();
Log.e("LISTVIEW", "selected item text = "+s);
Ixion answered 9/2, 2012 at 10:17 Comment(0)
L
0
public void onItemClick(**AdapterView**<?> parent, View view, 
                                            int position, long id) {

 }

See the AdapterView.....--->>>the class

Only need to do this :

  TextView selectedText=(TextView) parent.findViewById(R.id.textView2);

See...you get the TextView directly

Ludovika answered 12/2, 2017 at 2:23 Comment(2)
and this can use in FragmentLudovika
Welcome to Stack Overflow! While you may have solved this user's problem, code-only answers are not very helpful to users who come to this question in the future. Please edit your answer to explain why your code solves the original problem.Warrigal
L
0

Try this code:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
     @Override
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
         Toast.makeText(getApplicationContext(),(String)parent.getItemAtPosition(position),Toast.LENGTH_SHORT).show();
     }
});
Lonnielonny answered 15/8, 2018 at 18:28 Comment(0)
S
0
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> av,
                                View view, int position, long l) {
            String text = String.valueOf(myListView.getItemAtPosition(position));

            }
        }
    });
Sanhedrin answered 17/2, 2019 at 2:15 Comment(0)
M
0

It is as simple as that

@Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            TextView text1 = (TextView) findViewById(R.id.Text1);
            TextView text2 = (TextView) findViewById(R.id.Text2);

            String txt_1 = ""+text1.getText().toString().trim();
            String txt_2 = ""+text2.getText().toString().trim();

           //Other_Related_Work

        }
    });
Mastersinger answered 2/4, 2019 at 19:27 Comment(0)
S
0

I found a simplest way:

list_content.xml

 <TextView
    <!-- rest of the code -->
    android:id="@+id/content"
    android:onClick="get_content"  <!-- Just add this -->
    />

MainActivity

public void get_content(View view){

    TextView textView = view.findViewById(R.id.content);
    System.out.println("Text is: "+textView.getText().toString());
}
Sharla answered 27/3, 2020 at 13:6 Comment(0)
D
0

This worked for me. I had tried some solutions here but they hadn't worked. Hope this helps.

ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myFamily);

    listViewDemo.setAdapter(arrayAdapter);

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

            //String nameSelectedfromList = arrayAdapter.getItem(position).toString();
            String nameSelectedfromList = listViewDemo.getItemAtPosition(position).toString();

            Log.i("Clicked Item", nameSelectedfromList);

        }
    }); 
Downwash answered 28/5, 2020 at 18:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.