Get ID or position of listview text - android

I have a problem with my Listview with 3 textviews when I use a ClickListener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
...
}
I can't find out which textview is clicked.
And when I use a onClick-Method with
<TextView
android:id="#+id/listview_text3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="onClickMenge"/>
and
public void onClickMenge(View view) {
...
}
I know which textview is clicked but I canĀ“t get the id (Database-ID).
I read and tried but with no success.
Any ideas?

If I understand your issue here:
If you have data in your database tables, you simply need to create a class like this :
public class ListItem {
//define variables here
private long id;
private String itemName;
//define constructor and getters and setters here;
}
Now, when you provide the data to your adapter, you pass to each object instance an id;
Next, when a user clicks on the item in your list, you use the position provided to you by the onClickListener interface, to get the item from your Adapterthen get the id as you wish!
I hope this makes sense and helps you get the solution!

You can use your Cursor to find the id, using the position that onClickListener returns.
(...)
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String[] column = new String[]{"_id"};
Cursor cursor = db.query("name_of_table", column, null, null, null, null, null, null);
cursor.move(position+1);
long id = cursor.getLong(0);
(...)
You need to connect your database with variable db.
private SQLiteDatabase db;
BDCore xDB = new BDCore(context);
db = xDB.getWritableDatabase();

The int position in the on item click listener is the position of ur text view it starts from 0,1,2,3
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(pos==0)
{
TextView txt = (TextView) findViewById(R.id.text_1);
txt.setText("abc");
}
}
});

Use onClick and position from getView method of your adapter
int itemPosition = -1;
Now set itemPosition in getView method
#Override
public View getView(int position, View convertView, ViewGroup parent) {
itemPosition = position;
}
public void onClickMenge(View view) {
int viewId = view.getId();//ID of text view clicked
//Use itemPosition now
}

Related

How do I change a list item text for a ListFragment/ArrayAdapter?

I have a fragment which extends ListFragment.
In it I use an ArrayAdapter
public class MyFragment extends ListFragment {
public void onStart() {
super.onStart();
List<String> list = new ArrayList<String>();
list.add("Superman");
list.add("Batman");
arrayAdapter = new ArrayAdapter<OptionToStringAdapter>(
getActivity(),
android.R.layout.simple_list_item_1,
list);
getListView().setAdapter(arrayAdapter);
getListView().setOnItemClickListener(new ModifyOption(this));
setListShown(true);
}
When the user taps an item I want to modify the text.
How do I modify the text?
public class ModifyOption implements OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
???What goes here????
}
}
Assuming you want to change the content of the list item you clicked.
First, change the value using a dialog or widget of your choice.
Second, change the value of the item at the position in the list by using 'position' argument.
Third, call notifyDataSetChanged() method of the adapter object.
public class ModifyOption implements OnItemClickListener {
public void onItemClick(AdapterView parent, View view, int position, long id) {
// create a dialog or other widget
String newValue = "your_new_value";
list.set(position,newValue);
arrayAdapter.notifyDataSetChanged(); //informs views that data has been changed
}
}
try with below code:
public class ModifyOption implements OnItemClickListener { public void onItemClick(AdapterView parent, View view, int position, long id) {
arrayAdapter.remove(arrayAdapter.getItem(position));
arrayAdapter.insert("new text",position);
} }
This seems to do the trick. I don't know if this is an appropriate way though.
public void onItemClick(AdapterView parent, View view, int position, long id) {
TextView textview = (TextView) view.findViewById(android.R.id.text1);
textview.setText("Spiderman");
}

Android: how to get AutoCompleteTextView inside onItemClick

