I have a listview that working perfet.Today I added a search function to the listview using this code
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
The problem: I have 114 items on my listview and the selected item depends on the position, when I do search and press on the item that I found it will return the position 1, I want to return the position of that item before the search.. not the new position, is there anyway to solve it?!
Nope, it will return the position of the item based on the current lenght of your list view/adapter.
Why would it matter?
If you want to start a different activity based on the item clicked, there are many ways to do it. Using the position in the list to choose the activity works ONLY when the positions are fixed, which is not your case, since the user can filter the items.
Instead, start the activity based on the content of the item clicked.
Say for instance, your listview is populated using the following items:
public static final String [] PLANETS = {
"Mercury",
"Venus",
"Earth",
"Mars",
"Jupiter",
"Saturn",
"Uranus",
"Neptune",
};
Using the following ArrayAdapter:
mAdapter = new ArrayAdapter<String>(this, R.layout.simple_list_item_1, R.id.text1, PLANETS);
Then you can edit your OnItemClickListener to start the activity based on the actual planet selected, not the position selected.
private AdapterView.OnItemClickListener mOnPlanetOnItemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int iistPosition, long l) {
//Notice I don't get the value from the String array
//Rather, I tell the adapter to give me the text from the selected item.
String planet = mAdapter.getItem(iistPosition);
Intent newActivity = new Intent(Example.this, NextActivity.class);
newActivity.putExtra("planet", planet);
}
};
If you are using a custom adapter it's even easier.
EDIT It is unfortunate that because of the way your mp3 files are named you must depend on the list position to get appropiate file.
In that case you could try a few workarounds, for instance:
If your list view is populated with a set ArrayList or just a List, you could first get the text of the item selected, and then get the actual array position based on the text of the item selected.
Like this:
private AdapterView.OnItemClickListener mOnPlanetOnItemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int iistPosition, long l) {
//get the text of the current item
String planet = mAdapter.getItem(iistPosition);
//get the position of this planet in the original unfiltered array
int actualListPosition = PLANETS_ARRAY.indexOf(planet);
//handle the click based on the actualListPosition
}
};
I hope that helps
Related
I created 2 Spinners and I to fill them with an array of numbers. What I want is that the user chooses the number they want on the first one, and then I save it to a variable that I use to populate the dropdown list of the second one with values that start with that number. How can I do this?
How can I change the text in the second spinner to start with the number chosen.
I have this, I store the item of the Spinner on the variable x, and I want a second Spinner to start with that variable.
mySpinner
.setAdapter(new ArrayAdapter<String>(NewGuiaActivity.this,
android.R.layout.simple_spinner_dropdown_item,
establist));
// Spinner on item click listener
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// Locate the textviews in activity_main.xml
x = estab.get(position).getID();
Toast.makeText(getApplicationContext(), x,
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
If I understand what you want to do correctly, for example if you select the number 4 from the drop down of spinner1, you want spinner2 to be set to the 4th position in it's list:
Try something like this, say you have mySpinner1 and mySpinner2, let your class implement OnItemSelectedListener and give it a class variable private int spinner2Pos = 0;
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
Spinner spinner = (Spinner) parent;
if(spinner.getId() == case R.id.spinner_1_id){
spinner2Pos =
(spinner.getItemAtPosition(position) < mySpinner2.getAdapter().getCount())?
spinner.getItemAtPosition(position): 0;
mySpinner2.setSelection(spinner2Pos);
}
}
This should set mySpinner2 to the item you select with mySpinner1, which is stored as a class variable spinner2Pos. I haven't had time to check it so let me know if there are errors.
I have populated a list view. which show up like
123 apple
456 Linux
789 windows
I have also added onItemClick listener to it and by displaying toast I can check the id of pressed listview. As I have a long list of approx. 1000 items, I want that if item 1 is clicked I should get the listview. some thing like
String clicked_Item = 123 apple.
how can I do it. here is my itm listener.
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long id) {
Toast.makeText(getActivity(), "item clicked id="+id, Toast.LENGTH_LONG).show();
}
});
In your adapter, you should have a method called getItem(position)
So, in your onItemClickListener, the int arg2 means the position of the list that was clicked.
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long id) {
Object object = adapter.getItem(position);
Toast.makeText(getActivity(), "item clicked id="+id, Toast.LENGTH_LONG).show();
}
});
So, this object might be your model, wich means that this object has every information you want. So, just take what you want.
i am trying to get index of the list item, through which i can set different views for different items in another activity. Here is my code..
String description[] = {"inspiron","pavilion","macbook"}; /* i want this list on another activity after clicking listitem of first activity.*/
ArrayList<String> listDesc = new ArrayList<String>();
String ArrayDesc[] = null;
ListView listViewDesc;
ArrayAdapter<String> listAdapterDesc;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.category);
for(int i = 0;i<description.length;i++)
{
listDesc.add(description[i]);
}
ArrayDesc = (String[]) listDesc.toArray();
listAdapterDesc=newrrayAdapter<String>this,android.R.layout.simple_spinner_item,ArrayDesc);
listViewDesc.setAdapter(listAdapterDesc);
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
lstView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> a,View v, int i, long l)
{
/*here i want some code to extract list item index from list to set
different lists according to the item click on another view.*/
Intent intent = new Intent(getApplicationContext(), categorySelected.class);
startActivity(intent);
}
});
From your comments You say
please show me the code if any item from the list is clicked its index number will pop-up (in Toast)
So Try the below
public void onItemClick(AdapterView<?> a,View v, int i, long l)
{
Toast.makeText(getApplicationContext(),"Index of the item clicked is"+i,Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), categorySelected.class);
startActivity(intent);
}
In my android app my search function works, the list gets correctly populated, but the items are not clickable. I'm trying to get that to work. Here's my code, can anyone see why the items are not clickable?
private void showResults(String query) {
Cursor cursor = DBHelper.searchDB(query);
startManagingCursor(cursor);
String[] searchFrom = new String[] { DBAdapter.KEY_TITLE,
DBAdapter.KEY_YEAR, DBAdapter.KEY_MAKE,
DBAdapter.KEY_MODEL };
int[] displayHere = new int[] { R.id.rTitleTV, R.id.rYearTV,
R.id.rMakeTV, R.id.rModelTV };
SimpleCursorAdapter records = new SimpleCursorAdapter(this,
R.layout.record_2, cursor, searchFrom, displayHere);
setListAdapter(records);
DBHelper.close();
// --- Click on list item ---
ListView clickList = getListView();
clickList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
}
});
// --- END click on list item ----
}
I just want to get the onClick to work, I don't care that it doesn't do anything at the moment. I'll put that functionality in later.
An example of record_2.xml:
<TextView
android:id="#+id/rMakeTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Make"
android:textColor="#000000"
android:textSize="16dp"
android:textStyle="bold" >
</TextView>
I've tried this, based on what Sam is pointing out, but the list items are still not clickable.
// --- Click on list item ---
AdapterView<?> clickList = getListView();
clickList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
}
});
// --- END click on list item ----
It seems to me that since there's no reference to the records ListAdapter in the setOnItemClickListener it won't work?
You aren't doing anything in your onItemClick() method, how will you know if it is working (unless you are using the debugger)? Since your code looks fine, try something simple like this:
ListView clickList = getListView();
clickList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Log.v("Test", "A row was clicked with OnItemClick!");
}
});
Watch your logcat for these messages.
Try this. Remove AdapterView before OnItemClickListener in the method setOnItemClickListener(). Or replace AdapterView with simple View
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