How to get the selected item from ListView? - android

in my Android app I have created a ListView component called myList, and filled it with objects of my own custom type:
class MyClass{
private String displayName;
private String theValue;
... //here constructor, getters, setters and toString() are implemented
}
I used the ArrayAdapter to bound the ArrayList theObjects with myList:
ArrayAdapter<MyClass> adapter=
new ArrayAdapter<MyClass>(this, R.layout.lay_item, theObjects);
myList.setAdapter(adapter);
This works fine, the list is populated and etc., but when I'm trying to access the selected item, i receive a Null object. I've done this using
myList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
MyClass selItem = (MyClass) myList.getSelectedItem(); //
String value= selItem.getTheValue(); //getter method
}
What seems to be the problem? Thank you

By default, when you click on a ListView item it doesn't change its state to "selected". So, when the event fires and you do:
myList.getSelectedItem();
The method doesn't have anything to return. What you have to do is to use the position and obtain the underlying object by doing:
myList.getItemAtPosition(position);

You are implementing the Click Handler rather than Select Handler. A List by default doesn't suppose to have selection.
What you should change, in your above example, is to
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
MyClass item = (MyClass) adapter.getItem(position);
}

Since the onItemClickLitener() will itself provide you the index of the selected item, you can simply do a getItemAtPosition(i).toString(). The code snippet is given below :-
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String s = listView.getItemAtPosition(i).toString();
Toast.makeText(activity.getApplicationContext(), s, Toast.LENGTH_LONG).show();
adapter.dismiss(); // If you want to close the adapter
}
});
On the method above, the i parameter actually gives you the position of the selected item.

On onItemClick :
String text = parent.getItemAtPosition(position).toString();

myList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
MyClass selItem = (MyClass) adapter.getItem(position);
}
}

Using setOnItemClickListener is the correct answer, but if you have a keyboard you can change selection even with arrows (no click is performed), so, you need to implement also setOnItemSelectedListener :
myListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
MyObject tmp=(MyObject) adapterView.getItemAtPosition(position);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
// your stuff
}
});

In touch mode, there is no focus and no selection. Your UI should use a different type of widget, such as radio buttons, for selection.
The documentation on ListView about this is terrible, just one obscure mention on setSelection.

Though I am using kotlin, the following code answered your question. This return selected item:
val item = myListView.adapter.getItem(i).toString()
The following is the whole selecteditem Listener
myListView.setOnItemClickListener(object : OnItemClickListener {
override fun onItemClick(parent: AdapterView<*>, view: View, i: Int,
id: Long) {
val item = myListView.adapter.getItem(i).toString()
}
})
The code returns the item clicked by its index i as shown in the code

MyClass selItem = (MyClass)
myList.getSelectedItem(); //
You never instantiated your class.

Related

Android how to select id of autocompletetextview inside onitemclick overridden function

I have three autoCompleteTextView box as home , work , other .
So in home autocomplete box i get a data from server and select one item and that item i stored to home_latlong string. Similarly i have to get value from other autocomplete work which i am storing that value in another string called home_latlong. Below code shows onItemClick overridden function where i will store home_latlong or work_latlong.
`
ontemClick(AdapterView<?> adapterView, View view,
int position, long id) {
System.out.println("POSITION ="+position);
for (int i = 0; i < latlong.size(); i++) {
if(i==position){
home_latlong=latlong.get(i);
System.out.println("ARRAY"+latlong.get(i));
}
}
}`
So problem is i am not able differenciate when i will store home_latlong and when to store work_latlong. I tried with id of autocompletetextview but it did not help in this function.
I solved it by using anonymous inner class ,
actv1 = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
actv1 .setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int position,
long id) {
// TODO Auto-generated method stub
for (int i = 0; i < latlong.size(); i++) {
if (i == position) {
home_latlong = latlong.get(i);
System.out.println("ARRAY" + latlong.get(i));
}
}
}
});
Similarly for work_latlong i had another anonymous inner class so i can get which autocompleteview i have clicked.
Check the documentation for AdapterView.OnItemClickListener:
public abstract void onItemClick (AdapterView<?> parent, View view, int position, long id)
Parameters
parent: The AdapterView where the click happened.
view: The view within the AdapterView that was clicked (this will be a view provided by the adapter)
You need to use the first parameter (the AdapterView) to identify the AutocompleteTextView.

List.Remove always removes last item for ListView