I'm trying to get an AutoCompleteTextView's ID after I clicked a value on the list. Tried looking up on google and stackoverflow, but the provided answers didn't work. Here's what I've got:
Created the view in my class declaration:
public class ActivityCadastrarCliente extends Activity implements OnClickListener, OnItemClickListener {
AutoCompleteTextView E_Nome_Cliente, E_CPF;
List<String> Nomes = new ArrayList<String>();
...
Associated the view to an XML element:
E_Nome_Cliente = (AutoCompleteTextView)findViewById(R.id.Nome_Cliente);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, Nomes.toArray(new String[0]));
E_Nome_Cliente.setAdapter(adapter);
E_Nome_Cliente.setOnItemClickListener(this);
and my onItemClick method is called normally as below:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//switch (parent.getId()) {
//case R.id.Nome_Cliente:
...
//}
}
Does anybody know how I can access this view inside onItemClick? Tried several ways, but I only get exceptions:
//Class cast exception
AutoCompleteTextView input = (AutoCompleteTextView)view.getParent();
//Class cast exception
AutoCompleteTextView input = (AutoCompleteTextView)parent;
//Class cast exception
AutoCompleteTextView input = (AutoCompleteTextView)parent.getParent();
I need to identify which view was clicked, because I'm using 3 to 5 AutoCompleteTextView and based on the selected value I'll automatically fill in a bunch of other fields.
Have a look at the class AutoCompleteTextViewClickListener in this answer.
Change your setOnItemClickListener call in the following way:
E_Nome_Cliente.setOnItemClickListener(
new AutoCompleteTextViewClickListener(E_Nome_Cliente, this));
Now you can get the id by accessing the modified view parameter:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//view had been modified by AutoCompleteTextViewClickListener
//to contain the original AutoCompleteTextView
switch (view.getId()) {
case R.id.Nome_Cliente:
//...
}
}
An easier way:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Adapter adapter = parent.getAdapter();
if (adapter == autoCompleteTextView1.getAdapter()) {
// Do something
} else if (adapter == autoCompleteTextView2.getAdapter()) {
// Do something else
}
}
i am not sure what do you mean by view id? do you want to get the selected value?
if yes, then the below code will do it, otherwise please clarify more what do you need and why you want to access the view itself.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//switch (parent.getId()) {
String selected = adapter.getItem(position);
//}
}
more on adapter methods are here
Use parent.findViewById(R.id.id_of_autocompleteTextView) on the parent of the AutoCompleteTextView.

Trying to get String from ListView

My current problem is I have a ListView I'm using to display my contacts now I'd like to set the onItemClick to grab the name of the contact and set that to a TextView called p2 the code I currently have is:
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.setp2);
cursor = managedQuery(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
String[] from = new String[]{ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME};
int[] to = new int[]{R.id.id_text,R.id.name_text};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(setp2.this,R.layout.setp2_layout,cursor,from,to);
ListView list = (ListView)findViewById(R.id.contact_list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
}
});
}
So basically I'm unsure of what I need to do in the onItemClick, any help appreciated!
In your onItemClick, you will get the instance of the view associated with that list item.From that view you can get the text associated with it and set it to the p2 TextView. If my understanding of your requirement is correct, the code will be something like this:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
CharSequence name = ((TextView)view.findViewById(R.id.name_text)).getText();
//Set this to your textview in P2
tvP2.setText(name);
}
});
Set up a SimpleCursorAdapter.CursorToStringConverter and set it on the adapter, then use convertToString(Cursor cursor) to get the text in on item click :
(Cursor) simple.getItem(position)
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
cursor.moveToPosition(position);
String name = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
p2.setText(name);
}
});

Android - Populate a textview from a Spinner item

I would like to have my application populate an empty textview with the value that a user selects from a spinner. Currently it seems to work, but it only populates the textview with what I'm guessing is the entire cursor: (android.database.sqlite.SQLiteCursor#4120dd08).
Can someone help me figure out what the issue is? I can post more code if necessary.
// Set spinner listener to populate the description field onclick.
mContext = this;
commonDescSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
String stringItem = parent.getItemAtPosition(position).toString();
mDescriptionText.setText(stringItem);
}
public void onNothingSelected(AdapterView<?> parent) {}
});
Try this:
// Set spinner listener to populate the description field onclick.
mContext = this;
commonDescSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
TextView objTextView = (TextView) commonDescSpin.getSelectedView();
String stringItem = objTextView.getText().toString();
mDescriptionText.setText(stringItem);
}
public void onNothingSelected(AdapterView<?> parent) {}
});
The method toString() usually has other implementations relating to identifying object instances. If you know that the item in the spinner is without a doubt a string, you could consider performing an explicit cast:
String stringItem = (String)(spinner1.getItemAtPosition(2));
textViewStatus.setText(stringItem);

