My question is similar to this Implementing Search Filter in Adapter Class which parses a json array (without using pojo)
but I would like to try to struggle the problem differently. I have a list of elements that must be filtered based on a condition and once this condition is verified, I want to retrieve the elements that verify it from the json array. In this example, I filtered the elements based on their name, and in the setContentValue () I would set the code and the hex string taking only those elements that have that name, otherwise during filtering the name has a different index from the code and the hex strings. How could I do that?
Fragment
public class ColorViewFragment extends Fragment {
private RecyclerView recyclerView;
private JSONArray json;
private ColorListAdapter adapter;
private EditText editColor;
#Nullable #Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.color_list, container, false);
this.recyclerView = view.findViewById(R.id.recyclerView);
/*
try {
this.recyclerView.setAdapter(new ColorListAdapter(this.json));
} catch (JSONException e) {
e.printStackTrace();
}
*/
try {
adapter = new ColorListAdapter(json);
} catch (JSONException e) {
e.printStackTrace();
}
recyclerView.setAdapter(adapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
this.recyclerView.setLayoutManager(layoutManager);
//
editColor = view.findViewById(R.id.editText);
editColor.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) {
ColorViewFragment.this.adapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
return view;
}
public void setJSON(JSONArray newJson){
this.json = newJson;
}
Adapter
public class ColorListAdapter extends RecyclerView.Adapter implements Filterable {
private JSONArray colorList;
private List<String> colorListFiltered = new ArrayList<String>();
public ColorListAdapter(JSONArray json) throws JSONException {
super();
if (json != null) {
this.colorList = json;
for (int i=0;i<json.length();i++){
//colorListFiltered.add((colorList.getString(i)));
colorListFiltered.add(json.getJSONObject(i).getString("Name"));
}
}
}
#Override
public Filter getFilter() {
return new colorFilter();
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_color_view, viewGroup, false);
return new ColorListHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int i) {
try {
((ColorListHolder) viewHolder).setContentValue(i);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return this.colorListFiltered.size();
}
private class ColorListHolder extends RecyclerView.ViewHolder {
private TextView colorCodeText;
private TextView colorNameText;
private CardView imageView;
public ColorListHolder(#NonNull View itemView) {
super(itemView);
this.colorCodeText = itemView.findViewById(R.id.colorCode_text);
this.colorNameText = itemView.findViewById(R.id.colorName_text);
this.imageView = itemView.findViewById(R.id.colorView);
}
public void setContentValue(int index) throws JSONException {
this.colorNameText.setText(colorListFiltered.get(index));
//this.colorNameText.setText(((JSONObject) colorList.get(index)).getString("Name"));
this.colorCodeText.setText(((JSONObject) colorList.get(index)).getString("ColorCode"));
this.imageView.setCardBackgroundColor(Color.parseColor(((JSONObject) colorList.get(index)).getString("HexString")));
}
}
public class colorFilter extends Filter{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults Result = new FilterResults();
// if constraint is empty return the original names
if(constraint.length() == 0 ) {
ArrayList<String> arrColorList = new ArrayList<>();
for (int i = 0; i < colorList.length(); i++) {
try {
arrColorList.add(colorList.getJSONObject(i).getString("Name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Result.values = arrColorList;
Result.count = arrColorList.size();
return Result;
}
/*if(constraint.length() == 0 ){
Result.values = colorList;
Result.count = colorList.length();
return Result;*/
else {
List<String> Filtered_Names = new ArrayList<String>();
String filterString = constraint.toString().toLowerCase();
String filterableString = "";
for (int i = 0; i < colorList.length(); i++) {
try {
filterableString = (colorList.getJSONObject(i)).getString("Name");
} catch (JSONException e) {
e.printStackTrace();
}
if (filterableString.toLowerCase().contains(filterString)) {
Filtered_Names.add(filterableString);
}
}
Result.values = Filtered_Names;
Result.count = Filtered_Names.size();
return Result;
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
colorListFiltered = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
I am near solution, list loads and get filtered, but when I delete word, I get a ClassCastException: String cannot be cast to JSONObject (in setContentValue).
public class ColorListAdapter extends RecyclerView.Adapter implements Filterable {
private List<JSONObject> colorList = new ArrayList<JSONObject>();
private List<JSONObject> colorListFiltered = new ArrayList<JSONObject>();
public ColorListAdapter(JSONArray json) throws JSONException {
super();
if (json != null) {
for(int i=0; i<json.length(); i++) {
JSONObject jsonObj = json.getJSONObject(i);
colorList.add(jsonObj);
colorListFiltered = colorList;
}
}
}
#Override
public Filter getFilter() {
return new colorFilter();
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_color_view, viewGroup, false);
return new ColorListHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int i) {
try {
((ColorListHolder) viewHolder).setContentValue(i);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return this.colorListFiltered.size();
}
private class ColorListHolder extends RecyclerView.ViewHolder {
private TextView colorNameText;
private TextView colorCodeText;
private CardView imageView;
public ColorListHolder(#NonNull View itemView) {
super(itemView);
this.colorCodeText = itemView.findViewById(R.id.colorCode_text);
this.colorNameText = itemView.findViewById(R.id.colorName_text);
this.imageView = itemView.findViewById(R.id.colorView);
}
public void setContentValue(final int index) throws JSONException {
this.colorNameText.setText(colorListFiltered.get(index).getString("Name"));
this.colorCodeText.setText(colorListFiltered.get(index).getString("ColorCode"));
this.imageView.setCardBackgroundColor(Color.parseColor(colorListFiltered.get(index).getString("HexString")));
}
}
//filtro su Name
public class colorFilter extends Filter{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults Result = new FilterResults();
// if constraint is empty return the original names
if(constraint.length() == 0 ) {
ArrayList<String> arrNameList = new ArrayList<>();
for (int i = 0; i < colorList.size(); i++) {
try {
arrNameList.add(colorList.get(i).getString("Name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Result.values = arrNameList;
Result.count = arrNameList.size();
return Result;
}
else {
List<JSONObject> Filtered_Names = new ArrayList<JSONObject>();
String filterString = constraint.toString().toLowerCase();
String filterableString = "";
for (int i = 0; i < colorList.size(); i++) {
try {
filterableString = (colorList.get(i)).getString("Name");
} catch (JSONException e) {
e.printStackTrace();
}
if (filterableString.toLowerCase().contains(filterString)) {
Filtered_Names.add(colorList.get(i));
}
}
Result.values = Filtered_Names;
Result.count = Filtered_Names.size();
return Result;
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
colorListFiltered = (ArrayList<JSONObject>) results.values;
notifyDataSetChanged();
}
}
}
You use colorListFiltered for names but you use colorList for hex codes in setContentValue. First two lists are same but when you filter colorListFiltered they are getting different.
Change this,
private JSONArray colorList;
private List<String> colorListFiltered = new ArrayList<String>();
to
private List<JSONObject> colorList = new ArrayList<JSONObject>();
private List<JSONObject> colorListFiltered = new ArrayList<JSONObject>();
and your performFiltering
List<JSONObject> Filtered_Names = new ArrayList<JSONObject>();
String filterString = constraint.toString().toLowerCase();
String filterableString = "";
for (int i = 0; i < colorList.size(); i++) {
try {
filterableString = (colorList.get(i)).getString("Name");
} catch (JSONException e) {
e.printStackTrace();
}
if (filterableString.toLowerCase().contains(filterString)) {
Filtered_Names.add(colorList.get(i));
}
}
setContentValue:
public void setContentValue(int index) throws JSONException {
this.colorNameText.setText(colorListFiltered.get(index).getString("Name"));
this.colorCodeText.setText(colorListFiltered.get(index).getString("ColorCode"));
this.imageView.setCardBackgroundColor(Color.parseColor(colorListFiltered.get(index).getString("HexString"));
}
Related
I get duplicate data items in the RecyclerView when data is retrieved.
I have tried some such like way NotifyDataSetChanged() and setHasStableIds (true). But still has not succeeded and I tried this way (How to solve duplicate data items in recyclerview) but still has not succeededed too.
private void loadFirstPage() {
Log.d(TAG, "loadFirstPage: ");
callTopRatedMoviesApi().enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if (!response.isSuccessful()) {
Log.e(TAG, "Response Error : " + response.code());
} else {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
JSONObject dataObject = jsonObject.getJSONObject("data");
JSONArray itemsObject = dataObject.getJSONArray("items");
modelGetProductSearchList = new ArrayList<>();
progressBar.setVisibility(View.GONE);
if (itemsObject.length() == 0) {
// Set GONE Visibility of TextView
} else {
for (int a = 0; a <= itemsObject.length(); a++) {
JSONObject object = itemsObject.getJSONObject(a);
ModelGetProductSearch modelGetProductSearch = new ModelGetProductSearch();
modelGetProductSearch.setId(object.getInt("id"));
modelGetProductSearch.setName(object.getString("name"));
JSONObject sourceObject = object.getJSONObject("source");
modelGetProductSearch.setSourceNames(sourceObject.getString("name"));
modelGetProductSearchList.add(modelGetProductSearch);
adapter.addAll(modelGetProductSearchList);
progressBar.setVisibility(View.GONE);
tvTidakAdaHasil.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if (currentPage <= TOTAL_PAGES && currentPage <= adapter.getItemCount()) adapter.addLoadingFooter();
else isLastPage = true;
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
tvTidakAdaHasil.setText("Maaf, cek koneksi internet anda dan coba kembali");
progressBar.setVisibility(View.GONE);
}
});
}
private void loadNextPage() {
Log.d(TAG, "loadNextPage: " + currentPage);
callTopRatedMoviesApi().enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
adapter.removeLoadingFooter();
isLoading = false;
if (!response.isSuccessful()) {
Log.e(TAG, "Response Error : " + response.code());
} else {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
JSONObject dataObject = jsonObject.getJSONObject("data");
JSONArray itemsObject = dataObject.getJSONArray("items");
modelGetProductSearchList = new ArrayList<>();
progressBar.setVisibility(View.GONE);
for (int a = 0; a <= itemsObject.length(); a++) {
JSONObject object = itemsObject.getJSONObject(a);
ModelGetProductSearch modelGetProductSearch = new ModelGetProductSearch();
modelGetProductSearch.setId(object.getInt("id"));
modelGetProductSearch.setName(object.getString("name"));
JSONObject sourceObject = object.getJSONObject("source");
modelGetProductSearch.setSourceNames(sourceObject.getString("name"));
modelGetProductSearchList.add(modelGetProductSearch);
adapter.addAll(modelGetProductSearchList);
progressBar.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
}
if (currentPage != TOTAL_PAGES && currentPage <= adapter.getItemCount()) adapter.addLoadingFooter();
else isLastPage = true;
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
tvTidakAdaHasil.setText("Maaf, cek koneksi internet anda dan coba kembali");
progressBar.setVisibility(View.GONE);
}
});
}
and this is my adapter
public class AdapterDetailSearch extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int ITEM = 0;
private static final int LOADING = 1;
private List<ModelGetProductSearch> modelGetProductSearchList;
private Context context;
private boolean isLoadingAdded = false;
public AdapterDetailSearch(Context context) {
this.context = context;
modelGetProductSearchList = new ArrayList<>();
}
public List<ModelGetProductSearch> getMovies() {
return modelGetProductSearchList;
}
public void setMovies(List<ModelGetProductSearch> movieResults) {
this.modelGetProductSearchList = movieResults;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case ITEM:
viewHolder = getViewHolder(parent, inflater);
break;
case LOADING:
View v2 = inflater.inflate(R.layout.row_item_progress, parent, false);
viewHolder = new LoadingVH(v2);
break;
}
return viewHolder;
}
#NonNull
private RecyclerView.ViewHolder getViewHolder(ViewGroup parent, LayoutInflater inflater) {
RecyclerView.ViewHolder viewHolder;
View viewHolder = inflater.inflate(R.layout.row_item_detail_list, parent, false);
return new MovieVH(viewHolder);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
final ModelGetProductSearch result = modelGetProductSearchList.get(position);
switch (getItemViewType(position)) {
case ITEM:
final MovieVH itemsListVH = (MovieVH) holder;
// Visible and Invisible set TextView
}
}
#Override
public int getItemCount() {
return modelGetProductSearchList == null ? 0 : modelGetProductSearchList.size();
}
#Override
public int getItemViewType(int position) {
return (position == modelGetProductSearchList.size() - 1 && isLoadingAdded) ? LOADING : ITEM;
}
/*
Helpers
_________________________________________________________________________________________________
*/
public void add(ModelGetProductSearch r) {
modelGetProductSearchList.add(r);
notifyItemInserted(modelGetProductSearchList.size() - 1);
}
public void addAll(List<ModelGetProductSearch> moveResults) {
for (ModelGetProductSearch result : moveResults) {
add(result);
}
}
public void remove(ModelGetProductSearch r) {
int position = modelGetProductSearchList.indexOf(r);
if (position > -1) {
modelGetProductSearchList.remove(position);
notifyItemRemoved(position);
}
}
public void clear() {
isLoadingAdded = false;
while (getItemCount() > 0) {
remove(getItem(0));
}
}
public boolean isEmpty() {
return getItemCount() == 0;
}
public void addLoadingFooter() {
isLoadingAdded = true;
add(new ModelGetProductSearch());
}
public void removeLoadingFooter() {
isLoadingAdded = false;
int position = modelGetProductSearchList.size() - 1;
ModelGetProductSearch result = getItem(position);
if (result != null) {
modelGetProductSearchList.remove(position);
notifyItemRemoved(position);
}
}
public ModelGetProductSearch getItem(int position) {
return modelGetProductSearchList.get(position);
}
/*
View Holders
_________________________________________________________________________________________________
*/
/**
* Main list's content ViewHolder
*/
protected class MovieVH extends RecyclerView.ViewHolder {
private LinearLayout llContainer;
private ImageView ivItem;
private TextView tvItemTitle, tvPriceRegular, tvPriceAfterDiscount, textFrom;
public MovieVH(View itemView) {
super(itemView);
llContainer = itemView.findViewById(R.id.container);
ivItem = itemView.findViewById(R.id.iv_item);
textFrom = itemView.findViewById(R.id.tv_from);
}
}
protected class LoadingVH extends RecyclerView.ViewHolder {
public LoadingVH(View itemView) {
super(itemView);
}
}
}
You add the same list multiple times in your adapter inside for-loop that's why it creates duplication. Move adapter.addAll outside for loop like below:
if (itemsObject.length() == 0) {
// Set GONE Visibility of TextView
} else {
for (int a = 0; a < itemsObject.length(); a++) {
...
//Remove from here
/*adapter.addAll(modelGetProductSearchList);
progressBar.setVisibility(View.GONE);
tvTidakAdaHasil.setVisibility(View.GONE);*/
}
//Add list here
adapter.addAll(modelGetProductSearchList);
progressBar.setVisibility(View.GONE);
tvTidakAdaHasil.setVisibility(View.GONE);
}
i have listview that changes according to the number i type in edittext, the list doesn't change when i type another number and keeps the same items from the previous number typed.
here is the adapter:
public class ElectorListAdapter extends BaseAdapter{
private Context activity;
private LayoutInflater inflater;
private List<Electors> DataList;
private ArrayList<Electors> arraylist=null;
// private ItemFilter mFilter = new ItemFilter();
public ElectorListAdapter(Context activity, List<Electors> electors) {
this.activity = activity;
this.DataList = electors;
this.arraylist = new ArrayList<Electors>();
this.arraylist.addAll(electors);
inflater = LayoutInflater.from(activity);
}
#Override
public int getCount() {
return DataList.size();
}
#Override
public Object getItem(int location) {
return DataList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.elector_info_cell_list, null);
TextView name = (TextView)convertView.findViewById(R.id.name);
TextView status = (TextView)convertView.findViewById(R.id.status);
Electors m = DataList.get(position);
//97697691
name.setText(m.getName());
status.setText(m.getStatus().toString());
return convertView;
}
}
and here is the implantation in the MainActivity:
adapter = new ElectorListAdapter(this, list);
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
and here where i clear the list:
serial.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
serialno = serial.getText().toString();
if(serial.getText()!=null){
//list = new ArrayList<>();
list.clear();
getlist();
}else if(serial.getText()==null){
lv.setVisibility(v.GONE);
}
}
}
});
here is the getlist();
public void getlist(){
//list = new ArrayList<>();
try {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String URL = "http://gickuwait-dev.com/electionapi/api/electors";
JSONObject jsonBody = new JSONObject();
// jsonBody.put("tblRegisteredUsers_nickName", username.getText().toString().trim());
jsonBody.put("SerialNo", serialno.toString().trim());
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//my response later should be changed
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
})
{
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString;
String json = null;
try {
json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
responseString = String.valueOf(json).trim();
ArrayList<ElectorResponse> list_response = new ArrayList<ElectorResponse>();
Type listType = new TypeToken<List<ElectorResponse>>() {}.getType();
list_response = new Gson().fromJson(responseString, listType);
for (int i = 0; i < list_response.size(); i++) {
Electors listItemData = new Electors();
listItemData.setName(list_response.get(i).getNameAr());
listItemData.setStatus(list_response.get(i).getExpr1());
listItemData.setId(list_response.get(i).getPKID());
if (listItemData.getName().startsWith(classletter)){
list.add(listItemData);
}
}
// i should have this piece of code for methods that are running in the background
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
}
});
// String Check = yourModel.getMessagetitle();
return Response.success(list_response.toString(), HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
here where i use filter to filter the list
name.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable theWatchedText) {
//Vote.this.adapter.getFilter().filter(theWatchedText.toString());
String text = name.getText().toString().toLowerCase(Locale.getDefault());
// Vote.this.adapter.getFilter().filter(text);
search_model(name.getText().toString());
}
});
private void search_model(String key){
search = new ArrayList<>();
for(int i = 0;i<list.size();i++){
Electors electors = list.get(i);
if(electors.getName().toLowerCase(Locale.getDefault()).startsWith(key)){
search.add(electors);
}
}
adapter = new ElectorListAdapter(this, search);
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
}
how can i make it change its values when i type another number, is there something missing in the adapter? thanks in advance
You need to notify the list of changes to the dataset via notifyDatasetChanged()
you should have clear array list when data is changed. Then add your new text to the array list and update it.
arraylist.clear(); //to clear array list
arraylist.add(); //to add new text
adapter.notifyDataSetChanged(); //to notify adapter
if(serial.getText()!=null){
//list = new ArrayList<>();
list.clear();
// since you removed the item you need to inform the adapter to
//refresh view
adapter.notifyDataSetChanged();
// also as soon as getlist(); gets new list , set that list on adapter and call
// adapter.notifyDataSetChanged();
getlist();
}
So I have this fun little list adapter I'm trying to figure out, in addition to Android/Java as a whole. It started with just compiling a simple list of RFID tags picked up by a scanner. The API that came with the scanner made that part pretty easy. It later evolved into fetching JSON objects associated with the tags the scanner would pick up via a URL that needed to be built using the tag ID itself.
Fast forward to today, I'm now trying to figure out a way to filter the finished list items, but I need it be done by the 'status' of the tag; not the actual 10-digit string, 'tagTitle'. Unfortunately, the working spinner filter I have set up now only does it by 'tagTitle' because I can't figure out how to access the other two TextViews to use them as a constraint instead. However, the array used by the spinner is populated with all the possible status we have in our system. So obviously any filter selection I pick, the list goes blank.
With that said, any help that'll get me to Point-B would be greatly appreciated. If there's any more information I should've included in this, please let me know. Thanks.
public class rfid_status extends UgiUiActivity implements
UgiInventoryDelegate,
UgiInventoryDelegate.InventoryDidStopListener,
UgiInventoryDelegate.InventoryTagFoundListener {
public UgiRfidConfiguration rfidConfig;
public EPCAdapter epcAdapter;
public List<UgiTag> tagArray = new ArrayList<>();
public RequestQueue rQ;
public Spinner tagSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rfid_status);
ListView tagListView = (ListView) findViewById(R.id.tagList);
String[] statStrings = {
"",
"In",
"Filled",
"Out",
"Repair",
"Lost",
"QC",
"Missing",
"Sold",
"In Transfer"
};
ArrayAdapter<String> statusArray = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, statStrings);
tagSearch = (Spinner) findViewById(R.id.tagSearch);
tagSearch.setAdapter(statusArray);
tagSearch.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String constraint = parent.getItemAtPosition(position).toString();
epcAdapter.getFilter().filter(constraint);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Do Nothing
}
});
this.setDisplayDialogIfDisconnected(true);
UgiTitleView titleView = (UgiTitleView) findViewById(R.id.status_title);
titleView.setTheTitle(getResources().getString(R.string.status_title));
this.configureTitleViewNavigation(titleView);
titleView.setBatteryStatusIndicatorDisplayVersionInfoOnTouch(true);
titleView.setUseBackgroundBasedOnUiColor(true);
titleView.setThemeColor(ContextCompat.getColor(this, msq_black));
titleView.setTextColorOnThemeColor(ContextCompat.getColor(this, msq_red));
titleView.setDisplayWaveAnimationWhileScanning(true);
rQ = Volley.newRequestQueue(this);
rfidConfig = UgiRfidConfiguration.INVENTORY_SHORT_RANGE;
epcAdapter = new EPCAdapter(this);
tagListView.setAdapter(epcAdapter);
updateUI();
}
public class EPCAdapter extends BaseAdapter implements Filterable {
rfid_status rfidStatus;
List<UgiTag> origTags;
EPCAdapter(rfid_status rfidStatus) {
super();
this.rfidStatus = rfidStatus;
}
class TagHolder {
TextView tagNumber, tagDetails, tagStatus;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public int getCount() {
return tagArray.size();
}
#Override
public Object getItem(int position) {
return position < tagArray.size() ? tagArray.get(position) : null;
}
#Override
public long getItemId(int position) {
return position < tagArray.size() ? tagArray.get(position).getEpc().hashCode() : 0;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final TagHolder tagHolder;
final UgiTag ugiTag = tagArray.get(position);
final String tagTitle = ugiTag.toString().substring(14);
Uri.Builder jsonBuild = new Uri.Builder();
jsonBuild.scheme("http").authority("thirdstreamv2").appendPath("utilities").appendPath("HandheldGreenScreen").appendQueryParameter("assetid", tagTitle);
String jsonURL = jsonBuild.build().toString();
if (convertView == null) {
convertView = LayoutInflater.from(rfid_status.this).inflate(R.layout.tag_row, null);
tagHolder = new TagHolder();
tagHolder.tagNumber = (TextView) convertView.findViewById(R.id.tagHere);
tagHolder.tagStatus = (TextView) convertView.findViewById(R.id.statHere);
tagHolder.tagDetails = (TextView) convertView.findViewById(R.id.descHere);
convertView.setTag(tagHolder);
} else {
tagHolder = (TagHolder) convertView.getTag();
}
JsonObjectRequest jObj = new JsonObjectRequest(Request.Method.GET, jsonURL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String displayIf = response.getString("display");
if (!displayIf.equals("true")) {
tagArray.remove(ugiTag);
notifyDataSetChanged();
} else {
tagHolder.tagNumber.setText(tagTitle);
tagHolder.tagStatus.setText(response.getString("status"));
// I need to filter by the above somehow...
tagHolder.tagDetails.setText(response.getString("description"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
rQ.add(jObj);
return convertView;
}
#Override
public Filter getFilter() {
return new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
tagArray = (List<UgiTag>) results.values;
notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
List<UgiTag> filteredTags = new ArrayList<>();
constraint = constraint.toString();
if (origTags == null) {
origTags = new ArrayList<>(tagArray);
}
if (constraint.length() == 0) {
results.count = origTags.size();
results.values = origTags;
} else {
for (int position = 0; position < origTags.size(); position++) {
UgiTag ugiTag = origTags.get(position);
String tagString = ugiTag.toString().substring(14);
if (tagString.contains(constraint)) {
filteredTags.add(ugiTag);
}
}
results.count = filteredTags.size();
results.values = filteredTags;
}
return results;
}
};
}
}
Never mind, answered it myself. I trashed my old array and created a new one using a custom object I put together to store the JSON responses instead of listing only the RFID tags (UgiTag). With the values being in the object, I can now access them within the filter and use it as a constraint.
public class EPCAdapter extends BaseAdapter implements Filterable {
rfid_status rfidStatus;
List<TagInfo> origTags = null;
EPCAdapter(rfid_status rfidStatus) {
super();
this.rfidStatus = rfidStatus;
}
class TagHolder {
TextView tagNumber, tagDetails, tagStatus;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public int getCount() {
return tagList.size();
}
#Override
public Object getItem(int position) {
return position < tagList.size() ? tagList.get(position) : null;
}
#Override
public long getItemId(int position) {
return position < tagList.size() ? tagList.get(position).hashCode() : 0;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final TagInfo tagItem = tagList.get(position);
final String tagTitle = tagItem.getUgiTag().toString().substring(14);
final TagHolder tagHolder;
Uri.Builder jsonBuild = new Uri.Builder();
jsonBuild.scheme("http").authority("thirdstreamv2").appendPath("utilities").appendPath("HandheldGreenScreen").appendQueryParameter("assetid", tagTitle);
String jsonURL = jsonBuild.build().toString();
if (convertView == null) {
convertView = LayoutInflater.from(rfid_status.this).inflate(R.layout.tag_row, null);
tagHolder = new TagHolder();
tagHolder.tagNumber = (TextView) convertView.findViewById(R.id.tagHere);
tagHolder.tagStatus = (TextView) convertView.findViewById(R.id.statHere);
tagHolder.tagDetails = (TextView) convertView.findViewById(R.id.descHere);
convertView.setTag(tagHolder);
} else {
tagHolder = (TagHolder) convertView.getTag();
}
JsonObjectRequest jObj = new JsonObjectRequest(Request.Method.GET, jsonURL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
tagItem.setTagStatus(response.getString("status"));
tagItem.setTagDescription(response.getString("description"));
tagItem.setTagDisplay(response.getString("display"));
tagHolder.tagNumber.setText(tagTitle);
tagHolder.tagStatus.setText(tagItem.getTagStatus());
tagHolder.tagDetails.setText(tagItem.getTagDescription());
if (!tagItem.getTagDisplay().equals("true")) {
tagList.remove(tagItem);
notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
rQ.add(jObj);
return convertView;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
List<TagInfo> filteredTags = new ArrayList<>();
constraint = constraint.toString();
if (origTags == null) {
origTags = new ArrayList<>(tagList);
}
if (constraint.length() == 0) {
results.count = origTags.size();
results.values = origTags;
} else {
for (int position = 0; position < origTags.size(); position++) {
TagInfo origPos = origTags.get(position);
String tagString = origPos.getTagStatus();
if (tagString.contains(constraint)) {
filteredTags.add(origPos);
}
}
results.count = filteredTags.size();
results.values = filteredTags;
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
tagList = (List<TagInfo>) results.values;
notifyDataSetChanged();
}
};
}
}
Currently i can search only one string word. example, I need to search for multiple words i type "nougat,donut" and they show me these two? What i need to put in code for this to work?
DataAdapter.java
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> implements Filterable {
private ArrayList<AndroidVersion> mArrayList;
private ArrayList<AndroidVersion> mFilteredList;
public DataAdapter(ArrayList<AndroidVersion> arrayList) {
mArrayList = arrayList;
mFilteredList = arrayList;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {
viewHolder.tv_name.setText(mFilteredList.get(i).getName());
viewHolder.tv_version.setText(mFilteredList.get(i).getVer());
viewHolder.tv_api_level.setText(mFilteredList.get(i).getApi());
}
#Override
public int getItemCount() {
return mFilteredList.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
mFilteredList = mArrayList;
} else {
ArrayList<AndroidVersion> filteredList = new ArrayList<>();
for (AndroidVersion androidVersion : mArrayList) {
if (androidVersion.getApi().toLowerCase().contains(charString) || androidVersion.getName().toLowerCase().contains(charString) || androidVersion.getVer().toLowerCase().contains(charString)) {
filteredList.add(androidVersion);
}
}
mFilteredList = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = mFilteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
mFilteredList = (ArrayList<AndroidVersion>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView tv_name,tv_version,tv_api_level;
public ViewHolder(View view) {
super(view);
tv_name = (TextView)view.findViewById(R.id.tv_name);
tv_version = (TextView)view.findViewById(R.id.tv_version);
tv_api_level = (TextView)view.findViewById(R.id.tv_api_level);
}
}
json recycler view
this is search but only for one word
you can try this
if (charString.contains(",")) {
String searchChar[] = charString.split(",");
for (int i = 0; i < searchChar.length; i++) {
if (androidVersion.getApi().toLowerCase().contains(searchChar[i]) || androidVersion
.getName()
.toLowerCase().contains(searchChar[i]) || androidVersion.getVer().toLowerCase()
.contains(searchChar[i])) {
filteredList.add(androidVersion);
}
}
} else {
if (androidVersion.getApi().toLowerCase().contains(charString) || androidVersion.getName()
.toLowerCase().contains(charString) || androidVersion.getVer().toLowerCase()
.contains(charString)) {
filteredList.add(androidVersion);
}
}
replace the code :
if (androidVersion.getApi().toLowerCase().contains(charString) ||
androidVersion.getName().toLowerCase().contains(charString) ||
androidVersion.getVer().toLowerCase().contains(charString)) {
filteredList.add(androidVersion);
}
You need to add some pre-processing to determine if there are multiple values
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String splitter = ",";
final String[] multipleValues = charSequence.toString().split(splitter);
//your null check
List<AndroidVersions> filteredList = new ArrayList()
for (String value : multipleValues) {
filteredList.addAll(internalFilter(mArrayList, value));
}
//the rest of your code
}
private List<AndroidVersions> internalFilter(ArrayList<AndroidVersions> listToFilter, String value) {
List<AndroidVersions> filteredList = new ArrayList()
for (AndroidVersion androidVersion : listToFilter) {
if (androidVersion.getApi().toLowerCase().contains(value)
|| androidVersion.getName().toLowerCase().contains(value)
|| androidVersion.getVer().toLowerCase().contains(value)) {
filteredList.add(androidVersion);
}
}
return filteredList;
}
This code will also work perfectly fine with only 1 value
I have 3 spinners in my project named standard, division and age. They contain values from json data. When I select a value from each individual spinner it shows all data of students in a listview respectivly (fetched from json).
I'm working with the following JSON data:
[
{
"name":"aarti",
"surname":"singh",
"age":"18",
"div":"A",
"standard":"7"
},
{
"name":"seema",
"surname":"desai",
"age":"17",
"div":"B",
"standard":"7"
},
{
"name":"tina",
"surname":"joshi",
"age":"18",
"div":"A",
"standard":"8"
},
{
"name":"megha",
"surname":"kale",
"age":"17",
"div":"A",
"standard":"7"
},
{
"name":"swati",
"surname":"marathe",
"age":"18",
"div":"A",
"standard":"8"
},
{
"name":"rekha",
"surname":"surve",
"age":"17",
"div":"A",
"standard":"7"
},
{
"name":"madhu",
"surname":"dalvi",
"age":"18",
"div":"B",
"standard":"6"
}
I am trying to do it like this way:
When I select standard 7 from the spinner it should display students information studying in 7th standard ("aarti", "seema", "megha", "rekha") and their other information too.
Then I am selecting value from division spinner say "A", it should take above result granted and accordingly display students from standard 7 and division "A". It should shows the result as ("aarti", "megha", "rekha") and their other informations too.
Finally when I am selecting value from age spinner say "17", it should take above result granted and accordingly display students from standard 7 and division "A" and age "17". Accordingly it shows "megha" and "rekha".
Can anyone please assist me
This is my MainActivity.java class:
public class MainActivity extends AppCompatActivity {
ArrayList<String> AllStandards = new ArrayList<>();
ArrayList<String> AllDivision = new ArrayList<>();
ArrayList<String> AllAge = new ArrayList<>();
JSONArray jsonArray;
Spinner spinner_std, spinner_div, spinner_age;
private ArrayList<StudInfo> studentVOList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final List<String> item_Std = getStandard("data.json");
final List<String> items_div = getDivision("data.json");
final List<String> items_age = getAge("data.json");
/*spinner for standard*/
spinner_std = (Spinner) findViewById(R.id.spinnerStandard);
ArrayAdapter<String> adapter_std = new ArrayAdapter<String>(this, R.layout.spinner_standard_layout, R.id.textViewStandard, item_Std);
adapter_std.getFilter().filter(txt);
spinner_std.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
try {
String standard = AllStandards.get(i);
if (studentVOList.size() > 0)
studentVOList.clear();
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject jsonObject = jsonArray.getJSONObject(j);
String stand = jsonObject.getString("standard");
if (stand.equalsIgnoreCase(standard)) {
StudInfo studentVO = new StudInfo();
studentVO.setName(jsonObject.getString("name"));
studentVO.setSurname(jsonObject.getString("surname"));
studentVO.setAge(jsonObject.getString("age"));
studentVO.setDiv(jsonObject.getString("div"));
studentVO.setStandard(jsonObject.getString("standard"));
studentVO.setStandard(stand);
studentVOList.add(studentVO);
}
}
// Log.d("TAG", "List With All Students in selected standard: " + studentVOList.size());
Intent intent = new Intent(getApplicationContext(), StudentsInfo.class);
Bundle b = new Bundle();
b.putSerializable("list", studentVOList);
intent.putExtra("bundle", b);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spinner_std.setAdapter(adapter_std);
/*spinner for division*/
spinner_div = (Spinner) findViewById(R.id.spinnerDiv);
ArrayAdapter<String> adapter_div = new ArrayAdapter<String>(this, R.layout.spinner_division_layout, R.id.textViewDivision, items_div);
adapter_div.getFilter().filter(txt);
spinner_div.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
try {
String division = AllDivision.get(i);
if (studentVOList.size() > 0)
studentVOList.clear();
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject jsonObject = jsonArray.getJSONObject(j);
String div = jsonObject.getString("div");
// Collections.sort(AllDivision);
if (div.equalsIgnoreCase(division)) {
StudInfo studentVO = new StudInfo();
studentVO.setName(jsonObject.getString("name"));
studentVO.setSurname(jsonObject.getString("surname"));
studentVO.setAge(jsonObject.getString("age"));
studentVO.setStandard(jsonObject.getString("standard"));
studentVO.setDiv(jsonObject.getString("div"));
studentVO.setDiv(div);
studentVOList.add(studentVO);
}
}
Intent intent = new Intent(getApplicationContext(), StudentsInfo.class);
Bundle b = new Bundle();
b.putSerializable("list", studentVOList);
intent.putExtra("bundle", b);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spinner_div.setAdapter(adapter_div);
/*spinner for age*/
spinner_age = (Spinner) findViewById(R.id.spinerAge);
ArrayAdapter<String> adapter_age = new ArrayAdapter<String>(this, R.layout.spinner_age_layout, R.id.textViewAge, items_age);
adapter_age.getFilter().filter(txt);
spinner_age.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
try {
String age = AllAge.get(i);
if (studentVOList.size() > 0)
studentVOList.clear();
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject jsonObject = jsonArray.getJSONObject(j);
String age_list = jsonObject.getString("age");
Collections.sort(AllAge);
if (age_list.equalsIgnoreCase(age)) {
StudInfo studentVO = new StudInfo();
studentVO.setName(jsonObject.getString("name"));
studentVO.setSurname(jsonObject.getString("surname"));
studentVO.setDiv(jsonObject.getString("div"));
studentVO.setStandard(jsonObject.getString("standard"));
studentVO.setAge(jsonObject.getString("age"));
studentVO.setAge(age_list);
studentVOList.add(studentVO);
}
}
Intent intent = new Intent(getApplicationContext(), StudentsInfo.class);
Bundle b = new Bundle();
b.putSerializable("list", studentVOList);
intent.putExtra("bundle", b);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spinner_age.setAdapter(adapter_age);
}//onCreate Method
private List<String> getStandard(String fileName) {
jsonArray = null;
try {
InputStream is = getResources().getAssets().open(fileName);
int size = is.available();
byte[] data = new byte[size];
is.read(data);
is.close();
String json = new String(data, "UTF-8");
// AllStandards.clear();
try {
jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String stand = jsonObject.getString("standard");
if (!AllStandards.contains(stand)) {
AllStandards.add(stand);
}
}
} catch (JSONException je) {
je.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return AllStandards;
}
private List<String> getDivision(String fileName) {
jsonArray = null;
try {
InputStream is = getResources().getAssets().open(fileName);
int size = is.available();
byte[] data = new byte[size];
is.read(data);
is.close();
String json = new String(data, "UTF-8");
try {
jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String stand = jsonObject.getString("div");
if (!AllDivision.contains(stand)) {
AllDivision.add(stand);
}
}
} catch (JSONException je) {
je.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return AllDivision;
}
private List<String> getAge(String fileName) {
jsonArray = null;
try {
InputStream is = getResources().getAssets().open(fileName);
int size = is.available();
byte[] data = new byte[size];
is.read(data);
is.close();
String json = new String(data, "UTF-8");
try {
jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String stand = jsonObject.getString("age");
if (!AllAge.contains(stand)) {
AllAge.add(stand);
}
}
} catch (JSONException je) {
je.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return AllAge;
}
this is my ListAdapter.java class
public class ListAdapter extends ArrayAdapter<StudInfo> {
int vg;
ArrayList<StudInfo> list;
Context context;
public ListAdapter(Context context, int vg, int id, ArrayList<StudInfo> list) {
super(context, vg, id, list);
this.context = context;
this.vg = vg;
this.list = list;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(vg, parent, false);
TextView textViewName = (TextView) itemView.findViewById(R.id.txtName);
TextView textViewSurname = (TextView)itemView.findViewById(R.id.txtSurname);
TextView textViewAge = (TextView) itemView.findViewById(R.id.txtAge);
TextView textViewDiv = (TextView) itemView.findViewById(R.id.txtDiv);
TextView textViewStd = (TextView) itemView.findViewById(R.id.txtStandard);
textViewName.setText(list.get(position).getName());
textViewSurname.setText(list.get(position).getSurname());
textViewAge.setText(list.get(position).getAge());
textViewDiv.setText(list.get(position).getDiv());
textViewStd.setText(list.get(position).getStandard());
return itemView;
}
}
this is my StudentsInfo.java class
public class StudentsInfo extends Activity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.studentsinfo_layout);
Bundle b = getIntent().getBundleExtra("bundle");
ArrayList<StudInfo> studentVOList = (ArrayList<StudInfo>) b.getSerializable("list");
ListView listView = (ListView) findViewById(R.id.listViewShow);
ListAdapter listAdapter = new ListAdapter(this, R.layout.list_layout, R.id.txtName, studentVOList);
listView.setAdapter(listAdapter);
}
}
this is my StudInfo.java class,
import java.io.Serializable;
public class StudInfo implements Serializable
{
private String name;
private String surname;
private String age;
private String div;
private String standard;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getDiv() {
return div;
}
public void setDiv(String div) {
this.div = div;
}
public String getStandard() {
return standard;
}
public void setStandard(String standard) {
this.standard = standard;
}
}
i tried googling to find out solution but the questions i found all are based on searching listview items using edittext.i didn't found ant similar post matching with my question which solve my problem.can anyone please help me to solve this??
1. Override getFilter method in your adapter class
2. Use adapter.getFilter().filter(txt) in your spinner selection
package com.hughesnet.adapters;
import com.hughesnet.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.TextView;
import java.util.ArrayList;
public class ListAdapter extends ArrayAdapter<StudInfo> {
int vg;
ArrayList<StudInfo> list;
Context context;
ItemFilter mFilter;
ArrayList<StudInfo> filteredData;
public ListAdapter (Context context, int vg, int id, ArrayList<StudInfo> list) {
super (context, vg, id, list);
this.context = context;
this.vg = vg;
this.list = list;
}
public View getView (int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate (vg, parent, false);
TextView textViewName = (TextView) itemView.findViewById (R.id.txtName);
TextView textViewSurname = (TextView) itemView.findViewById (R.id.txtSurname);
TextView textViewAge = (TextView) itemView.findViewById (R.id.txtAge);
TextView textViewDiv = (TextView) itemView.findViewById (R.id.txtDiv);
TextView textViewStd = (TextView) itemView.findViewById (R.id.txtStandard);
textViewName.setText (list.get (position).getName ());
textViewSurname.setText (list.get (position).getSurname ());
textViewAge.setText (list.get (position).getAge ());
textViewDiv.setText (list.get (position).getDiv ());
textViewStd.setText (list.get (position).getStandard ());
return itemView;
}
ItemFilter mFilter = new ItemFilter ();
public Filter getFilter () {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering (CharSequence constraint) {
String filterString = constraint.toString ().toLowerCase ();
FilterResults results = new FilterResults ();
int count = list.size ();
final ArrayList<StudInfo> nlist = new ArrayList<StudInfo> (count);
String filterableString;
for (int i = 0; i < count; i++) {
StudInfo info = list.get (i);
// Check for standard, division and age here
if (info.getAge().contains(filterString) || info.getStandard().contains(filterString ) || info.getDiv().contains(filterString )) {
nlist.add (filterableString);
}
}
results.values = nlist;
results.count = nlist.size ();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<StudInfo>) results.values;
notifyDataSetChanged();
}
}
}