Google Autocomplete cannot resolve getActivity() - android

I'm new in android programming and I have this snippet from somewhere in the internet and it says "cannot resolve getActivity()" I then tried to use getApplicationContext() but the Autocomplete did not function. What should I do to get it running without problems?
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, DirectionFinderListener {
private GoogleMap mMap;
private Button btnFindPath;
//private EditText etOrigin;
//private EditText etDestination;
private List<Marker> originMarkers = new ArrayList<>();
private List<Marker> destinationMarkers = new ArrayList<>();
private List<Polyline> polylinePaths = new ArrayList<>();
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
AutoCompleteTextView etOriginView = (AutoCompleteTextView) findViewById(R.id.etOrigin);
etOriginView.setAdapter(new PlacesAutoCompleteAdapter(getActivity(), R.layout.autocomplete_list_item));
etOriginView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Get data associated with the specified position
// in the list (AdapterView)
String description = (String) parent.getItemAtPosition(position);
Toast.makeText(getActivity(), description, Toast.LENGTH_SHORT).show();
}
});
btnFindPath = (Button) findViewById(R.id.btnFindPath);
//etOrigin = (EditText) findViewById(R.id.etOrigin);
//etDestination = (EditText) findViewById(R.id.etDestination);
btnFindPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendRequest();
}
});
}
PlacesAutoCompleteAdapter Class
class PlacesAutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
ArrayList<String> resultList;
Context mContext;
int mResource;
PlaceAPI mPlaceAPI = new PlaceAPI();
public PlacesAutoCompleteAdapter(Context context, int resource) {
super(context, resource);
mContext = context;
mResource = resource;
}
#Override
public int getCount() {
// Last item will be the footer
return resultList.size();
}
#Override
public String getItem(int position) {
return resultList.get(position);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
resultList = mPlaceAPI.autocomplete(constraint.toString());
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
}
else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
Any help is appreciated, thanks in advance!
My Google Places API Web Service tells me that I have 100% errors, so does it mean that something is wrong with my Adapter?

Try MapsActivity.this insted of getActivity()

Related

Android ArrayAdapter cant Filter because mOriginalValues not set

My Problem is that I cant Filter a ListView with a self defined Filter. The Filter prints out the needed Result but the View wont update.
This is my Activity :
public class RecipesActivity extends AppCompatActivity implements RecipeListFragment.OnListFragmentInteractionListener {
private TextView mTextMessage;
private ListView listView;
private RecipeListAdapter sIAdapter;
private EditText searchRecipe;
private ArrayList<Recipe> recipes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipes);
searchRecipe = (EditText) findViewById(R.id.searchRecipe);
mTextMessage = (TextView) findViewById(R.id.message);
recipes =SQLGetter.readRecipesFromDB(this,"");
listView = (ListView) findViewById(R.id.recipeList);
sIAdapter = new RecipeListAdapter(this,R.layout.recipe_list_row, recipes);
listView.setAdapter(sIAdapter);
searchRecipe.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
sIAdapter.getFilter().filter(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}
This is my Adapter:
public class RecipeListAdapter extends ArrayAdapter<Recipe> implements Filterable {
private ArrayList<Recipe> arr;
private ArrayList<Recipe> filteredRecipes;
private TextView text;
public RecipeListAdapter(Context context, int textviewResourceId, ArrayList<Recipe> recipes){
super(context,textviewResourceId,recipes);
this.arr =recipes;
this.filteredRecipes=new ArrayList<Recipe>();
}
#Override
public View getView (final int position, View convertView, ViewGroup parent){
final Recipe recipe = getItem(position);
if(convertView==null) {
convertView= LayoutInflater.from(parent.getContext()).inflate(R.layout.recipe_list_row, parent, false);
}
final TextView recipeName = convertView.findViewById(R.id.recipeName);
recipeName.setText(recipe.getName());
if(!recipeName.getText().toString().isEmpty()) {
recipeName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), RecipeShowcaseActivity.class);
intent.putExtra("recipeName", recipe.getName());
getContext().startActivity(intent);
}
});
}
System.out.println("Arraygröße ="+ arr.size());
return convertView;
}
#Override
public Filter getFilter() {
final Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arr = (ArrayList<Recipe>) results.values;
System.out.println("Arrgröße : "+arr.size());
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
constraint = constraint.toString().toLowerCase();
ArrayList<Recipe> filteredList = new ArrayList<Recipe>();
ArrayList<Recipe> allRecipes =SQLGetter.readRecipesFromDB(getContext(),"");
for(Recipe recipe:allRecipes){
if(recipe.getName().toUpperCase().contains(constraint.toString().toUpperCase())){
filteredList.add(recipe);
}
}
System.out.println("Filterlistengröße: " +filteredList.size());
results.count = filteredList.size();
results.values = filteredList;
Log.e("VALUES", results.values.toString());
return results;
}
};
return filter;
}
}
And lastly this is the Problem I'm facing while calling the Filter in RecipesActivity :
enter image description here
In every post I've read so far, it's usually written that, mOriginalValues should be set because of the initiation
sIAdapter = new RecipeListAdapter(this,R.layout.recipe_list_row, recipes);
I'm really out of Ideas what I'm doing wrong here..
you should use sIAdapter.notifyDataSetChanged() after every time changes made in list.

