I have a spinner which starts a second activity on a value change. This works good.
After a return everything works fine too. But if I rotate now the mobile the OnItemSelectedListener is called! Why? The spinner should be on position -1. Which means that the callback will not be called.
How does android know which spinner item is selected? I tried to prevend to restore this information by sending the base class the a null value for the savedInstanceState.
Here is some code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(null);
setContentView(R.layout.menu);
String db=MyDatabase.getData();
if(db == null)
db="";
Spinner spinner=(Spinner)findViewById(R.id.spinner);
MyAdapter adapter=new MyAdapter(this, db, "ID", "Name");
spinner.setAdapter(adapter);
adapter.setHint(spinner, "Please select...");
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id2) {
int id=((SpinnerItem)parent.getAdapter().getItem(position)).getId();
Intent intent=new Intent();
intent.setClass(MainMenu.this, Other.class);
intent.putExtra("id", id);
startActivity(intent);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
Here is my adapter:
public class MyAdapter extends ArrayAdapter<SpinnerItem> {
private final Context context;
private String hint;
public MyAdapter(Context context, String input, String key, String value) {
super(context, android.R.layout.simple_spinner_item, create(input, key, value));
this.context=context;
}
private static SpinnerItem[] create(String input, String key, String value) {
Vector<SpinnerItem> list=new Vector<SpinnerItem>();
// fill the list
return list.toArray(new SpinnerItem[] {});
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// show the hint
if(position == -1) {
TextView tv=new TextView(context);
tv.setTextColor(Color.DKGRAY);
tv.setText(hint);
return tv;
}
return super.getView(position, convertView, parent);
}
public void setHint(Spinner spinner, String hint) {
if(spinner.getAdapter() == null) {
throw new IllegalStateException("Set your adapter first!");
}
this.hint=hint;
try {
final Method m=AdapterView.class.getDeclaredMethod("setNextSelectedPositionInt", int.class);
m.setAccessible(true);
m.invoke(spinner, -1);
final Method n=AdapterView.class.getDeclaredMethod("setSelectedPositionInt", int.class);
n.setAccessible(true);
n.invoke(spinner, -1);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
When you rotate your device your Activity gets restarted or recreated add this line to your AndroidManifest file in activity tag to avoid it.
android:configChanges="keyboardHidden|orientation"
When you change the orientation the onCreate() of Activity get Called.
and by default as the behaviour of the spinner the method onItemSelectedListener() get called of the spinner when ever the activity gets created.
So this is happening to you in this case
Solution for such issue is given here StackOverflow Question's Link check how he handled the issue by taking two counters checkBoxCounter and checkBoxInitialized and try to implement same in your case.
Related
I have an activity Advanced Research, with a spinner that contains all category from my db. When i create the activity, this spinner call onSetItemListener in loop. Why?
I try to use onTouchListener but not working, maybe i fail something.
if(risultato.getCategoria().getSottocategorie().toArray() != null && risultato.getCategoria().getSottocategorie().toArray().length != 0){
adapterSpinnerCategoria = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, risultato.getCategoria().getSottocategorie().toArray());
}else{
adapterSpinnerCategoria = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, categoriaVuota);
}
spinnerCategoria.setAdapter(adapterSpinnerCategoria);
public void spinnerChange(AdapterView<?> parent){
if(!parent.getSelectedItem().toString().equals("Sottocategorie vuote")) {
ricercaAvanzata.setCategoria((Categoria) parent.getSelectedItem());
setArticoli();
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
spinnerChange(parent);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
return;
}
public void setListener() {
spinnerCategoria.setOnItemSelectedListener(this);
}
public class ActivityRicercaAvanzata extends AppCompatActivity implements AdapterView.OnItemSelectedListener { .... }
I expect that when i click on spinner call onItemSelected not before
i am using Spinner for Country Selection for User Registration.
please vote my answer.
Spinner spcountry;
String country;
//in onCreare
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
spcountry = (Spinner) findViewById(R.id.country);
final String[] countryNames = getResources().getStringArray(R.array.countries_array);
ArrayAdapter aa = new ArrayAdapter(this, android.R.layout.simple_spinner_item, countryNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spcountry.setAdapter(aa);
spcountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.v("item", (String) parent.getItemAtPosition(position));
if (position == 0) {
return;
} else
country = countryNames[position];
//Toast.makeText(getBaseContext(),country,Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
From what I can see, you are extending AdapterView.OnItemSelectedListener.
You cannot extend it since OnItemSelectedListener is an interface, not a class.
What you actually should be doing is, implementing it instead, like so:
MyActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
}
Then you can set the OnItemSelectedListener on the Spinner,
spinnerCategoria.setOnItemSelectedListener(this);
And the final step would be to write the implementation for the overridden methods,
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Your implementation here
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
//Your implementation here
}
Ok, mark as solved thx. I create a new List and i convert my set into list. After this operation i add a null element at first position, and when i'm call onItemSelected, i do
if(position != 0)then
//do something
Activity start always at position 0 then must wait my click and my choice. Thx all for help me.
I am having issues trying to restore state of Android Spinners in my application. Currently there are multiple Spinners in my Activity's ListView header that depend on one another, as the selection of one Spinner loads data for the subsequent Spinner.
The problem I am experiencing is, restoring state doesn't seem to work when I manually set selections on the Spinners. I have tried in both onRestoreInstanceState and onResume. It appears setting the selections is asynchronous when looking at the LogCat output. How can I reliably restore state of these Spinners when I have to wait for one to be selected before the other can populated and then set?
EDIT: Added code
Activity's onCreate():
mSecondSpinner = mMyListHeader.findViewById(R.id.second_spinner);
mSecondSpinnerArrayAdapter = new SecondArrayAdapter(MyActivity.this, R.layout.second_spinner_item, new ArrayList<MySecondDto>());
mSecondSpinner.setAdapter(mSecondSpinnerArrayAdapter);
mSecondSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
MySecondDto selectedMySecondDto = (MySecondDto) parent.getItemAtPosition(position);
List<MyThirdDto> myThirdDtos = selectedMySecondDto.getMyThirdDtos();
// Load third spinner with dtos....
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}}
);
mFirstSpinner = mMyListHeader.findViewById(R.id.first_spinner);
mFirstSpinnerAdapter= new FirstArrayAdapter(MyActivity.this, R.layout.first_spinner, mResponse.getAllDtos());
mFirstSpinner.setAdapter(mFirstSpinnerArrayAdapter);
mFirstSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mSecondSpinner.setAdapter(null);
MyFirstDto selectedMyFirstDto = (MyFirstDto ) parent.getItemAtPosition(position);
List<MySecondDto> mySecondDtos = selectedMyFirstDto .getMySecondDtos();
mSecondSpinnerArrayAdapter.clearAndReplaceAll(mySecondDtos);
mSecondSpinner.setAdapter(mSecondSpinnerArrayAdapter);
// If there is only one second dto, disable the spinner
if (mySecondDtos== null || mySecondDtos.size() <= 1)
{
disableSpinner(mSecondSpinner);
}
else
{
// Enable second spinner, select the hint element
enableSpinner(mSecondSpinner);
mSecondSpinner.setSelection(mSecondSpinnerArrayAdapter .getHintIndex());
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
});
Activity's onRestoreInstanceState():
mFirstSpinner.setSelection(mFirstAdapterPosition);
mFirstSpinnerArrayAdapter.notifyDataSetChanged();
mSecondSpinner.setSelection(mSecondAdapterPosition);
mSecondSpinnerArrayAdapter.notifyDataSetChanged();
Have u tried this
mySpinner.post(new Runnable() { #Override public void run() { mySpinner.setSelection(position); } });
This might work for you.
There could be a bug in it somewhere, so be careful.
I have a similar situation to you but I had 3 spinners and they get populated depending on the selection of the previous one.
The idea is to store the Indexes/Positions of the Spinners in IndexVariables.
Theses Variables have default value of -1.
Store current values in onSaveInstanceState,
Restore values in onActivityCreated.
In onItemSelected check if selected Item = null, check if the IndexVariable was set (i.e. !-= -1)
If so use it to set Spinner then set IndexVariable back to -1;
Here's the class
(I used NothingSelectedSpinnerAdapter from How to make an Android Spinner with initial text "Select One".
Not really important but just giving a shout out to the guy/girl where I got that code.)
public class SpinnerTestFragment extends Fragment {
private MainActivity activity;
private static final String SELECTED_THEME_IDX_STORAGE_KEY = "mSelectedTheme_IDX_StorageKey";
private static final String SELECTED_AIM_IDX_STORAGE_KEY = "mSelectedAim_IDX_StorageKey";
private static final String SELECTED_GOAL_IDX_STORAGE_KEY = "mSelectedGoal_IDX_StorageKey";
private static String TAG = "SpinnerTestFragment";
private Spinner spnrThemes;
private Spinner spnrAims;
private Spinner spnrGoals;
private String mSelectedTheme;
private String mSelectedAim;
private String mSelectedGoal;
private int mSelectedAimIdx = -1;
private int mSelectedThemeIdx = -1;
private int mSelectedGoalIdx = -1;
//----------------------------------------------------------------------------------------//
public SpinnerTestFragment() {
}//ctor
//----------------------------------------------------------------------------------------//
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "onCreateView");
activity = (MainActivity) getActivity();
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_photo, container, false);
spnrThemes = view.findViewById(R.id.spnrThemes);
spnrAims = view.findViewById(R.id.spnrAims);
spnrGoals = view.findViewById(R.id.spnrGoals);
setSpinner(spnrThemes, "Select Theme", ThemesAimsGoals.getThemes());
spnrThemes.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object selectedItem = parent.getItemAtPosition(position);
if (selectedItem != null) {
mSelectedTheme = selectedItem.toString();
setSpinner(spnrAims, "Select Aim", ThemesAimsGoals.getAims(mSelectedTheme));
} else if(mSelectedThemeIdx != -1){
selectedItem = parent.getItemAtPosition(mSelectedThemeIdx);
mSelectedTheme = selectedItem.toString();
setSpinner(spnrAims, "Select Aim", ThemesAimsGoals.getAims(mSelectedTheme));
parent.setSelection(mSelectedThemeIdx);
mSelectedThemeIdx = -1;
}//Else
}//onItemSelected
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spnrAims.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object selectedItem = parent.getItemAtPosition(position);
if (selectedItem != null) {
mSelectedAim = selectedItem.toString();
setSpinner(spnrGoals, "Select Goal", ThemesAimsGoals.getGoals(mSelectedTheme, mSelectedAim));
} else if(mSelectedAimIdx != -1){
selectedItem = parent.getItemAtPosition(mSelectedAimIdx);
mSelectedAim = selectedItem.toString();
setSpinner(spnrGoals, "Select Goal", ThemesAimsGoals.getGoals(mSelectedTheme, mSelectedAim));
parent.setSelection(mSelectedAimIdx);
mSelectedAimIdx = -1;
}//Else
}//onItemSelected
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spnrGoals.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object selectedItem = parent.getItemAtPosition(position);
if (selectedItem != null) {
mSelectedGoal = selectedItem.toString();
}else if(mSelectedGoalIdx != -1){
selectedItem = parent.getItemAtPosition(mSelectedGoalIdx);
mSelectedGoal = selectedItem.toString();
parent.setSelection(mSelectedGoalIdx);
mSelectedGoalIdx = -1;
}//Else
}//onItemSelected
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return view;
}//onCreateView
//----------------------------------------------------------------------------------------//
/**
* Populate Spinner
* #param spnr Spinner to populate
* #param prompt What to show at the start
* #param array Items in the spinner
*/
private void setSpinner(Spinner spnr, String prompt, String[] array) {
spnr.setPrompt(prompt);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(activity, android.R.layout.simple_spinner_item, array);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnr.setAdapter(
new NothingSelectedSpinnerAdapter(
adapter,
R.layout.contact_spinner_row_nothing_selected,
activity,
prompt));
}//setSpinner
//----------------------------------------------------------------------------------------//
/**
* Some lifecycle callbacks so that the image can survive orientation chang
*
* #param outState current state of fragment
*/
#Override
public void onSaveInstanceState(Bundle outState) {
Log.d(TAG, "onSaveInstanceState");
super.onSaveInstanceState(outState);
outState.putInt(SELECTED_THEME_IDX_STORAGE_KEY, spnrThemes.getSelectedItemPosition());
outState.putInt(SELECTED_AIM_IDX_STORAGE_KEY, spnrAims.getSelectedItemPosition());
outState.putInt(SELECTED_GOAL_IDX_STORAGE_KEY, spnrGoals.getSelectedItemPosition());
}//onSaveInstanceState
//----------------------------------------------------------------------------------------//
/**
* Rebuilds the Activity/Fragment in the image of the last one.
*
* #param savedInstanceState Info from last session or rotation
*/
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(TAG, "onActivityCreated");
if (savedInstanceState == null)
return;
mSelectedThemeIdx = savedInstanceState.getInt(SELECTED_THEME_IDX_STORAGE_KEY);
mSelectedAimIdx = savedInstanceState.getInt(SELECTED_AIM_IDX_STORAGE_KEY);
mSelectedGoalIdx = savedInstanceState.getInt(SELECTED_GOAL_IDX_STORAGE_KEY);
}//onActivityCreated
}//Cls
With the following code I'm correctly receiving a dynamic list from mysql db and putting the elements in a listview.
public class MenuActivity extends ListActivity implements FetchDataListener {
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
initView();
}
private void initView() {
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading..");
String url = "http://www.*********.php";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
#Override
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
This is my array adapter:
public class ApplicationAdapter extends ArrayAdapter<Application>{
private List<Application> items;
public ApplicationAdapter(Context context, List<Application> items) {
super(context, R.layout.app_cat_list, items);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.app_cat_list, null);
}
Application app = items.get(position);
if(app != null) {
TextView titleText = (TextView)v.findViewById(R.id.titleTxt);
if(titleText != null) titleText.setText(app.getTitle());
}
return v;
}
Now I want to click on single row and open another activity passing some values via intent extra.
Where should I implement click listener?
I'm pretty sure it should be inserted in the "getView" but how I pass the app.getTitle() via intent? I know how pass intent extra in general, tried but no click happens.
Any help would be appreciated, thanks
Now I want to click on single row and open another activity passing
some values via intent extra. Where should I implement click listener?
No need to add OnItemClickListener because extending ListActivity in MenuActivity so just override onListItemClick method for handing ListView row click:
#Override
public void onListItemClick(ListView l, View view, int position, long id) {
// your code here...
}
how I pass the app.getTitle() via intent?
Get selected row TextView value in onListItemClick using view parameter:
TextView txtView=(TextView)v.findViewById(R.id.titleTxt);
String selectedText=txtView.getText().toString();
Use selectedText for sending value with Intent in Next Activity
Put this in your getView()
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent =new Intent(context, YourActivity.class);
context.startActivity(intent);
}
});
There can be multiple ways and following is one of them:
Set onItemClickListner on your listview in your activity and it will give you a callback i.e onListItemClick. But as you said you want the title their you have to set tag on the convertView in the getView method like covertView.setTag("itemTitle"); and in your onListItemClick get the tag from view and convert it to the title like this v.getTag().toString(); and set it any where you want.
follwoing is the full code:
#Override
public void onListItemClick(ListView l, View view, int position, long id) {
String title = view.getTag().toString();
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("title", title);
startActivity(intent);
// your code here... }
Please post if got stuck anywhere.
I want to programmatically (re)highlight selected list item after screen rotation.
public class MyListFragment extends ListFragment {
private static final String tag = MyListFragment.class.getName();
private static final String indexTag = "index";
private int index = -1;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
if (savedInstanceState != null) {
index = savedInstanceState.getInt(indexTag, -1);
Log.d(tag, "Restored index " + index + " from saved instance state.");
}
}
#Override
public void onResume() {
super.onResume();
if (index >= 0) {
showDetails(index);
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
private void showDetails(int index) {
this.index = index;
getListView().setItemChecked(index, true);
// update details panel
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(indexTag, index);
}
}
I use CheckedTextView as item view in my custom adapter:
public class MyListAdapter extends BaseAdapter {
private static final String tag = MyListAdapter.class.getName();
#Override
public CheckedTextView getView(int position, View convertView, ViewGroup parent) {
if (convertView == null || !(convertView instanceof CheckedTextView)) {
final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.simple_list_item_single_choice, parent, false);
}
((CheckedTextView)convertView).setText("test");
return (CheckedTextView)convertView;
}
}
After screen rotation showDetails() is called and details panel updates but setItemChecked()does nothing and the item is still not highlighted. Also I noticed that when item it clicked by touch event setItemChecked() is not needed and the row highlights anyway.
So how can I programmatically check the item during onResume stage?
put showIndex(index) in your onActivityCreate() because on screen rotation Android destroys current activity and create another one saving current state through Bundle savedInstanceState
I solved the problem. I forgot that I'm setting list adapter through AsyncTask on my activity so when showDetails() is called during onResume stage my fragment still has empty list.
So I removed onResume method from my fragment, made showDetails() public and call it from my activity after setting the adapter:
public void onListLoadDone(...) {
final MyListAdapter adapter = new MyListAdapter(...);
myListFragment.setListAdapter(adapter);
myListFragment.showDetails();
}
I have a ListView with a custom Adapter that extends ArrayAdapter. It's a ArrayAdapter of Type Artist.
Artist is a very small class that has a name and an id. The Artist Class has toString() overridden to return just the name.
I have an EditText. The EditText has an TextChangeListener where i call .getFilter().filter(chars, callback) on my adapter.
In the Filter.Filterlistener().onComplete() callback i print the count and it looks really good. As i type the count decreases. So it seams everything works as advertised, but the List stays the same. I tried to call artistAdapter.notifyDataSetChanged() to force the list to redraw, but nothing happens. [see 2.)]
I am tinkering around for days now! I am desperate.. Hopefully someone can have a look on my code and tell me what i am doing wrong!
Thanks!
Here is what i have done:
1.) Defined a ListView and an EditText like this:
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_search_text"
android:layout_width="fill_parent"
android:layout_height="35dip"
android:layout_below="#id/header">
</EditText>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_search"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
2.) Setup my ListView in the Activities onCreate():
private ListView listView = null;
private ArtistAdapter artistAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_artists);
artistAdapter = new ArtistAdapter(this, R.layout.row, list); // 'list' is an ArrayList<Artist>
listView = (ListView) findViewById(R.id.list_search);
listView.setAdapter(artistAdapter);
listView.setFastScrollEnabled(true);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int position, long id) {
// do something
}
});
EditText txtSearch = (EditText) findViewById(R.id.list_search_text);
txtSearch.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable arg0) { }
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
public void onTextChanged(CharSequence chars, int start, int before, int count) {
artistAdapter.getFilter().filter(chars, new Filter.FilterListener() {
public void onFilterComplete(int count) {
Log.d(Config.LOG_TAG, "filter complete! count: " + count);
artistAdapter.notifyDataSetChanged();
}
});
}
});
}
3.) This is my ArtistAdapter in short. I added an remove() and add() method:
public class ArtistAdapter extends ArrayAdapter<Artist> implements SectionIndexer {
private List<Artist> items;
/* other stuff like overridden getView, getPositionForSection, getSectionForPosition and so on */
#Override
public void remove(Artist object) {
super.remove(object);
items.remove(object);
}
#Override
public void add(Artist object) {
super.add(object);
items.add(object);
}
}
4.) My artist has also the toString() overridden:
public class Artist implements Comparable<Artist> {
public String uid;
public String name;
public Artist(String id, String name) {
this.uid = id;
this.name = name;
}
public int compareTo(Artist another) {
return this.name.compareToIgnoreCase(another.name);
}
#Override
public String toString() {
return this.name;
}
}
I found the solution. I have rewritten the whole code from scratch and found the problem.
In my custom ArrayAdapter called ArtistAdapter (see 3. in question) if have a var to store the items:
private List items;
And in my overridden getView() when i want to get the current item i did:
items.getItem(position)
now i do a:
getItems(position) (so the item is retrieved from the storage of the base class and not my own) and this seems to do the trick!
This is my getView() as it is now (the version, that is working):
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout artistView;
Artist art = getItem(position);
if (convertView == null) {
artistView = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi;
vi = (LayoutInflater)getContext().getSystemService(inflater);
vi.inflate(resId, artistView, true);
} else {
artistView = (LinearLayout) convertView;
}
TextView nameView = (TextView)artistView.findViewById(R.id.txt_name);
TextView uidView = (TextView)artistView.findViewById(R.id.txt_uid);
nameView.setText(art.name);
uidView.setText(art.uid);
return artistView;
}
Pfu, this was a really annoying bug...
Try using listView.setFilterText() rather then adapter filter.
You have to override the toString() method, to return the text you want to filter.