When i try to remove a specific item from a list View:
buyButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tempToken -= selPerk.cost;
plrPerks.add(selPerk);
String tokStr = String.valueOf(tempToken);
tkn.setText(tokStr);
shopItems.remove(selPerk);
selPerk = new Perk();
perkDialog.dismiss();
}
});
It always seems to remove the last item. This is where i open the dialog:
perks.setClickable(true);
perks.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Perk perk = (Perk) perks.getItemAtPosition(position);
showItem(perk);
}
});
}
This is the show Item function:
public void showItem(Perk perk) {
if (tempToken >= perk.cost) {
selPerk = perk;
How do i remove a specific item from a list and list view respectively?
Thanks for your time :)
In "setOnItemClickListener" listener, you are getting the perk object. So you can remove that object from your list like this-
shopItems.remove(perk);
and then you can call-
your_adapter.notifyDataSetChanged();
to refresh your listview.
To remove a specific item from a list view, your can call removeView(View toBeRemoved) if you have a reference to the view you wish to remove. If you have the index, you can call removeView(int index).
http://developer.android.com/reference/android/widget/ListView.html
You can remove a specific item from a list in the same way, using remove(Object item) or remove(int index).
http://docs.oracle.com/javase/7/docs/api/java/util/List.html
Hope this helps!
I fixed it. Whenever i removed an item i had to do it like so:
shopItems.remove(selPerk);
perk_adapter.notifyDataSetChanged();
So i had to notify my listeview adapter that i removed an item.

Android OnItemClickListener long id parameter is not giving field id

I have generated a list of customers. On click this should open edit view to edit the customer. Here the parameter should pass the _id of the row according to stored in the database. But everytime passing it's position in the list. So the edit view is opening wrong data. Please help.
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
Uri customerEditUri = Uri.parse(CustomerBean.CONTENT_URI + "/" + id);
customerEdit(customerEditUri);
}
});
Answer:
Thank you all. Your comments helped me to solve this. I have created following function inside my CustomerObject class:
#Override
public String toString() {
return this.name;
}
After that created an array of CustomerObject in activity like following:
List<CustomerObject> customers = new ArrayList<CustomerObject>();
Created ArrayAdapter by following:
adapter = new ArrayAdapter<CustomerObject>(this, R.layout.list, R.id.customer_name, customers);
Finally called setOnItemClickListener() like this:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
CustomerObject custObj = adapter.getItem(position);
Uri customerEditUri = Uri.parse(CustomerBean.CONTENT_URI + "/" + custObj.pkid);
customerEdit(customerEditUri);
}
});
You will have to set the ID you would like it to return in the adapter, the List View Adapter that you used to bind data to the ListView.
If I am not wrong, the method is in the adapter class under the following method name:
public long getItemId(int position) {
return myitem[position].getId();
}
Returning the appropriate ID will get you the results you wanted.
I believe that the "long id" is not the record id but the internally generated view id.
If you want to get back to the datasource id then you need to use position and something like:
// Assuming datasource is an ArrayAdapter<Customer>
Customer customer = customerAdapter.getItemAtPosition(position);
// then you can do
Uri customerEditUri = Uri.parse(CustomerBean.CONTENT_URI + "/" + customer.getId());
customerEdit(customerEditUri);
Replace id with position.
Use
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
Uri customerEditUri = Uri.parse(CustomerBean.CONTENT_URI + "/" + position);
customerEdit(customerEditUri);
}
})
In my opinion, through the position, you can get row item with adapter's getItem(position).
So, the position mean the data position in the adapter.
For the id parameter, I think it is a help method, as you know, the data in adapter always is a recorder. general speaking, a recorder should have an id column(something like the database id). when coding, you can get the item through position, then get the item's id(if the item has id). but you can get such "id" directly with "id" parameter.
By the way, if you want use the id parameter, you have to implement the getItemId() method in adapter. the default implement in ArrayAdapter is just return the position.

Get value of item on OnItemClick Listview

I try to get the value of a selected Item within a custom adapter on a listview. I try this with following code:
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
View curr = parent.getChildAt((int) id);
TextView c = (TextView)curr.findViewById(R.id.tvPopUpItem);
String playerChanged = c.getText().toString();
Toast.makeText(Settings.this,playerChanged, Toast.LENGTH_SHORT).show();
}
At the beginning, if I click, the values are good, but once I scrolled and I click on another Item, I get the wrong value of that clicked item... Any idea what is causing this?
The parameter v is the current row. so use:
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
TextView c = (TextView) v.findViewById(R.id.tvPopUpItem);
String playerChanged = c.getText().toString();
Toast.makeText(Settings.this,playerChanged, Toast.LENGTH_SHORT).show();
}
(Or you could use getChildAt(position) but this would be slower.)
Understand you might be able to simplify this more depending on your layout.
Just Small Change is Required
TextView c = (TextView) v.findViewById(R.id.tvPopUpItem);
Since you are using custom view you need to pass the View argument in your OnItemClickListener then you need to use that value to get the Details of TextViews present in that
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i=new Intent(ListOfAstrologers.this,AstroProForUser.class);
i.putExtra("hello",adapter.getItem(position).getUsername() );
startActivity(i);
}
});
Here username is a string field declared in a class and you must over ride getItem() method in adapter class to get the details of inflated row when you click.
I dont have much experience but I think if you want to pass a variable from an OnClick (which is an anonimous class) to the outside of the onClick and to the other activity, you want to pass it via Intent intent.putExtra... (it's quite easy)
Otherwise you might end up using "public static" variable, which might be a memory leak...

list view issue in android

I am using a custom list view. I have tried to get the value of the row which the user clicked.
Can anybody tell me how to get the value?
Thanks
You may want to implement a new method in your class, specifically onItemClick:
[...]
private ListView lv;
[...]
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
String itemValue = lv.getItemAtPosition(position);
[... do something ...]
}
Then you can do whatever you want with with itemValue.
Hope this helps.

Categories

Resources