Add personal locations to Google Placeautocomplete list

Is there a way to pin an address to the top of a placeautocomplete search for an android app?
http://jsfiddle.net/v9rt3t2y/
This example is in JS/HTML, but I couldn't find anything for native android studio.
Anyway you can use customized AutoCompleteTextView like in this article. You should add your custom place name in protected void publishResults(CharSequence constraint, FilterResults results) just after filling places list from results.values; from Task<AutocompletePredictionBufferResponse>.
So, for custom place name "-> Custom place <-" with MainActivity.java like:
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final String TAG = MainActivity.class.getSimpleName();
private GoogleMap mGoogleMap;
private SupportMapFragment mMapSupportedFragment;
private AutoCompleteTextView mPlaceAutoCompleteTextView;
private PlacesAdapter mPlacesAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlacesAdapter = new PlacesAdapter(this);
mPlaceAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.place_autocomplete);
mPlaceAutoCompleteTextView.setThreshold(1);
mPlaceAutoCompleteTextView.setAdapter(mPlacesAdapter);
mMapSupportedFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_fragment);
mMapSupportedFragment.getMapAsync(MainActivity.this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
}
class PlacesAdapter extends ArrayAdapter {
Context context;
List<String> placesList = new ArrayList<>();
GeoDataClient geoDataClient;
PlacesAdapter.PlacesAutoCompleteFilter filter = new PlacesAdapter.PlacesAutoCompleteFilter();
public PlacesAdapter(Context context) {
super(context, android.R.layout.simple_dropdown_item_1line,
new ArrayList<Place>());
this.context = context;
geoDataClient = Places.getGeoDataClient(context, null);
}
#Override
public int getCount() {
return placesList.size();
}
#Override
public String getItem(int position) {
return placesList.get(position);
}
#Override
public Filter getFilter() {
return filter;
}
#Override
public View getView(int position, View view, #NonNull ViewGroup parent) {
if (view == null) {
view = LayoutInflater.from(parent.getContext())
.inflate(android.R.layout.simple_dropdown_item_1line,
parent, false);
}
TextView textOne = view.findViewById(android.R.id.text1);
textOne.setText(placesList.get(position));
return view;
}
class PlacesAutoCompleteFilter extends Filter {
private Object lock = new Object();
private Object lockTwo = new Object();
private boolean placeResults = false;
#Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
placeResults = false;
final List<String> predictedPlacesList = new ArrayList<>();
if (prefix == null || prefix.length() == 0) {
synchronized (lock) {
results.values = new ArrayList<Place>();
results.count = 0;
}
} else {
final String searchStrLowerCase = prefix.toString().toLowerCase();
Task<AutocompletePredictionBufferResponse> task
= getAutoCompletePlaces(searchStrLowerCase);
task.addOnCompleteListener(new OnCompleteListener<AutocompletePredictionBufferResponse>() {
#Override
public void onComplete(#NonNull Task<AutocompletePredictionBufferResponse> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Auto complete prediction successful");
AutocompletePredictionBufferResponse predictions = task.getResult();
for (AutocompletePrediction prediction : predictions) {
predictedPlacesList.add((prediction.getFullText(null)).toString());
}
predictions.release();
} else {
Log.d(TAG, "Auto complete prediction unsuccessful");
}
placeResults = true;
synchronized (lockTwo) {
lockTwo.notifyAll();
}
}
});
while (!placeResults) {
synchronized (lockTwo) {
try {
lockTwo.wait();
} catch (InterruptedException e) {
}
}
}
results.values = predictedPlacesList;
results.count = predictedPlacesList.size();
Log.d(TAG, "Autocomplete predictions size after wait" + results.count);
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.values != null) {
placesList = (ArrayList<String>) results.values;
} else {
placesList = null;
}
// add your custom place here:
placesList.add(0, "-> Custom place <-");
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
private Task<AutocompletePredictionBufferResponse> getAutoCompletePlaces(String query) {
AutocompleteFilter.Builder filterBuilder = new AutocompleteFilter.Builder();
Task<AutocompletePredictionBufferResponse> results =
geoDataClient.getAutocompletePredictions(query, null,
filterBuilder.build());
return results;
}
}
}
}
and activity_main.xml (NB! according to Usage Limits:
If your app uses the autocomplete service programmatically, your UI
must either display a 'Powered by Google' attribution, or appear
within a Google-branded map.
) like:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="<YOUR_PACKAGE_NAME>.MainActivity">
<fragment class="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<AutoCompleteTextView android:id="#+id/place_autocomplete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/background_light"
android:layout_margin="16dp"
android:padding="8dp"
android:inputType="text"
android:imeOptions="actionNext"
android:textSize="16sp"
android:hint="Type place name here" />
</RelativeLayout>
when you enter letter "a" to text field you should get something like that:
And don't forget to activate Places SDK on Google Cloud Platform Console.

