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.
Related
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();
}
}
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);
I have one custom list view adapter loading contact list. When I open app, contacts are loading perfectly , but once I came back after scrolling to Preference Fragment, listview is empty. Though Data is collected by calling Inner class LoadContact but nothing in listview. There are three fragments. pls guide.
Code for Fragment (tab1). If u see I added adapter initialization in oncreatview as otherwise on back tab I m getting Null point exception. m I did correct here?
public class Requestor extends Fragment {
EditText targetdevice;
ListView recentlist;
List<String> recentlistarray = new ArrayList<>();
ArrayAdapter arrayAdapter;
Dialog dialog;
String targetmobile, requesttype;
private TextView tex1, remotelocation;
int deviceid;
LinearLayout contactlayout;
RadioButton radiorecent, radiocontact;
ArrayList<ContactListSelectUser> contactListSelectUsers;
List<ContactListSelectUser> temp;
// Contact List
ListView listView;
// Cursor to load contacts list
Cursor phones, email;
// Pop up
ContentResolver resolver;
SearchView search;
ContactListAdapter adapter;
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LoadContact loadContact = new LoadContact();
loadContact.execute();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) throws NullPointerException{
View view = inflater.inflate(R.layout.autolocationrequester, container, false);
targetdevice = (EditText) view.findViewById(R.id.targetdevice);
recentlist = (ListView) view.findViewById(R.id.targetlist);
remotelocation = (TextView) view.findViewById(R.id.remotelocationreq);
tex1 = (TextView) view.findViewById(R.id.tex1);
requesttype = "Location";
radiorecent = (RadioButton) view.findViewById(R.id.radiorecent);
radiocontact = (RadioButton) view.findViewById(R.id.radiocontact);
contactlayout = (LinearLayout) view.findViewById(R.id.contactlayout);
tex1 = (TextView) view.findViewById(R.id.tex1);
recentlist.setVisibility(View.GONE);
contactlayout.setVisibility(View.GONE);
tex1.setVisibility(View.GONE);
contactListSelectUsers = new ArrayList<ContactListSelectUser>();
resolver = getActivity().getApplicationContext().getContentResolver();
listView = (ListView) view.findViewById(R.id.contacts_list);
adapter = new ContactListAdapter(contactListSelectUsers, getActivity().getApplicationContext());
phones = getActivity().getApplicationContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
LoadContact loadContact = new LoadContact();
loadContact.execute();
search = (SearchView) view.findViewById(R.id.searchView);
//*** setOnQueryTextListener ***
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
adapter.filter(newText);
return false;
}
});
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
deviceid = Integer.parseInt(sharedPreferences.getString("deviceid", ""));
remotelocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
arrayAdapter = new ArrayAdapter(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, recentlistarray);
recentlist.setAdapter(arrayAdapter);
targetmobile = targetdevice.getText().toString();
new sendreqloc().execute();
targetdevice.setText("");
// Popup.smallpopup("hi", getApplicationContext());
}
});
radiorecent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
recentlist.setVisibility(View.VISIBLE);
tex1.setVisibility(View.VISIBLE);
contactlayout.setVisibility(View.GONE);
targetdevice.setText("");
}
});
radiocontact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
recentlist.setVisibility(View.GONE);
contactlayout.setVisibility(View.VISIBLE);
tex1.setVisibility(View.GONE);
targetdevice.setText("");
LoadContact loadContact = new LoadContact();
loadContact.execute();
}
});
return view;
}
public class LoadContact extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
// Get Contact list from Phone
if (phones != null) {
Log.e("count", "" + phones.getCount());
if (phones.getCount() == 0) {
// Toast.makeText(Requestor.this, "No contacts in your contact list.", Toast.LENGTH_LONG).show();
}
while (phones.moveToNext()) {
Log.d("Contact Class Called","");
Bitmap bit_thumb = null;
String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// String EmailAddr = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA2));
String image_thumb = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
try {
if (image_thumb != null) {
bit_thumb = MediaStore.Images.Media.getBitmap(resolver, Uri.parse(image_thumb));
} else {
Log.e("No Image Thumb", "--------------");
}
} catch (IOException e) {
e.printStackTrace();
}
ContactListSelectUser contactListSelectUser = new ContactListSelectUser();
contactListSelectUser.setThumb(bit_thumb);
contactListSelectUser.setName(name);
contactListSelectUser.setPhone(phoneNumber);
contactListSelectUser.setEmail(id);
// contactListSelectUser.setCheckedBox(false);
// if (!contactListSelectUsers.contains(contactListSelectUser.getPhone())) {
contactListSelectUsers.add(contactListSelectUser);
//}
}
} else {
Log.e("Cursor close 1", "----------------");
}
//phones.close();
//System.out.println(contactListSelectUsers.size());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new ContactListAdapter(contactListSelectUsers, getActivity());
listView.setAdapter(adapter);
// Select item on listclick
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("search", "here---------------- listener");
ContactListSelectUser data = contactListSelectUsers.get(i);
targetdevice.setText(data.getPhone());
}
});
listView.setFastScrollEnabled(true);
}
}
/* #Override
protected void onStop() {
super.onStop();
phones.close();
}*/
}
Custom Adapter class code:
public class ContactListAdapter extends BaseAdapter implements Filterable {
public List<ContactListSelectUser> _data;
private ArrayList<ContactListSelectUser> arraylist;
Context _c;
ViewHolder v;
RoundImage roundedImage;
private Filter filter = new CustomFilter();
public ContactListAdapter(List<ContactListSelectUser> contactListSelectUsers, Context context) {
_data = contactListSelectUsers;
_c = context;
this.arraylist = new ArrayList<ContactListSelectUser>();
this.arraylist.addAll(_data);
}
#Override
public int getCount() {
return _data.size();
}
#Override
public Object getItem(int i) {
return _data.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
View view = convertView;
if (view == null) {
LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.contact_info, null);
Log.e("Inside", "here--------------------------- In view1");
} else {
view = convertView;
Log.e("Inside", "here--------------------------- In view2");
}
v = new ViewHolder();
v.title = (TextView) view.findViewById(R.id.name);
// v.check = (CheckBox) view.findViewById(R.id.check);
v.phone = (TextView) view.findViewById(R.id.no);
v.imageView = (ImageView) view.findViewById(R.id.pic);
final ContactListSelectUser data = (ContactListSelectUser) _data.get(i);
v.title.setText(data.getName());
// v.check.setChecked(data.getCheckedBox());
v.phone.setText(data.getPhone());
// Set image if exists
try {
if (data.getThumb() != null) {
v.imageView.setImageBitmap(data.getThumb());
} else {
v.imageView.setImageResource(R.mipmap.ic_launcher);
}
// Seting round image
Bitmap bm = BitmapFactory.decodeResource(view.getResources(), R.mipmap.ic_launcher); // Load default image
roundedImage = new RoundImage(bm);
v.imageView.setImageDrawable(roundedImage);
} catch (OutOfMemoryError e) {
// Add default picture
v.imageView.setImageDrawable(this._c.getDrawable(R.mipmap.ic_launcher));
e.printStackTrace();
}
Log.e("Image Thumb", "--------------" + data.getThumb());
/*// Set check box listener android
v.check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox checkBox = (CheckBox) view;
if (checkBox.isChecked()) {
data.setCheckedBox(true);
} else {
data.setCheckedBox(false);
}
}
});*/
view.setTag(data);
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
_data.clear();
if (charText.length() == 0) {
_data.addAll(arraylist);
} else {
for (ContactListSelectUser wp : arraylist) {
if (wp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
_data.add(wp);
}
}
}
notifyDataSetChanged();
}
#Override
public Filter getFilter() {
return filter;
}
static class ViewHolder {
ImageView imageView;
TextView title, phone;
CheckBox check;
}
private class CustomFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
_data.clear();
FilterResults filterResults = new FilterResults();
filterResults.values = _data;
filterResults.count = _data.size();
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
if (filterResults.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
below is logcat where u can see data is fetched while I choose back fragment but not set to listview.
E/Inside: here--------------------------- In view1
E/Image Thumb: --------------null
E/Inside: here--------------------------- In view1
E/Image Thumb: --------------null
I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
E/count: 2
E/No Image Thumb: --------------
E/No Image Thumb: --------------
E/count: 2
E/count: 2
implements Filterable in BaseAdapter
public class ContactListAdapter extends BaseAdapter implements Filterable
and add value :
private Filter filter = new CustomFilter();
and create class in your baseAdapter:
private class CustomFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
_data.clear();
if (arraylist != null && constraint != null) {
for (int i = 0; i < arraylist.size(); i++) {
if (arraylist.get(i).toString().toLowerCase().contains(constraint)) {
_data.add(arraylist.get(i));
}
}
}
FilterResults results = new FilterResults();
results.values = _data;
results.count = _data.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
add in your baseAdapter class:
#Override
public Filter getFilter() {
return filter;
}
my adapter for example:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CustomArrayAdapter extends BaseAdapter implements Filterable{
private LayoutInflater mInflater;
private final Context context;
private List<String> mItems;
private Filter filter = new CustomFilter();
private ArrayList<String>mItemsSuggestion = new ArrayList<String>();
public CustomArrayAdapter(Context context, String[] values) {
this.context = context;
mItems = Arrays.asList(values);
}
#Override
public int getCount() {
return mItemsSuggestion.size();
}
#Override
public Object getItem(int position) {
return mItemsSuggestion.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View oneView = mInflater.inflate(R.layout.towar_list, parent, false);
TextView text = (TextView)oneView.findViewById(R.id.towaryAllList);
text.setText(mItemsSuggestion.get(position).toString());
return oneView;
}
#Override
public Filter getFilter() {
return filter;
}
private class CustomFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
mItemsSuggestion.clear();
if (mItems != null && constraint != null) {
for (int i = 0; i < mItems.size(); i++) {
if (mItems.get(i).toString().toLowerCase().contains(constraint)) {
mItemsSuggestion.add(mItems.get(i));
}
}
}
FilterResults results = new FilterResults();
results.values = mItemsSuggestion;
results.count = mItemsSuggestion.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
I solved it now. The issue was only placing search view code in radiocontact on click listeners instead of in createview method directly.
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();
}
}
}
I'm trying to create a ListView with custom ArrayAdapter.
Following the example from here.
In the code below, I've created a ListActivity.
This list is getting its value from custom ArrayAdapter - OrderAdapter.
OrderAdapter is getting its elements from ArrayAdapter
I'm using runOnUiThread to fill the elements in adpater.
But inside this thread's run() method, the code is going into infinite loop. (See comments below).
Please check why it not getting out of the for loop.
Code:
public class SoftwarePassionView extends ListActivity {
private ProgressDialog m_progressDialog = null;
private ArrayList<Order> m_orders = null;
private OrderAdapter m_adapter; // Defined Below
private Runnable viewOrders;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.softwarepassionview);
m_orders = new ArrayList<Order>();
viewOrders = new Runnable() {
#Override
public void run() {
getOrders();
}
};
Thread thread = new Thread(null, viewOrders, "MagnatoBackground");
thread.start();
m_progressDialog = ProgressDialog.show(SoftwarePassionView.this, "Please Wait",
"Retriving data", true);
this.m_adapter = new OrderAdapter(this, R.layout.row, m_orders);
setListAdapter(this.m_adapter);
}
private void getOrders() {
try {
m_orders = new ArrayList<Order>();
Order o1 = new Order();
o1.setOrderName("T-Shirt Purchase");
o1.setOrderStatus("Dispatched");
Order o2 = new Order();
o2.setOrderName("Deo Purchase");
o2.setOrderStatus("Pending");
m_orders.add(o1);
m_orders.add(o2);
Thread.sleep(2000);
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
runOnUiThread(returnRes);
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if (m_orders != null && m_orders.size() > 0) {
m_adapter.notifyDataSetChanged();
/*
* Going in an infinite loop below
*/
for (int i = 0; i < m_orders.size(); i++)
m_adapter.add(m_orders.get(i));
}
m_progressDialog.dismiss();
m_adapter.notifyDataSetChanged();
}
};
private class OrderAdapter extends ArrayAdapter<Order> {
private ArrayList<Order> items;
public OrderAdapter(Context context, int textViewResourceId,
ArrayList<Order> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
super.getView(position, convertView, parent);
View v = convertView;
try {
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
}
Order o = items.get(position);
if (o != null) {
TextView orderName = (TextView) v
.findViewById(R.id.topText);
TextView orderStatus = (TextView) v
.findViewById(R.id.bottomText);
orderName.setText(o.getOrderName());
orderStatus.setText(o.getOrderStatus());
}
} catch (Exception e) {
Toast.makeText(SoftwarePassionView.this, e.toString(),
Toast.LENGTH_SHORT).show();
}
return v;
}
}
}
Order.java
public class Order {
private String orderName;
private String orderStatus;
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
public String getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
}
try this...
make a methode in OrderAdapter
setList(ArrayList<Order> items);
{
this.items.clear();
this.items.addAll(items);
notifyDataSetChanged();
}
and in run() of UI Thread do
if (m_orders != null && m_orders.size() > 0) {
m_adapter.setList(m_orders)
}
m_progressDialog.dismiss();
EDIT do some refracting of your code...make like this
in onCreat() new SampleTask().execute();
and
public class SampleTask extends AsyncTask{
#Override
protected void onPreExecute() {
super.onPreExecute();
//show progress bar here
}
#Override
protected Void doInBackground(Void... params) {
//Do heavy work here
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Dissmiss the dialgo
//call m_adapter.setList(m_orders)
}