First of all I am a beginner so please bear with me for a moment here.
I am trying to create an app with a list of items. When you click on the item you go to a new corresponding activity. When I added a SearchView to filter the list items, the problem now with the filtered results when clicked they do not direct to the corresponding activity.
Can you please correct my code below or provide a better way to direct to the corresponding activity. Please provide as much details as possible. Thank you so much in advance.
MainActivity.java
public class MainActivity extends Activity
implements SearchView.OnQueryTextListener {
private SearchView mSearchView;
private ListView mListView;
private final String[] mStrings = { "Google", "Apple", "Samsung", "Sony", "LG", "HTC" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_main);
mSearchView = findViewById(R.id.search_view);
mListView = findViewById(R.id.list_view);
mListView.setAdapter(new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1,
mStrings));
mListView.setTextFilterEnabled(true);
setupSearchView();
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
Intent i = new Intent(MainActivity.this, google.class);
startActivity(i);
} else {
// code to direct to the corresponding activity
}
});
}
private void setupSearchView() {
mSearchView.setIconifiedByDefault(false);
mSearchView.setOnQueryTextListener(this);
mSearchView.setSubmitButtonEnabled(true);
mSearchView.setQueryHint("Search Here");
}
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
mListView.clearTextFilter();
} else {
mListView.setFilterText(newText);
}
return true;
}
public boolean onQueryTextSubmit(String query) {
return false;
}
}
Here is how I did. Instead of checking for item position which changes when search filters the list, I am checking for the String value. It worked
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = (String) mListView.getItemAtPosition(position);
if (name == "Google") {
Intent i = new Intent(MainActivity.this, Google.class);
startActivity(i);
} else {
// code to direct to the corresponding activity
}
});