searchview EditText with Recyclerview

I am trying to add search functionality in my recyclerview. I found a tutorial on google and implemented the same. Search using editText in recyclerview. But my list disappears when I enter the input. Where am I going wrong? My recycler view contains multiple textboxes. Below is MyAdapter class.
How do I implement search functionality with the below code?
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>implements Filterable {
private List<ListItem> listItems;
private List<ListItem> mFilterData;
private Context context;
String m,e;
private ItemFilter mFilter = new ItemFilter();
public MyAdapter(List<ListItem> itemList, Context context) {
this.listItems = itemList;
this.context = context;
this.mFilterData = listItems;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ListItem listItem = mFilterData.get(position);
holder.nameText.setText(listItem.getName());
holder.addText.setText(listItem.getAddress());
Picasso.with(context).load(listItem.getLogo()).resize(180,80).into(holder.imageText);
}
#Override
public int getItemCount() {
return mFilterData.size();
}
public int getCount() {
return mFilterData.size();
}
public ListItem getItem(int position) {
return mFilterData.get(position);
}
public long getItemId(int position) {
return position;
}
#Override
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String userString = constraint.toString().toLowerCase();
FilterResults filterResults = new FilterResults();
final List<ListItem> originalList = listItems;
int count = originalList.size();
final ArrayList<ListItem> resultList = new ArrayList<>(count);
ListItem tDescription;
for (int i = 0; i < count; i++) {
tDescription= originalList.get(i);
if (tDescription.getName().toLowerCase().contains(userString)) {
resultList.add(tDescription);
}
}
filterResults.values = resultList;
filterResults.count = resultList.size();
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mFilterData = (ArrayList<ListItem>) results.values;
notifyDataSetChanged();
}
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView nameText, addText,mobText,emailText;
public ImageView imageText;
public ViewHolder(View itemView) {
super(itemView);
//code
}
}
}
SEARCH
private void addTextListener() {
search.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
s = s.toString().toLowerCase();
final List<ListItem> filteredList = new ArrayList<>();
for (int i = 0; i < listItems.size(); i++) {
final String text = listItems.get(i).toString();
if (text.contains(s)) {
filteredList.add(listItems.get(i));
}
}
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new MyAdapter(filteredList, getActivity());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged(); // data set changed
}
});
}
Try below code
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String userString = constraint.toString().toLowerCase();
if (userString.isEmpty()) {
mFilterData = listItems;
} else {
ArrayList<ListItem> resultList = new ArrayList<>();
for (ListItem mListItem : listItems) {
if (mListItem.getName().toLowerCase().contains(userString)) {
resultList.add(mListItem);
}
}
mFilterData = resultList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = mFilterData;
filterResults.count = mFilterData.size();
return filterResults;
}
}
Updated
Remove all code from edittext OnTextChange and write below code,no need to set adapter and all just write below oneline code and remove rest of code
adapter.getFilter().filter(s.toString());