How to get text from AutoCompleteTextView?

I have an AutoCompleteTextView in my app which works. I have successfully created an onClickItemListener. The question is how to grab the text the user selected.
And this is the thing: I have an ArrayList with words being passed to the Adapter to search for suggestions. As the user types a word the suggestions list gets shorter (in rows on the UI side) so when i want to get the word from the ArrayList at the index the user selected i get the wrong word because the indexes doesn't match.
How can I get the text (String) the user chose without having to mess with the index?
Here's my code:
public class AutocompleteActivity extends BaseActivity {
private DBManager m_db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.autocomplete);
m_db = new DBManager(this);
final ArrayList<String> words = m_db.selectAllWords();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.listitem, words);
AutoCompleteTextView tv = (AutoCompleteTextView)findViewById(R.id.autocomplete);
tv.setThreshold(1);
tv.setAdapter(adapter);
tv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Log.i("SELECTED TEXT WAS------->", words.get(arg2));
}
});
}
}
Yeah... unfortunately the name of the parameters on the onItemClick method you must implement are not so self-descriptive but here is an example with the names of what they are:
autoCompleteTextView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
String selection = (String)parent.getItemAtPosition(position);
//TODO Do something with the selected text
}
});
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)
position The position of the view in the adapter
id The row id of the item that was clicked.
For more info see: http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html
arg0 being your AdapterView and arg2 the position.
Have you tried:
arg0.getItemAtPosition(arg2);
I think what you are looking for is this.
String s = this.mCountry.getEditableText().toString();
Where mCountry is the AutoCompleteTextView.
this.mCountry = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
ArrayAdapter<String> adapterCountry = new ArrayAdapter<String>(this, R.layout.list_item, countries);
this.mCountry.setAdapter(adapterCountry);
mCountry is the list of countries, and I wanted to save the country selected in SharedPreferences.
Hope this helps.
Easiest of all
For Getting text of the selected suggestion in AutoCompleteTextView use this
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("========>>", autoCompleteTextView.getText().toString());
}
});
try this:
txtPurpose.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Purpose selected = (Purpose) arg0.getAdapter().getItem(arg2);
txtPurpose.setTag(selected);
}
});
One another of getting text of suggestion selected in AutoCompleteTextView is
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
TextView txtvw=(TextView) view;
String str=txtvw.getText().toString();
int index = contactNames.indexOf(str);
}
Here is the code that will solve the problem.
private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
int index = (int) view.getTag();
Object item = parent.getItemAtPosition(index);
if (item instanceof SearchItemShareConnectionDAO) {
SearchItemShareConnectionDAO dao = (SearchItemShareConnectionDAO) item;
}
}
};
SetTag(Dao.getPosition) in getView() method of adapter.
To get the text of the displayed item selected by the user
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String selectedItemText = arg0.getItemAtPosition(arg2);
Log.i("myTag", "SELECTED TEXT WAS["+selectedItemText+"]);
}
Following best practices, please use some form of descriptive nomenclature for your variables, your code will make more sense:
public void onItemClick(AdapterView<?> adapterViewIn, View viewIn, int selectedItemIndexIn, long id)
There is also a way to get item outside the onItemClick:
int index = tv.getListSelection();
if (index != ListView.INVALID_POSITION) {
Object item = tv.getAdapter().getItem(index);
}
beware that int getListSelection() may return ListView.INVALID_POSITION if there is no dropdown or if there is no selection.
For me, but on setOnItemSelectedListener():
arg0.getSelectedItem();
was enough. The same should work on setOnItemClickListener() I guess.
Kotlin version
autoCompleteId.setOnItemClickListener { parent, view, position, id ->
val selectedItem = parent.getItemAtPosition(position).toString()
Log.d("SELECTED ITEM", selectedItem )
}
Output:
D/CLASSROOM: selectedItem

Categories

Resources