JSONArray cannot be cast to java.util.ArrayList - java

I am writing ad Adapter class with a Filter and I get this error in publishResults method.
The list is loaded, when I type something in filter, it starts filtering, but when deleting chars and reaching 0 length, the app crash with this error, moreover some of imageView (CardView type) are inverted, so maybe I'm doing something wrong in parsing too.
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 ){
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();
}
}
}

The problem occurs in your performFiltering(CharSequence constraint) when you return a JSONArray object instead a ArrayList in the first if statement
To fix it do this changes:
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++) {
arrColorList.add(colorList.getJSONObject(i).getString("Name"));
}
Result.values = arrColorList;
Result.count = arrColorList.size();
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();
}
}

Related

search from editText in recyclerview where i am getting items from API using retrofit

I found many solution bute they searching in only given list aor may they search through searchview.But In my case I have to search using edite text. search from editText in recyclerview where i am getting items from API using retrofit.here is my code of recyclerview adapter and the class..
i want to filter list of collectionpoint on the basis of name .
thanx in advance
private List<CollectionPoint> collectionPointList;
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView collectionPointId, collectionPointName;
private int collectionPointID;
MyViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
collectionPointId = (TextView) itemView.findViewById(R.id.txtCollectionPointID);
collectionPointName = (TextView) itemView.findViewById(R.id.txtCollectionPointName);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(itemView.getContext(), Appointments.class);`
intent.putExtra("CollectionPointID", collectionPointID);
Appointments.CollectionPointID = collectionPointID;
FragmentProcedure.CollectionPointID = collectionPointID;
itemView.getContext().startActivity(intent);
}
}
public CollectionPointAdapter(List<CollectionPoint> collectionPointList1) {
this.collectionPointList = collectionPointList1;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.collectionpointlistitems, viewGroup, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
CollectionPoint collectionPoint = collectionPointList.get(position);
holder.collectionPointId.setText("ID - " + String.valueOf(collectionPoint.getID()));
holder.collectionPointName.setText(collectionPoint.getName());
holder.collectionPointID = collectionPointList.get(position).getID();
}
#Override
public int getItemCount() {
return collectionPointList.size();
}
public void filterList(ArrayList<CollectionPoint> filteredList) {
collectionPointList = filteredList;
notifyDataSetChanged();
}
Activity :
RecyclerView recyclerView;
public static GetCollectionPointByUserIDResponse getCollectionPointByUserIDResponse = new GetCollectionPointByUserIDResponse();
private List<CollectionPoint> collectionPointList = new ArrayList<>();
CollectionPointAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection_point);
getCollectionPoints();
recyclerView = findViewById(R.id.collectionPointRecyclerView);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.addItemDecoration(new DividerItemDecoration(getApplicationContext(), LinearLayoutManager.VERTICAL));
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
TextView logout = findViewById(R.id.logout);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(CollectionPoints.this, Login.class);
startActivity(intent);
}
});
EditText editText = findViewById(R.id.search);
/* editText.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) {
}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});*/
}
private void filter(String text) {
ArrayList<CollectionPoint> filteredList = new ArrayList<>();
for (CollectionPoint item : filteredList) {
if (item.getName().toLowerCase().contains(text.toLowerCase())) {
filteredList.add(item);
}
}
mAdapter.filterList(filteredList);
}
private void getCollectionPoints() {
GetCollectionPointByUserIDResquest request = new GetCollectionPointByUserIDResquest();
request.Token = Login.session.Token;
request.SessionID = Login.session.ID;
request.UserID = Login.loginResponse.UserInfo.get(0).ID;
request.MethodName = "GetCollectionPointBuUserID";
BusinessService businessService = APIClient.getClient().create(BusinessService.class);
Call<GetCollectionPointByUserIDResponse> call = businessService.GetCollectionPointBuUserID(request);
call.enqueue(new Callback<GetCollectionPointByUserIDResponse>() {
#Override
public void onResponse(Call<GetCollectionPointByUserIDResponse> call, Response<GetCollectionPointByUserIDResponse> response) {
try {
if (response.isSuccessful()) {
getCollectionPointByUserIDResponse = response.body();
assert getCollectionPointByUserIDResponse != null;
if (getCollectionPointByUserIDResponse.ResponseCode == 1) {
collectionPointList = new ArrayList<>(getCollectionPointByUserIDResponse.getCollectionpoint());
CollectionPointAdapter collectionPointAdapter = new CollectionPointAdapter(collectionPointList);
recyclerView.setAdapter(collectionPointAdapter);
} else if (getCollectionPointByUserIDResponse.ResponseCode == 6) {
Intent intent = new Intent(CollectionPoints.this, Login.class);
startActivity(intent);
} else {
Toast.makeText(CollectionPoints.this, getCollectionPointByUserIDResponse.ResponseMessage, Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
Toast.makeText(CollectionPoints.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<GetCollectionPointByUserIDResponse> call, Throwable t) {
Toast.makeText(CollectionPoints.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
You can filter Recyclerview items from editText by calling filter method in addTextChangedListener and passing arraylist to your Adapter class like below code :
Private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(yourLayout);
context = YourActivity.this;
editText_filter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
try {
if (CollectionPointAdapter != null)
//Calling Adapter method
CollectionPointAdapter.getFilter().filter(editable);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void setNoDataVisible(int size) { //IF results empty handle UI from adapter.
try {
if (size == 0) {
txtView_noData.setVisibility(View.VISIBLE);
} else {
txtView_noData.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void getCollectionPoints() {
GetCollectionPointByUserIDResquest request = new GetCollectionPointByUserIDResquest();
request.Token = Login.session.Token;
request.SessionID = Login.session.ID;
request.UserID = Login.loginResponse.UserInfo.get(0).ID;
request.MethodName = "GetCollectionPointBuUserID";
BusinessService businessService = APIClient.getClient().create(BusinessService.class);
Call<GetCollectionPointByUserIDResponse> call = businessService.GetCollectionPointBuUserID(request);
call.enqueue(new Callback<GetCollectionPointByUserIDResponse>() {
#Override
public void onResponse(Call<GetCollectionPointByUserIDResponse> call, Response<GetCollectionPointByUserIDResponse> response) {
try {
if (response.isSuccessful()) {
getCollectionPointByUserIDResponse = response.body();
assert getCollectionPointByUserIDResponse != null;
if (getCollectionPointByUserIDResponse.ResponseCode == 1) {
collectionPointList = new ArrayList<>(getCollectionPointByUserIDResponse.getCollectionpoint());
//Here You're passing List to Adatper, so that we can filter it.
CollectionPointAdapter collectionPointAdapter = new CollectionPointAdapter(context, collectionPointList);
recyclerView.setAdapter(collectionPointAdapter);
} else if (getCollectionPointByUserIDResponse.ResponseCode == 6) {
Intent intent = new Intent(CollectionPoints.this, Login.class);
startActivity(intent);
} else {
Toast.makeText(CollectionPoints.this, getCollectionPointByUserIDResponse.ResponseMessage, Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
Toast.makeText(CollectionPoints.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<GetCollectionPointByUserIDResponse> call, Throwable t) {
Toast.makeText(CollectionPoints.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
Change your Adapter like below code :
public class CollectionPointAdapter extends RecyclerView.Adapter<CollectionPointAdapter.MyViewHolder> implements Filterable {
private Context mContext;
private ArrayList<CollectionPoint> collectionPointResults;
private ArrayList<CollectionPoint> mFilteredList;
public CollectionPointAdapter(Context mContext, ArrayList<CollectionPoint> collectionPointResults) {
this.mContext = mContext;
this.collectionPointResults = collectionPointResults;
this.mFilteredList = collectionPointResults;
}
#Override
public int getItemCount() {
return mFilteredList.size();
}
#Override
public long getItemId(int position) {
return position;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.item_list_yours, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
try {
holder.collectionPointId.setText("ID - " + String.valueOf(mFilteredList.get(position).getID()));
holder.collectionPointName.setText(mFilteredList.get(position).getName());
} catch (Exception e) {
e.printStackTrace();
}
}
//Filter the adapter interface
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
try {
String charString = charSequence.toString();
if (charString.isEmpty()) {
mFilteredList = collectionPointResults;
} else {
ArrayList<RefLeadsgivenResult> filteredList = new ArrayList<>();
for (RefLeadsgivenResult row : collectionPointResults) {
if (row.getName().toLowerCase().contains(charString)) { //Searching by Name
filteredList.add(row);
}
}
mFilteredList = filteredList;
}
} catch (IndexOutOfBoundsException ie) {
ie.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
FilterResults filterResults = new FilterResults();
filterResults.values = mFilteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
try {
mFilteredList = (ArrayList<RefLeadsgivenResult>) filterResults.values;
notifyDataSetChanged();
((YourActivity) mContext).setNoDataVisible(mFilteredList.size());
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
class MyViewHolder extends RecyclerView.ViewHolder {
public final View mView;
#BindView(R.id.collectionPointId)
TextView collectionPointId;
#BindView(R.id.collectionPointName)
TextView collectionPointName;
public MyViewHolder(View itemView) {
super(itemView);
mView = itemView;
ButterKnife.bind(this, itemView);
}
}
}

RecyclerView search filter is not working

I want to filter some ArrayList of datas with search,
In my Activity's onCreate:
arrayList = getListItemData();
filteredArrayList = new ArrayList<>();
filteredArrayList.addAll(arrayList);
adapter = new NameAdapter(filteredArrayList);
itemList.setAdapter(adapter);
searchBox.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) {
adapter.getFilter().filter(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
my adapter with filterable:
public class NameAdapter extends RecyclerView.Adapter<NameAdapter.ViewHolder> implements Filterable {
private ArrayList<Name> arrayList;
private CustomFilter filter;
public NameAdapter(ArrayList<Branch> items) {
arrayList = items;
filter = new CustomFilter(NameAdapter.this);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_name, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.data = arrayList.get(position);
}
#Override
public int getItemCount() {
return branchArrayList.size();
}
#Override
public Filter getFilter() {
return filter;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View view;
public final TextView branch;
public Name data;
public ViewHolder(View view) {
super(view);
this.view = view;
branch = view.findViewById(R.id.textView_name);
}
}
public class CustomFilter extends Filter {
private NameAdapter adapter;
private CustomFilter(NameAdapter adapter) {
super();
this.adapter = adapter;
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
filteredArrayList.clear();
final FilterResults results = new FilterResults();
if (constraint.length() == 0) {
filteredArrayList.addAll(arrayList);
} else {
final String filterPattern = constraint.toString().toLowerCase().trim();
for (final Name name : arrayList) {
if (name.getName().toLowerCase().startsWith(filterPattern)) {
filteredBranchArrayList.add(name);
}
}
}
results.values = filteredArrayList;
results.count = filteredArrayList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
this.adapter.notifyDataSetChanged();
}
}
}
filter doesn't work for some reason it clears the recyclerview when I type something
1st make a copy of the branchArrayList in the constructor.like this :-
private ArrayList<Branch> branchCopy = new ArrayList<>;
public BranchAdapter(ArrayList<Branch> items) {
branchArrayList = items;
branchCopy.addAll(items);
filter = new CustomFilter(BranchAdapter.this);
}
your performingFilter
#Override
protected FilterResults performFiltering(CharSequence constraint) {
ArrayList<Branch> branchFilter = new ArrayList<>;
final FilterResults results = new FilterResults();
if (constraint.length() == 0) {
branchFilter.addAll(branchArrayList);
} else {
final String filterPattern = constraint.toString().toLowerCase().trim();
for (final Branch branch : branchCopy) {
if (branch.getBranchName().toLowerCase().startsWith(filterPattern)) {
branchFilter.add(branch);
}
}
}
results.values = branchFilter ;
results.count = branchFilter.size();
return results;
}
Your publishResults
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
branchArrayList = (ArrayList<Branch>) results.values; // you have done nothing with the filter results
notifyDataSetChanged();
}
Before notifying change the mainList !!
branchArrayList = (ArrayList<Branch>) results.values;
add this line to publishResults
You have done NOTHING with the filter results
Try to change your Adapter as
public class BranchAdapter extends RecyclerView.Adapter<BranchAdapter.ViewHolder> implements Filterable {
private ArrayList<Branch> mArrayList;
private ArrayList<Branch> mFilteredList;
private CustomFilter filter;
public BranchAdapter(ArrayList<Branch> items) {
mArrayList = items;
mFilteredList = items;
filter = new CustomFilter(BranchAdapter.this);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_branch, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.data = branchArrayList.get(position);
holder.branch.setText(String.valueOf(mArrayList.get(position).getBranchCode() + " / " + mArrayList.get(position).getBranchName()));
}
#Override
public int getItemCount() {
return mFilteredList.size();
}
#Override
public Filter getFilter() {
return filter;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View view;
public final TextView branch;
public Branch data;
public ViewHolder(View view) {
super(view);
this.view = view;
branch = view.findViewById(R.id.textView_branch);
}
}
public class CustomFilter extends Filter {
private BranchAdapter adapter;
private CustomFilter(BranchAdapter adapter) {
super();
this.adapter = adapter;
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
mFilteredList = mArrayList;
} else {
ArrayList<Branch> filteredList = new ArrayList<>();
for (Branch branch : mArrayList) {
if (branch.getBranchName().toLowerCase().contains(charString)) {
filteredList.add(branch);
}
}
mFilteredList = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = mFilteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mFilteredList = (ArrayList<Branch>) filterResults.values;
notifyDataSetChanged();
// this.adapter.notifyDataSetChanged();
}
}
}
update your branchArrayList in the publishResults method before doing notifyDataSetChanged
update your PublishResults() with below code
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
filteredBranchArrayList = (ArrayList<Branch>) filterResults.values;
notifyDataSetChanged();
}

How to apply filter in recyclerview based on spinner item selection?

Hi i got a situation that to load images in an activity based on spinner selection. Here i will get those images as an ArrayList and spinner values from api. I dont know how to apply filter here based on spinner selection. Kindly come up with a solution. Below s my code.
For Activity:
public class MedicalRecordsActivity extends BaseActivity implements MedicalRecordsView {
#Inject
MedicalRecordsPresenter mPresenter;
#Bind(R.id.back_img_rl)
RelativeLayout backImage;
#Bind(R.id.tv_toolbartitle)
TextView header;
#Bind(R.id.upload_btn_layout)
RelativeLayout uploadBtnLayout;
#Bind(R.id.spinner_industry)
Spinner categorySpinner;
#Bind(R.id.images_recycler_view)
RecyclerView recyclerView;
List<MemberImageModel> arrayList;
String patientID, imageType, title;
EditText fileName;
ProgressDialog categoryProgress, uploadProgress;
List<String> uploadTypesList;
ArrayAdapter<String> categoryAdapter;
static String selectedSpinnerItem;
File imageProfileFile;
List<ProfileImagesModel> membersList;
MedicalRecordsAdapter dataAdapter = null;
List<String> Prescription = new ArrayList<>();
private static final int RC_CAMERA_PERM = 123;
private static final int RC_GALLERY = 124;
private static final int RC_SETTINGS_SCREEN = 125;
private static final int RC_WRITE_EXTERNAL_STORAGE = 126;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medical_records);
ButterKnife.bind(this);
activityComponent().inject(this);
mPresenter.attachView(this);
header.setText("Medical Records");
uploadBtnLayout.setVisibility(View.VISIBLE);
patientID = PrefUtils.getPatientID(this);
categoryProgress = new ProgressDialog(this);
categoryProgress.setMessage(getString(R.string.loading));
uploadProgress = new ProgressDialog(this);
uploadProgress.setMessage(getString(R.string.file_uploading));
}
#Override
public void onResume() {
super.onResume();
callGetProfileApi();
callUploadTypesApi();
}
#Override
public void onBackPressed() {
finish();
}
#OnClick(R.id.back_img_rl)
public void onBackClicked() {
finish();
}
#Override
public void getRecordType(UploadTypes response) {
if (response != null) {
if (response.isSuccess()) {
uploadTypesList = new ArrayList<>();
for (UploadTypes.TypesInfo typesInfo : response.getResponseObject()) {
uploadTypesList.add(typesInfo.getDocumentname());
}
loadSpinner(uploadTypesList);
categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedSpinnerItem = uploadTypesList.get(position);
dataAdapter.getFilter().filter(selectedSpinnerItem);
//callGetProfileApi();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
}
#Override
public void showCategoryProgress() {
categoryProgress.show();
}
#Override
public void hideCategoryProgress() {
categoryProgress.dismiss();
}
#Override
public void showUploadProgress() {
uploadProgress.show();
}
#Override
public void hideUploadProgress() {
uploadProgress.dismiss();
}
#Override
public void showProfile(ProfileResponse response) {
if (response != null) {
if (response.isSuccess()) {
membersList = response.getResponseObject().get(0).getImages();
setAdapter();
}
}
}
#Override
public void showProgress() {
}
#Override
public void hideProgress() {
}
#Override
public void showNoInternet() {
}
#Override
public void showNoData() {
}
#Override
public void showError() {
}
private void callUploadTypesApi() {
mPresenter.getRecordType(ApiConstants.PLATFORM_VAL, patientID, ApiConstants.ROLE_ID_VAL);
}
private void callGetProfileApi() {
mPresenter.getProfileDetails(patientID);
}
public static String getSelectedItem() {
return selectedSpinnerItem;
}
private void loadSpinner(List<String> categoryList) {
categoryAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, categoryList);
categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
categorySpinner.setAdapter(categoryAdapter);
}
private void setAdapter() {
try {
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
MedicalRecordsAdapter dataAdapter = new MedicalRecordsAdapter(this, membersList);
recyclerView.setAdapter(dataAdapter);
/* dataAdapter.getFilter().filter(selectedSpinnerItem);
dataAdapter.notifyDataSetChanged();*/
} catch (Exception e) {
e.printStackTrace();
}
}}
For Adapter:
public class MedicalRecordsAdapter extends RecyclerView.Adapter<MedicalRecordsAdapter.ViewHolder> implements Filterable {
Context context;
List<ProfileImagesModel> membersList, filterList;
//CustomFilter filter;
public MedicalRecordsAdapter(Context context, List<ProfileImagesModel> membersList) {
this.context = context;
this.membersList = membersList;
this.filterList = membersList;
}
#Override
public MedicalRecordsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_patient_record, parent, false);
return new MedicalRecordsAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(MedicalRecordsAdapter.ViewHolder holder, int position) {
holder.recordName.setText(filterList.get(position).getTitle());
holder.recordDate.setText(filterList.get(position).getCreateddate());
String thumbnail = filterList.get(position).getImagepath();
Glide.with(context)
.load(ApiEndpoint.IMAGE_URL + thumbnail)
.into(holder.thumbnail);
}
#Override
public int getItemCount() {
return filterList.size();
}
#Override
public Filter getFilter() {
/*if (filter == null) {
filter = new CustomFilter(filterList, this);
}
return filter;*/
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String charString = constraint.toString();
if (charString.isEmpty()) {
filterList = membersList;
} else {
List<ProfileImagesModel> filteredList = new ArrayList<>();
for (ProfileImagesModel androidVersion : membersList) {
if (androidVersion.getType().contains(charString) /*|| androidVersion.getName().toLowerCase().contains(charString) || androidVersion.getVer().toLowerCase().contains(charString)*/) {
filteredList.add(androidVersion);
}
}
filterList = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = filterList;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filterList = (List<ProfileImagesModel>) results.values;
notifyDataSetChanged();
}
};
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView recordName;
private TextView recordDate;
private ImageView thumbnail;
public ViewHolder(View itemView) {
super(itemView);
recordName = (TextView) itemView.findViewById(R.id.small_card_record);
recordDate = (TextView) itemView.findViewById(R.id.small_card_date);
thumbnail = (ImageView) itemView.findViewById(R.id.imageview_small_card_thumbnail);
}
}}
Remove getFilter() method from your Adpater and add following method :
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
membersList.clear();
if (charText.length() == 0) {
membersList.addAll(filterList);
} else {
for (int i=0; i<filterList.size(); i++) {
ProfileImagesModel androidVersion = filterList.get(i);
if (androidVersion.getType().toLowerCase(Locale.getDefault()).contains(charText)) {
membersList.add(androidVersion);
}
}
}
notifyDataSetChanged();
}
And call following method in setOnItemSelectedListener()
dataAdapter.filter(selectedSpinnerItem);

cant display data in listview from arraylist

my app is getting data from server and i am displaying it in listview i wanted to add filter/search function in it. so i used filterable in baseadapter. i am getting response from server in console but nothing is displayed in listview. kindly guide me whats wrong in my code.
This is adapter class
public class Patient_Adapter extends BaseAdapter implements Filterable{
Activity context;
String[] name, age, number, dip_rate;
//for filtering use arraylists
LayoutInflater inflater;
private ValueFilter valueFilter;
ArrayList<ArrayList_get_set> arrayList;
private ArrayList<ArrayList_get_set> StringFilterList;
public Patient_Adapter(Activity applicationContext,
ArrayList<ArrayList_get_set> arrayList) {
this.context = applicationContext;
/////
this.arrayList = arrayList;
StringFilterList = arrayList;
this.inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
getFilter();
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int i) {
return arrayList.get(i).getName();
}
#Override
public long getItemId(int i) {
return 0;
}
private class Viewholder{
TextView name_
,age_
,number_
,dip_rate_
,tv_request_number;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
Viewholder viewholder;
LayoutInflater inflater = context.getLayoutInflater();
if (view == null){
viewholder = new Viewholder();
view = inflater.inflate(R.layout.patient_item_list,null);
viewholder.tv_request_number = (TextView)
view.findViewById(R.id.s_req_num);
viewholder.name_ = (TextView) view.findViewById(R.id.name);
viewholder.age_ = (TextView) view.findViewById(R.id.age);
viewholder.number_ = (TextView) view.findViewById(R.id.number);
viewholder.dip_rate_ = (TextView) view.findViewById(R.id.dip_rate);
view.setTag(viewholder);
}
else {
viewholder = (Viewholder) view.getTag();
}
// set the value in TextView
viewholder.tv_request_number.setText((name.length-position)+".");
viewholder.name_.setText(name[position]);
viewholder.age_.setText(age[position]);
viewholder.number_.setText(number[position]);
viewholder.dip_rate_.setText(dip_rate[position]);
return view;
}
//Filter Results
#Override
public Filter getFilter() {
if(valueFilter==null) {
valueFilter=new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
//Invoked in a worker thread to filter the data according to the
constraint.
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if(constraint != null && constraint.length()>0){
ArrayList<ArrayList_get_set> filterList = new ArrayList<>();
for(int i=0;i<StringFilterList.size();i++){
if((StringFilterList.get(i).getName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
ArrayList_get_set contacts = new ArrayList_get_set();
contacts.setName(StringFilterList.get(i).getName());
filterList.add(contacts);
}
}
results.count=filterList.size();
results.values=filterList;
}else{
results.count=StringFilterList.size();
results.values=StringFilterList;
}
return results;
}
//Invoked in the UI thread to publish the filtering results in the user
interface.
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
arrayList = (ArrayList<ArrayList_get_set>) results.values;
notifyDataSetChanged();
}
}
}
this is getset class
public class ArrayList_get_set {
String name
,age
,number
,dip_rate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getDip_rate() {
return dip_rate;
}
public void setDip_rate(String dip_rate) {
this.dip_rate = dip_rate;
}
}
here is my main activity
private ArrayList<ArrayList_get_set> arrayList = new
ArrayList<ArrayList_get_set>();
boolean server_check=false;
Patient_Adapter patient_adapter;
ListView simListView;
EditText search;
String[] name
,age
,number
,dip_rate;
String server_response="0"
,server_response_text
,d_number;
JSONObject jp_obj;
JSONArray jar_array;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.patient_history, container,
false );
simListView = (ListView) v.findViewById(R.id.list);
search = (EditText) v.findViewById(R.id.et_search);
//Getting Client Number from SharedPreferences
SharedPreferences preferences =
this.getActivity().getSharedPreferences("DataStore" , Context.MODE_PRIVATE);
d_number = preferences.getString("number", "Ni Mila Kuch");
if(new Check_internet_connection(getActivity()).isNetworkAvailable()){
new GetPatientsList().execute();
}
else {
Toast.makeText(getActivity(),
"Check your Internet Connection & Try again",
Toast.LENGTH_LONG).show();
}
return v;
}
//load questions
public class GetPatientsList extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Loading! Be Patient!");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
JSONObject obj = new JSONObject();
obj.put("operation", "patients");
obj.put("d_number", d_number);
JsonParser jp = new JsonParser();
String str_req = jp.multipartFormRequestForFindFriends(Url.ulr,
"UTF-8", obj, null);
jp_obj = new JSONObject(str_req);
jar_array = jp_obj.getJSONArray("JsonData");
JSONObject c;
name = new String[(jar_array.length()-1)];
age = new String[(jar_array.length()-1)];
number = new String[(jar_array.length()-1)];
dip_rate = new String[(jar_array.length()-1)];
c = jar_array.getJSONObject(0);
if (c.length() > 0) {
server_response = c.getString("response");
if (server_response.equals("0")) {
server_response_text = c.getString("response-text");
}
}
int j = 1;
if (server_response.equals("1")) {
for (int i = 0; j < jar_array.length(); i++) {
c = jar_array.getJSONObject(j);
if (c.length() > 0) {
name[i] = c.getString("name");
age[i] = c.getString("age");
number[i] = c.getString("number");
dip_rate[i] = c.getString("dip_rate");
}
j++;
}
}
server_check = true;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
progressDialog.dismiss();
if (server_check) {
if (server_response.equals("1")) {
if (name.length > 0) {
Toast.makeText(getActivity(), arrayList.size(),
Toast.LENGTH_SHORT).show();
patient_adapter = new Patient_Adapter(getActivity(),
arrayList);
simListView.setAdapter(patient_adapter);
//filtering data
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence
charSequence, int i, int i1, int i2) {
patient_adapter.getFilter().filter(charSequence);
}
#Override
public void onTextChanged(CharSequence charSequence,
int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
}
});
} else {
Toast.makeText(getActivity(), server_response_text,
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getActivity(), "Error while loading data",
Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments
different titles
getActivity().setTitle("Patient History");
}
}
Try this.
in getView() use this
viewholder.tv_request_number.setText((arrayList.size()-position)+".");
viewholder.name_.setText(arrayList.get(position).getName());
viewholder.age_.setText(arrayList.get(position).getAge());
viewholder.number_.setText(arrayList.get(position).getNumber());
viewholder.dip_rate_.setText(arrayList.get(position).getDip_rate());
then update
#Override
public Object getItem(int i) {
return arrayList.get(i);
}
viewholder.name_.setText(arrayList.get(position).getName());
get from ArrayList.

Get correct position of custom gridView Item after Filter records

After apply filter on custom gridView productsListHolder.add_to_cart.setOnClickListener did not get the correct item position, it provides the result on the basis of previous arrangement as were before filter records.
How may I able to get the correct item of gridView after filtering?
And I wonder How Filterable does work?
public class GridAdapter extends BaseAdapter implements Filterable {
public interface BtnClickListener {
public abstract void onBtnClick(String position);
}
private BtnClickListener mClickListener = null;
Context context;
private ArrayList<Products> filteredProducts;
private ArrayList<Products> products;
private ItemFilter prodFilter = null;
private LayoutInflater inflater;
public GridAdapter(Context context, ArrayList<Products> products, BtnClickListener listener) {
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.products = products;
this.filteredProducts = products;
mClickListener = listener;
}
public class ProductsListHolder{
public ImageView prod_img;
public TextView prod_price;
public Button prod_cart;
public TextView prod_desc;
public Button add_to_cart;
}
public ArrayList<Products> getProducts() {
return products;
}
public void setProducts(ArrayList<Products> products) {
this.products = products;
}
public GridAdapter(){
}
#Override
public int getCount() {
if(products!=null)
return products.size();
return 0;
}
#Override
public Object getItem(int position) {
if(products!=null && position >=0 && position<getCount() )
return products.get(position);
return null;
}
#Override
public long getItemId(int position) {
if(products!=null && position >=0 && position<getCount() ){
Products temp = products.get(position);
return products.indexOf(temp);
}
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
ProductsListHolder productsListHolder;
if(view == null){
view = inflater.inflate(R.layout.product_adapter, parent, false);
productsListHolder = new ProductsListHolder();
productsListHolder.prod_img = (ImageView) view.findViewById(R.id.prod_img);
productsListHolder.prod_price = (TextView) view.findViewById(R.id.prod_price);
productsListHolder.prod_desc = (TextView) view.findViewById(R.id.prod_desc);
productsListHolder.add_to_cart = (Button) view.findViewById(R.id.add_to_cart);
productsListHolder.add_to_cart.setTag(products.get((int) getItemId(position)).getId());
view.setTag(productsListHolder);
}
else{
productsListHolder = (ProductsListHolder) view.getTag();
}
productsListHolder.add_to_cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mClickListener != null)
mClickListener.onBtnClick((String) v.getTag());
}
});
Products product = products.get(position);
setProduct(position,productsListHolder,product);
return view;
}
private void setProduct(int position, final ProductsListHolder productsListHolder, Products p) {
Picasso.with(context).load(p.getImageResours()).into(new Target(){
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
productsListHolder.prod_img.setBackground(new BitmapDrawable(context.getResources(), bitmap));
}
#Override
public void onBitmapFailed(final Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(final Drawable placeHolderDrawable) {
}
});
productsListHolder.prod_price.setText("Rs: ".concat(Integer.toString(p.getPrice())));
productsListHolder.prod_desc.setText(p.name);
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
#Override
public Filter getFilter() {
if(prodFilter == null)
prodFilter = new ItemFilter();
return prodFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toUpperCase();
FilterResults results = new FilterResults();
final ArrayList<Products> list = filteredProducts;
int count = list.size();
final ArrayList<Products> nlist = new ArrayList<Products>(count);
Products filtPro;
if (constraint == null || constraint.length() == 0) {
results.values = filteredProducts;
results.count = filteredProducts.size();
}
else {
for (int i = 0; i < count; i++) {
filtPro = list.get(i);
if (filtPro.getName().toUpperCase().contains(filterString)) {
nlist.add(filtPro);
}
}
results.values = nlist;
results.count = nlist.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
products = (ArrayList<Products>) results.values;
notifyDataSetChanged();
}
}
}

Categories