AutoCompleteTextView adapter returning old values

I implemented an AutoCompleteTextView where the data is updated from the server every time the user enters a new text input. It works well. However, every time I enter a new query, the previous results are displayed until the new result set is updated.
My guess is that it displays the currently queried results until the backend responds with the new search results. Is there a way to clear the current results?
Activity code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_test);
actv = (AutoCompleteTextView) findViewById(R.id.actv);
actv.setThreshold(1);
actv.setAdapter(new SearchSuggestionsAdapter(this, actv.getText().toString()));
Custom adapter:
public class SearchSuggestionsAdapter extends ArrayAdapter<String> {
List<String> types = new ArrayList<>();
protected static final String TAG = "SuggestionAdapter";
private List<String> suggestions;
private Context context;
public SearchSuggestionsAdapter(Activity context, String nameFilter) {
super(context, android.R.layout.simple_dropdown_item_1line);
suggestions = new ArrayList<String>();
this.context = context;
}
#Override
public int getCount() {
return suggestions.size();
}
#Override
public String getItem(int index) {
return suggestions.get(index);
}
#Override
public Filter getFilter() {
Filter myFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
//Get new results from backend
//searchItemsFromServer is the method that returns the data
//new data is successfully sent. no problem there
List<String> new_suggestions = searchItemsFromServer(constraint.toString());
suggestions.clear();
for (int i = 0; i < new_suggestions.size(); i++) {
suggestions.add(new_suggestions.get(i));
}
filterResults.values = suggestions;
filterResults.count = suggestions.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence contraint,
FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return myFilter;
}
}
Thank you in advance!
Change your code to your activity to this
SearchSuggestionsAdapter searchSuggestionsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_test);
searchSuggestionsAdapter = new SearchSuggestionsAdapter(this, actv.getText().toString());
actv = (AutoCompleteTextView) findViewById(R.id.actv);
actv.setThreshold(1);
actv.setAdapter(searchSuggestionsAdapter);
actv.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus){
searchSuggestionsAdapter.clear();
}
}
});
}
Add the following code to your SearchSuggestionsAdapter
/**
* Create list and notify recycler view
*/
public void clear() {
if (suggestions != null) {
suggestions.clear();
notifyDataSetChanged();
}
}
actv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
suggestionAdapter.clear;
}
});
When user click on autocomplete remove the old adapter. But for this you need to define suggesstionAdapter first. and every time update this adapter and set it to autocomplete
Clear suggestion before filtering. Call adapter.clear();
Add new method in adapter
public void clear() {
suggestions.clear();
notifyDataSetChanged();
}

Getting wrong item selected from filtered list using recyclerview

