I have a list of items
and i want to start different activity on the basis of item
, when i click it opens the correct activity but when i try to search list items from search view bar then it opens wrong activities.
listView = (ListView) findViewById(R.id.listView);
sv=(SearchView) findViewById(R.id.searchView1);
String[] values = new String[]{item1,item2,item3,item4,}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_2, android.R.id.text1, values);
listView.setAdapter(adapter);
//linking from 1 item to other activity stars with if options//
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0) {
Intent myIntent = new Intent(view.getContext(), activity1.class);
startActivityForResult(myIntent,0);
}
if (position == 4) {
Intent myIntent = new Intent(view.getContext(), aactivity4.class);
startActivityForResult(myIntent,0);
}
}
});
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String text) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
I don't know much about coding but can any one solve my problem..
you are starting your activity on the basis of position
but the position
will be changed when you do the search because list will shrink and positions
will change so to get data associated with the specified position in the list use getItemAtPosition
so changes conditions on the basis of data
if (parent.getItemAtPosition(position).equals("item1")) {
Intent myIntent = new Intent(view.getContext(), activity1.class);
startActivityForResult(myIntent,0);
}
else if (parent.getItemAtPosition(position).equals("item2")) { // use any item value here you want
Intent myIntent = new Intent(view.getContext(), aactivity4.class);
startActivityForResult(myIntent,0);
}
Note : you can use switch
as well instead of long if
or else-if
ladder
e.g You have three string
item 1 position 0
item 2 position 1
item 3 position 2
after searching item 2 you have two values in your list close to your search
item 2 position 0
item 3 position 1
so position will change so don't use it instead use the data
Code
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = null;
// global string to class
selectedValue = String.valueOf(parent.getItemAtPosition(position));
if (selectedValue.equals("item1")) {
// ^^^ use any item value here you want
Intent myIntent = new Intent(view.getContext(), activity1.class);
startActivityForResult(myIntent,0);
}
else if (selectedValue.equals("item2")) {
Intent myIntent = new Intent(view.getContext(), aactivity4.class);
startActivityForResult(myIntent,0);
}
}
});