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.
Related
This is my Recycler View adapter class:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.viewHolder> implements Filterable {
Context context;
OnBoardingFirstScreen activity;
public static ArrayList<CountryCodeModel> arrayList,arrayListFiltered;
public CustomAdapter(Context context, ArrayList<CountryCodeModel> arrayList, OnBoardingFirstScreen activity) {
this.context = context;
this.arrayList = arrayList;
this.arrayListFiltered = arrayList;
this.activity = activity;
}
#Override
public viewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.country_code_item, viewGroup, false);
/*view.measure(
View.MeasureSpec.makeMeasureSpec(200, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));*/
return new viewHolder(view);
}
#Override
public void onBindViewHolder(viewHolder viewHolder, int position) {
// viewHolder.name.setText(arrayListFiltered.get(position).getCountry()+ " " +
// "(" + arrayListFiltered.get(position).getCode() + ")");
String textdotted = arrayListFiltered.get(position).getCountry();
if (textdotted.length() >= 30) {
textdotted= textdotted.substring(0, 30)+ "...";
} else {
textdotted= textdotted;
}
viewHolder.name.setText(textdotted+ " (" + arrayListFiltered.get(position).getCode() + ")");
int imagee =arrayListFiltered.get(position).getFlag();
Picasso.get().load(imagee).resize(300, 300).centerCrop().into(viewHolder.image);
Picasso.get().load(imagee).fit();
//Picasso.get().load(imagee).fit().resize(300, 300).centerCrop().into(viewHolder.image);
viewHolder.layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((OnBoardingFirstScreen)activity).onClickCountryItem(position, arrayListFiltered);
}
});
}
#Override
public int getItemCount() {
int limit = 4;
if(arrayListFiltered.size()> limit){
return limit;
}
else {
return arrayListFiltered.size();
}
}
public class viewHolder extends RecyclerView.ViewHolder {
TextView name;
ShapeableImageView image;
LinearLayout layout;
public viewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.country_name);
image = (ShapeableImageView) itemView.findViewById(R.id.flagimg);
layout = (LinearLayout) itemView.findViewById(R.id.layout);
// itemView.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
//
//
// Toast.makeText(context,arrayListFiltered.get(getAdapterPosition()).getCountry(),Toast.LENGTH_LONG).show();
// }
// });
}
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<CountryCodeModel> arrayListFilter = new ArrayList<CountryCodeModel>();
if(constraint == null|| constraint.length() == 0) {
results.count = arrayList.size();
results.values = arrayList;
} else {
for (CountryCodeModel itemModel : arrayList) {
if(itemModel.getCountry().toLowerCase().contains(constraint.toString().toLowerCase())) {
arrayListFilter.add(itemModel);
}else if(itemModel.getCode().contains(constraint.toString())) {
arrayListFilter.add(itemModel);
}
}
results.count = arrayListFilter.size();
results.values = arrayListFilter;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayListFiltered = (ArrayList<CountryCodeModel>) results.values;
if (results.count == 0) {
((OnBoardingFirstScreen)activity).NoResultfound(results.count);
arrayListFiltered.clear();
notifyDataSetChanged();
}
else {
((OnBoardingFirstScreen)activity).NoResultfound(results.count);
arrayListFiltered = (ArrayList<CountryCodeModel>)results.values;
notifyDataSetChanged();
}
}
};
return filter;
}
}
This is my recyclerview XML part:
<androidx.recyclerview.widget.RecyclerView
android:layout_width="#dimen/_200sdp"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:layout_marginBottom="#dimen/_4sdp"
android:layout_marginStart="#dimen/_2sdp"
android:id="#+id/country_codes_rv"/>
in custom adapter class if i set getItemCount() to return the size instead of limit it loads all 200 items and in xml it is wrap content lists gets out of the screen.
I want to load 4 items at a time in my list and want my recyclerview list scrollable.
i dont want to give it a specific height. it will distort my view.
I made an app with listView and I want to use search in top bar but it doesn't work.
In this program, I get the data from the firebase.
These are the codes below:
This is MainActivity code:
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int List_APP_LOADER = 0;
ArrayList<Informatin> listItem;
ListView listView;
listAdapter adapter;
DatabaseReference reference;
ArrayList<Informatin> mInformation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listItem = new ArrayList<>();
listView = findViewById(R.id.list);
LoaderManager.getInstance(this).initLoader(LIST_APP_LOADER, null, this);
mInformation = new ArrayList<>();
adapter = new listAdapter(this, mInformation);
listView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_main_screen, menu);
MenuItem searchItem = menu.findItem(R.id.search_item);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
listView.getFilter().filter(newText);
return true;
}
});
return true;
}
}
This is listAdapter code
public class listAdapter extends ArrayAdapter<Informatin> implements Filterable {
List<Informatin> arrayList;
Context context;
public listAdapter(Context context, ArrayList<Informatin> informatins) {
super(context, 0, informatins);
this.context=context;
arrayList = informatins;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Informatin currentList = getItem(position);
TextView nameTextView = listItemView.findViewById(R.id.name);
TextView descriptionTextView = listItemView.findViewById(R.id.description);
TextView ageTextView = listItemView.findViewById(R.id.age);
ImageView imageView = listItemView.findViewById(R.id.image);
String firstName = currentList.getFirstName();
String lastName = currentList.getLastName();
String name = firstName + " " + lastName;
nameTextView.setText(name);
descriptionTextView.setText(currentList.getDescription());
ageTextView.setText(currentList.getAge());
return listItemView;
}
List<Informatin> informatins;
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<Informatin> results = new ArrayList<>();
if (informatins == null)
informatins = arrayList;
if (constraint != null) {
if (informatins != null && informatins.size() > 0) {
for (final Informatin g : informatins) {
if (g.getFirstName().toLowerCase()
.contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
arrayList = (ArrayList<Informatin>) results.values;
notifyDataSetChanged();
}
};
}
}
this is the picture of the problem
this is a screenshot for the problem from the device
Add this to your listadapter code:
Context context;
public listAdapter(Context context, List<Informatin> informatins) {
super();
this.context=context;
arraylist=informatins;
}
ArrayList<Informatin> informatins;
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<Informatin> results = new ArrayList<Informatin>();
if (informatins == null)
informatins = arraylist;
if (constraint != null) {
if (informatins != null && informatins.size() > 0) {
for (final Information g : informatins) {
if (g.getName().toLowerCase()
.contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
arraylist = (ArrayList<Informatin>) results.values;
notifyDataSetChanged();
}
};
}
Add this in your onquerytextchaged:
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);//replace adapter with listview name which in your case is listview as informed by you in comment
return true;
}
});
return true;
Modified MainActivity onCreate() code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listItem = new ArrayList<>();
listView = findViewById(R.id.list);
LoaderManager.getInstance(this).initLoader(LIST_APP_LOADER, null, this);
mInformation = new ArrayList<>();
adapter = new listAdapter(this, mInformation);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true)//add this line
}
I have a listview and an editText to filter data. It filters data correctly but e.g, if I filter list and open filtered item it shows me the data of item which was at index 0 of original list not that of filtered item.
My 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);
}
#Override
public long getItemId(int i) {
return 0;
}
private class Viewholder{
TextView name_
,date_
,number_
,dip_rate_
,tv_request_number;
Button button;
}
#Override
public View getView(final int position, View view, final 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.button = (Button) view.findViewById(R.id.btn_re);
viewholder.date_ = (TextView) view.findViewById(R.id.date);
view.setTag(viewholder);
}
else {
viewholder = (Viewholder) view.getTag();
}
viewholder.tv_request_number.setText((arrayList.size()-position)+".");
viewholder.name_.setText(arrayList.get(position).getName());
viewholder.date_.setText(getDate(Long.parseLong(arrayList.get(position).getDate())));
viewholder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((ListView)viewGroup).performItemClick(v,position,1);
}
});
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());
contacts.setDate(StringFilterList.get(i).getDate());
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 my main activity code
simListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(id == 1){
//CUSTOM DIALOG///////////////////////////////
final Dialog dialog = new Dialog(getActivity());
dialog.setCanceledOnTouchOutside(false);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_re_evaluate);
name_ = (TextView) dialog.findViewById(R.id.name);
f_name_ = (TextView) dialog.findViewById(R.id.f_name);
age_ = (TextView) dialog.findViewById(R.id.age);
number_ = (TextView) dialog.findViewById(R.id.number);
gender_ = (TextView) dialog.findViewById(R.id.gender);
dip_rate_ = (TextView) dialog.findViewById(R.id.dip_rate);
date_ = (TextView) dialog.findViewById(R.id.date);
name_.setText(name[position]);
f_name_.setText(f_name[position]);
age_.setText(age[position]);
number_.setText(number[position]);
dip_rate_.setText(dip_rate[position]);
gender_.setText(gender[position]);
date_.setText(getDate(Long.parseLong(date[position])));
Button re_eval = (Button) dialog.findViewById(R.id.btn);
Button btn_cross = (Button) dialog.findViewById(R.id.cross);
btn_cross.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
re_eval.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
p_name = name_.getText().toString();
p_f_name = f_name_.getText().toString();
p_age = age_.getText().toString();
p_number = number_.getText().toString();
p_dip_rate = dip_rate_.getText().toString();
p_gender = gender_.getText().toString();
p_date = date_.getText().toString();
//go from one fragment to another
Fragment fragment = null;
//send data to next fragment
Bundle bundle = new Bundle();
bundle.putString("name", p_name);
bundle.putString("f_name", p_f_name);
bundle.putString("age", p_age);
bundle.putString("number", p_number);
bundle.putString("dip_rate", p_dip_rate);
bundle.putString("gender", p_gender);
bundle.putString("date", p_date);
fragment = new Questions();
if (fragment != null) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
fragment.setArguments(bundle);
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
dialog.dismiss();
}
});
dialog.show();
}
}
});
performing filtering here
protected void onPostExecute(String s) {
progressDialog.dismiss();
if (server_check) {
if (server_response.equals("1")) {
if (name.length > 0) {
patient_adapter = new Patient_Adapter(getActivity(),
arrayList);
simListView.setAdapter(patient_adapter);
//filtering data
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
patient_adapter.getFilter().filter(charSequence);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
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.
Everything in the code below works except the when you try and search for a value, the application just doesnt respond to when you type letters into the searchview which should be filtering the gridview.
Cheers, Kripzy
Main Activity:
String[] Champions = {"Aatrox", "Ahri", "Akali"};
int[] Champimgs = {R.drawable.aatrox_square_0, R.drawable.ahri_square_0, R.drawable.akali_square_0};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gv = (GridView) findViewById(R.id.gridView);
sv = (SearchView) findViewById(R.id.searchView);
final Adapter adapter=new Adapter(this,this.getChampions());
gv.setAdapter(adapter);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String arg0) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
adapter.getFilter().filter(query);
return false;
}
});
}
private ArrayList<Champions> getChampions()
{
ArrayList<Champions> champions = new ArrayList<Champions>();
Champions p;
for (int i = 0; i < Champions.length; i++)
{
p = new Champions(Champions[i], Champimgs[i]);
champions.add(p);
}
return champions;
}
}
Champions
public Champions(String Champion, int Champimg) {
this.Champimg=Champimg;
this.Champion=Champion;}
public String getChampion() {
return Champion;
}
public int getChampimg() {
return Champimg;
}
public void setChampion(String champion) {
Champion = champion;
}
public void setChampimg(int champimg) {
Champimg = champimg;
}
}
Adapter
public Adapter(Context ctx, ArrayList<Champions> Champion){
this.c=ctx;
this.Champion=Champion;
this.filterlist=Champion;
}
#Override
public int getCount() {
return Champion.size();
}
#Override
public Object getItem(int position) {
return Champion.get(position);
}
#Override
public long getItemId(int position) {
return Champion.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.model, null);
}
TextView nameTxt = (TextView) convertView.findViewById(R.id.textView);
ImageView img = (ImageView) convertView.findViewById(R.id.imageView);
nameTxt.setText(Champion.get(position).getChampion());
img.setImageResource(Champion.get(position).getChampimg());
return convertView;
}
#Override
public Filter getFilter() {
if (filter == null)
{
filter=new CustomFiler();
}
return filter;
}
class CustomFiler extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results=new FilterResults();
if (constraint != null && constraint.length() > 0)
{
constraint=constraint.toString().toUpperCase();
ArrayList<Champions> filters = new ArrayList<Champions>();
for(int i = 0;i<filterlist.size();i++){
if (filterlist.get(i).getChampion().toUpperCase().contains(constraint));
{
Champions p= new Champions (filterlist.get(i).getChampion(),filterlist.get(i).getChampimg());
filters.add(p);
}
}
results.count=filters.size();
results.values=filters;
}else{
results.count=filterlist.size();
results.values=filterlist;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
Champion = (ArrayList<Champions>) results.values;
notifyDataSetChanged();
}
}
}
you have a little bug in this line:
if (filterlist.get(i).getChampion().toUpperCase().contains(constraint));
the bug is ; symbol in the end of if statement. It makes code below if run each time, therefore filter doesn't work. Just remove ; symbol after if statement