I have a RecyclerView & EditText. I can select the item from RecyclerView & gets correct item unless it is not filtered.
On entering in EditText, RecyclerView list gets filtered & when I select any item from the list it shows me actual list item instead of selected one.
Fragment Class :
public class RegionListFragment extends DialogFragment implements View.OnClickListener,
OnRecylerViewClickable {
private RecyclerView regionRecyclerView;
private ArrayList<RegionDetail> regionDetailArrayList = new ArrayList<>();
private GenericRegionListAdapter genericRegionListAdapter;
private Context context = this.getActivity();
private RecyclerView.LayoutManager mLayoutManager;
private View view;
private EditText editTextSearchView;
private DatabaseHandler spcl_databaseHandler;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.spinner_fragment_list_screen, container, false);
databaseHandler = new DatabaseHandler(getActivity());
regionDetailArrayList = (ArrayList<RegionDetail>) spcl_databaseHandler.getAllRegionDetails();
editTextSearchView = (EditText) view.findViewById( R.id.search);
editTextSearchView.setHint(getString(R.string.region_search_hint));
mLayoutManager = new LinearLayoutManager(context);
regionRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView_Locations);
regionRecyclerView.setLayoutManager(mLayoutManager);
relativeLayoutBottom = (RelativeLayout) view.findViewById(R.id.rlBottom);
genericRegionListAdapter = new GenericRegionListAdapter(context, regionDetailArrayList, this, false);
regionRecyclerView.setAdapter(genericRegionListAdapter);
addTextListener();
return view;
}
public void addTextListener(){
editTextSearchView.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
genericRegionListAdapter.getFilter().filter(query.toString());
}
});
}
#Override
public void onClick(View view) {
}
#Override
public void onRecyclerItemClicked(int position, String itemName, String itemID) {
Log.v("Region Name", " : " + regionDetailArrayList.get(position).getRegionName());
}
}
Adapter Class :
public class GenericRegionListAdapter extends RecyclerView.Adapter<GenericRegionListAdapter.DataObjectHolder>
implements Filterable {
private ArrayList<RegionDetail> originalArrayList;
private ArrayList<RegionDetail> filterArrayList;
private GenericRegionListAdapter.ValueFilter valueFilter;
private OnRecylerViewClickable onRecylerViewClickable;
private Context mContext = null;
#Override
public GenericRegionListAdapter.DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.sd_custom_cardview_for_walk_list_item, parent, false);
GenericRegionListAdapter.DataObjectHolder dataObjectHolder = new GenericRegionListAdapter.DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new GenericRegionListAdapter.ValueFilter();
}
return valueFilter;
}
public class DataObjectHolder extends RecyclerView.ViewHolder{
TextView textViewWalkName;
public DataObjectHolder(View itemView) {
super(itemView);
mContext = itemView.getContext();
textViewWalkName = (TextView) itemView.findViewById(R.id.textView_Walk_Name);
}
}
public GenericRegionListAdapter(Context context, ArrayList<RegionDetail> detailsArrayList,
OnRecylerViewClickable onRecylerViewClickable, boolean doShowCheckbox) {
mContext = context;
this.originalArrayList = detailsArrayList;
this.filterArrayList = detailsArrayList;
this.onRecylerViewClickable = onRecylerViewClickable;
}
#Override
public void onBindViewHolder(final GenericRegionListAdapter.DataObjectHolder holder, final int position) {
holder.textViewWalkName.setText(originalArrayList.get(position).getRegionName());
holder.textViewWalkName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onRecylerViewClickable.onRecyclerItemClicked(position, originalArrayList.get(position).getRegionName(), originalArrayList.get(position).getRegionID());
}
});
}
// method to access in activity after updating selection
public ArrayList<RegionDetail> getRegionList() {
return originalArrayList;
}
#Override
public int getItemCount() {
return originalArrayList.size();
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<RegionDetail> filterList = new ArrayList<RegionDetail>();
for (int i = 0; i < filterArrayList.size(); i++) {
if ((filterArrayList.get(i).getRegionName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
RegionDetail listItem = new RegionDetail();
listItem.setRegionID(filterArrayList.get(i).getRegionID());
listItem.setRegionName(filterArrayList.get(i).getRegionName());
filterList.add(listItem);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = filterArrayList.size();
results.values = filterArrayList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
originalArrayList = (ArrayList<RegionDetail>) results.values;
notifyDataSetChanged();
Log.v("Size", " : " + originalArrayList.size());
if (originalArrayList.size() == 0) {
new GlobalToast().showToastMessage(mContext, mContext.getResources().getString(R.string.no_records_found));
}
}
}
}
Please help me.
Please use this code snippet
private class ItemFilter extends Filter {
String filterString;
#Override
protected FilterResults performFiltering(CharSequence constraint) {
filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
int count = filterArrayList.size();
ArrayList<RegionDetail> filterList = new ArrayList<RegionDetail>();
String filterableString;
for (int i = 0; i < count; i++) {
RegionDetail listItem = new RegionDetail();
listItem.setRegionID(filterArrayList.get(i).getRegionID());
listItem.setRegionName(filterArrayList.get(i).getRegionName());
filterList.add(listItem);
}
results.values =filterList;
results.count = filterList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
originalArrayList = (ArrayList<RegionDetail>) results.values;
notifyDataSetChanged();
}
}
i hope this code will filter your list correctly and you get right list item onClick.

Categories

Resources