The list generating successfully but when i am trying to filter using search view then getting this error. just after type one later got this error.
Getting this Error
Process: com.galaxybd.eams, PID: 7836
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at com.galaxybd.eams.test.AD.getCount(AD.java:35)
at android.widget.AdapterView$AdapterDataSetObserver.onChanged(AdapterView.java:811)
at android.widget.AbsListView$AdapterDataSetObserver.onChanged(AbsListView.java:6140)
at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:37)
at android.widget.BaseAdapter.notifyDataSetChanged(BaseAdapter.java:50)
at com.galaxybd.eams.test.AD$ValueFilter.publishResults(AD.java:102)
at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:282)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
The list generating successfully but when i am trying to filter using search view then getting this error. just after type one later got this error.
Adapter
public class AD extends BaseAdapter implements Filterable {
private Context context;
private List<DM> beanList;
private LayoutInflater inflater;
List<DM> mStringFilterList;
ValueFilter valueFilter;
public AD(Context context, List<DM> beanList) {
// TODO Auto-generated constructor stub
this.context = context;
this.beanList = beanList;
mStringFilterList = beanList;
}
#Override
public int getCount() {
return beanList.size();
}
#Override
public Object getItem(int i) {
return beanList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (inflater == null) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (view == null) {
view = inflater.inflate(R.layout.row_tlist, null);
}
TextView tvName= view.findViewById(R.id.tvName);
TextView tvDesig= view.findViewById(R.id.tvDesig);
TextView tvCompany= view.findViewById(R.id.tvCompany);
DM bean = beanList.get(i);
tvName.setText(bean.getDmName());
tvDesig.setText(bean.getDmDesig());
tvCompany.setText(bean.getDmCom());
return view;
}
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<DM> filterList = new ArrayList<DM>();
for (int i = 0; i < mStringFilterList.size(); i++) {
if ((mStringFilterList.get(i).getDmName().toUpperCase()).contains(constraint.toString().toUpperCase())) {
DM bean = new DM(mStringFilterList.get(i).getDmName(), mStringFilterList.get(i).getDmDesig(), mStringFilterList.get(i).getDmCom());
filterList.add(bean);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = mStringFilterList.size();
results.values = mStringFilterList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
beanList = (ArrayList<DM>) results.values;
notifyDataSetChanged();
}
}}
The list generating successfully but when i am trying to filter using search view then getting this error. just after type one later got this error.
Data Model
public class DM {
String dmName,dmDesig,dmCom;
public DM(String dmName, String dmDesig, String dmCom) {
this.dmName = dmName;
this.dmDesig = dmDesig;
this.dmCom = dmCom;
}
public String getDmName() {
return dmName;
}
public void setDmName(String dmName) {
this.dmName = dmName;
}
public String getDmDesig() {
return dmDesig;
}
public void setDmDesig(String dmDesig) {
this.dmDesig = dmDesig;
}
public String getDmCom() {
return dmCom;
}
public void setDmCom(String dmCom) {
this.dmCom = dmCom;
}}
The list generating successfully but when i am trying to filter using search view then getting this error. just after type one later got this error.
Main Activity
public class listtest extends AppCompatActivity {
private SearchView tSearchView;
private ListView tList;
private ArrayList<DM> sARRAYLIST=new ArrayList<>();
private AD ad;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listtest);
tSearchView=findViewById(R.id.tSearchView);
tList=findViewById(R.id.tList);
new LIST_GENARATE().execute();
tSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if(ad!=null){
ad.getFilter().filter(s);
}
return false;
}
});
}
//AsynTask
private class LIST_GENARATE extends AsyncTask<String, String, String>
{
DM dm;
String qNAME =null;
String qDESIG =null;
String qCOM =null;
private String msg;
final Animation myRotation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.animationfile);
protected void onPreExecute()
{
}
#Override
protected String doInBackground(String... params) {
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#172.30.0.16:1521:GALAXYBD", "GIM", "GALAXYGIM");
Statement st = con.createStatement();
ResultSet lv= st.executeQuery("SELECT INITCAP(CUSTODIAN) NAM,(SELECT INITCAP(EI.DESIG_NAME) FROM GHRMS.EMP_INFO EI WHERE EI.EMP_ID=DD.CUS_ID) DESIG,(SELECT INITCAP(EI.COMPANY_NAME) FROM GHRMS.EMP_INFO EI WHERE EI.EMP_ID=DD.CUS_ID) COMPAN,CUS_ID,(SELECT EI.EMP_CODE FROM GHRMS.EMP_INFO EI WHERE EI.EMP_ID=DD.CUS_ID) EMP_CODE,COUNT(ASSET_ID) AID FROM GIM.DASHBOARD_DATA DD GROUP BY CUSTODIAN,CUS_ID ORDER BY COUNT(ASSET_ID) DESC");
while (lv.next())
{
dm=new DM(qNAME,qDESIG,qCOM);
dm.setDmName(lv.getString(1));
dm.setDmDesig(lv.getString(2));
dm.setDmCom(lv.getString(3));
sARRAYLIST.add(dm);
}
con.close();
st.close();
lv.close();
}
catch (Exception e) {
msg=e.toString();
}
return null;
}
protected void onPostExecute(String result)
{
if (TextUtils.isEmpty(msg))
{
ad=new AD(getApplicationContext(),sARRAYLIST);
tList.setAdapter(ad);
}else
{
SuperToast.create(listtest.this, "Network Error\n"+msg, SuperToast.Duration.EXTRA_LONG, Style.getStyle(Style.RED, SuperToast.Animations.FLYIN)).show();
}
}
}}
Related
I have a RecyclerView & EditText. I can select the item from RecyclerView & gets correct item unless it is not filtered.
On entering in EditText, RecyclerView list gets filtered & when I select any item from the list it shows me actual list item instead of selected one.
Fragment Class :
public class RegionListFragment extends DialogFragment implements View.OnClickListener,
OnRecylerViewClickable {
private RecyclerView regionRecyclerView;
private ArrayList<RegionDetail> regionDetailArrayList = new ArrayList<>();
private GenericRegionListAdapter genericRegionListAdapter;
private Context context = this.getActivity();
private RecyclerView.LayoutManager mLayoutManager;
private View view;
private EditText editTextSearchView;
private DatabaseHandler spcl_databaseHandler;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.spinner_fragment_list_screen, container, false);
databaseHandler = new DatabaseHandler(getActivity());
regionDetailArrayList = (ArrayList<RegionDetail>) spcl_databaseHandler.getAllRegionDetails();
editTextSearchView = (EditText) view.findViewById( R.id.search);
editTextSearchView.setHint(getString(R.string.region_search_hint));
mLayoutManager = new LinearLayoutManager(context);
regionRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView_Locations);
regionRecyclerView.setLayoutManager(mLayoutManager);
relativeLayoutBottom = (RelativeLayout) view.findViewById(R.id.rlBottom);
genericRegionListAdapter = new GenericRegionListAdapter(context, regionDetailArrayList, this, false);
regionRecyclerView.setAdapter(genericRegionListAdapter);
addTextListener();
return view;
}
public void addTextListener(){
editTextSearchView.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
genericRegionListAdapter.getFilter().filter(query.toString());
}
});
}
#Override
public void onClick(View view) {
}
#Override
public void onRecyclerItemClicked(int position, String itemName, String itemID) {
Log.v("Region Name", " : " + regionDetailArrayList.get(position).getRegionName());
}
}
Adapter Class :
public class GenericRegionListAdapter extends RecyclerView.Adapter<GenericRegionListAdapter.DataObjectHolder>
implements Filterable {
private ArrayList<RegionDetail> originalArrayList;
private ArrayList<RegionDetail> filterArrayList;
private GenericRegionListAdapter.ValueFilter valueFilter;
private OnRecylerViewClickable onRecylerViewClickable;
private Context mContext = null;
#Override
public GenericRegionListAdapter.DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.sd_custom_cardview_for_walk_list_item, parent, false);
GenericRegionListAdapter.DataObjectHolder dataObjectHolder = new GenericRegionListAdapter.DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new GenericRegionListAdapter.ValueFilter();
}
return valueFilter;
}
public class DataObjectHolder extends RecyclerView.ViewHolder{
TextView textViewWalkName;
public DataObjectHolder(View itemView) {
super(itemView);
mContext = itemView.getContext();
textViewWalkName = (TextView) itemView.findViewById(R.id.textView_Walk_Name);
}
}
public GenericRegionListAdapter(Context context, ArrayList<RegionDetail> detailsArrayList,
OnRecylerViewClickable onRecylerViewClickable, boolean doShowCheckbox) {
mContext = context;
this.originalArrayList = detailsArrayList;
this.filterArrayList = detailsArrayList;
this.onRecylerViewClickable = onRecylerViewClickable;
}
#Override
public void onBindViewHolder(final GenericRegionListAdapter.DataObjectHolder holder, final int position) {
holder.textViewWalkName.setText(originalArrayList.get(position).getRegionName());
holder.textViewWalkName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onRecylerViewClickable.onRecyclerItemClicked(position, originalArrayList.get(position).getRegionName(), originalArrayList.get(position).getRegionID());
}
});
}
// method to access in activity after updating selection
public ArrayList<RegionDetail> getRegionList() {
return originalArrayList;
}
#Override
public int getItemCount() {
return originalArrayList.size();
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<RegionDetail> filterList = new ArrayList<RegionDetail>();
for (int i = 0; i < filterArrayList.size(); i++) {
if ((filterArrayList.get(i).getRegionName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
RegionDetail listItem = new RegionDetail();
listItem.setRegionID(filterArrayList.get(i).getRegionID());
listItem.setRegionName(filterArrayList.get(i).getRegionName());
filterList.add(listItem);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = filterArrayList.size();
results.values = filterArrayList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
originalArrayList = (ArrayList<RegionDetail>) results.values;
notifyDataSetChanged();
Log.v("Size", " : " + originalArrayList.size());
if (originalArrayList.size() == 0) {
new GlobalToast().showToastMessage(mContext, mContext.getResources().getString(R.string.no_records_found));
}
}
}
}
Please help me.
Please use this code snippet
private class ItemFilter extends Filter {
String filterString;
#Override
protected FilterResults performFiltering(CharSequence constraint) {
filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
int count = filterArrayList.size();
ArrayList<RegionDetail> filterList = new ArrayList<RegionDetail>();
String filterableString;
for (int i = 0; i < count; i++) {
RegionDetail listItem = new RegionDetail();
listItem.setRegionID(filterArrayList.get(i).getRegionID());
listItem.setRegionName(filterArrayList.get(i).getRegionName());
filterList.add(listItem);
}
results.values =filterList;
results.count = filterList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
originalArrayList = (ArrayList<RegionDetail>) results.values;
notifyDataSetChanged();
}
}
i hope this code will filter your list correctly and you get right list item onClick.
I have a DB named RealmItem and I have all users have territories they are attached to. Which is n size unknown. Every item has a field called territory. Now, is there a way to query Realm to find all Item Records that has any of the territoryID attached to the user. The reason I'm in need of this is because, I pipe a AutoCompleteTextView to a filtering adapter that looks like this:
public class ItemFilterAdapter extends BaseAdapter implements Filterable {
private static final String TAG = ItemFilterAdapter.class.getSimpleName();
private Context mContext;
private List<RealmItem> mResult = new ArrayList<>();
private LayoutInflater inflater;
private boolean needsFilter = false;
public ItemFilterAdapter(Context mContext) {
this.mContext = mContext;
}
public void setNeedsFilter(boolean needsFilter) {
this.needsFilter = needsFilter;
}
#Override
public int getCount() {
return mResult.size();
}
#Override
public Object getItem(int position) {
return mResult.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.item_update_autocomplete, parent, false);
RealmItem item = mResult.get(position);
TextView updateName = (TextView) view.findViewById(R.id.update_name);
TextView updateAddress = (TextView) view.findViewById(R.id.update_address);
if (item != null) {
updateName.setText(item.getName());
try {
JSONObject obj = new JSONObject(item.getPayload());
String address = obj.getString("address");
updateAddress.setText(address);
} catch (Exception e) {
e.printStackTrace();
}
}
return view;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
return null;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults filterResults) {
if (constraint != null) {
mResult = filterDealers(constraint.toString());
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
}
#NonNull
private List<RealmItem> filterDealers(String query) {
Realm mRealm = RealmUtils.getRealmInstance(mContext);
if (!needsFilter) {
return mRealm.where(RealmItem.class)
.contains("name", query, Case.INSENSITIVE)
.equalTo("id", [array of Ids]) <-- This is where I need it
.findAll();
} else {
return mRealm.where(RealmItem.class)
.contains("name", query, Case.INSENSITIVE)
.notEqualTo("activeStatus", "inactive")
.equalTo("id", [array of Ids]) <-- This is where I need it
.findAll();
}
}
}
More like looking for something like this .equalTo("id", [array of Ids]) <-- This is where I need it or anything nice to make filtering seemlessly smooth 😉
Aren't you basically just looking for the in() operator, added in 1.1.0?
public RealmQuery<E> in(
String fieldName, Integer[] values)
MultiAutoCompleteTextView Custom adapter, How to dismissDropDown
my code click listener is not working.
output image
Fragment
public class ShareDialogFragment extends DialogFragment implements View.OnClickListener{
Dialog dialog;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
String articleID;
MultiAutoCompleteTextView myMultiAutoCompleteTextView;
TextView Cancel, share;
Context context;
public static ShareDialogFragment fragment;
OnClickListenerCustom onClickListenerCustom;
private PrefManager pref;
ArrayList<ShareWithArticle> userList = new ArrayList<>();
MultiAutoCompleteAdapter adapter;
RequestParse requestParse;
public ShareDialogFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
setStyle(DialogFragment.STYLE_NO_TITLE, R.style.alert_dialog);
Bundle arg = getArguments();
if(arg!=null){
articleID = getArguments().getString("ArticleId");
}
dialog = new Dialog(getActivity());
requestParse = new RequestParse();
UserNameTo();
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
context = activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_share_dialog, container, false);
Cancel = (TextView)view.findViewById(R.id.Cancel);
Cancel.setOnClickListener(this);
share = (TextView) view.findViewById(R.id.textView22);
myMultiAutoCompleteTextView = (MultiAutoCompleteTextView)view.findViewById(R.id.editText);
//ShareWithArticle s = (ShareWithArticle) myMultiAutoCompleteTextView.getAdapter().getItem(position);
return view;
}
public void UserNameTo(){
requestParse.postJson(ConfigApi.UserToArticle(), new RequestParse.VolleyCallBackPost() {
#Override
public void onSuccess(String result) {
userList = ShareArticleuserNameTo.parseResponse(result);
adapter = new MultiAutoCompleteAdapter(context,R.layout.custom_dropdown, userList);
myMultiAutoCompleteTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
myMultiAutoCompleteTextView.setAdapter(adapter);
myMultiAutoCompleteTextView.dismissDropDown();
}
#Override
public void onRequestError(String errorMessage) {
M.i("============errorMessage", errorMessage);
}
#Override
public Map OnParam(Map<String, String> params) {
return null;
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.Cancel:
getDialog().dismiss();
break;
}
}
}
and My Custom Adapter MultiAutoCompleteTextView Code:
public class MultiAutoCompleteAdapter extends ArrayAdapter<ShareWithArticle> {
//ShareWithArticle
private final Context mContext;
private final List<ShareWithArticle> mDepartments;
private final List<ShareWithArticle> mDepartments_All;
private final List<ShareWithArticle> mDepartments_Suggestion;
private final int mLayoutResourceId;
private ImageLoader imageLoader;
private RequestQueue requestQueue;
private VolleySingleton volleySingleton;
public MultiAutoCompleteAdapter(Context context, int resource, List<ShareWithArticle> departments) {
super(context, resource, departments);
this.mContext = context;
this.mLayoutResourceId = resource;
this.mDepartments = new ArrayList<>(departments);
this.mDepartments_All = new ArrayList<>(departments);
this.mDepartments_Suggestion = new ArrayList<>();
}
public int getCount() {
return mDepartments.size();
}
public ShareWithArticle getItem(int position) {
return mDepartments.get(position);
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
if (convertView == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(mLayoutResourceId, parent, false);
}
ShareWithArticle department = getItem(position);
TextView name = (TextView) convertView.findViewById(R.id.name);
ImageView userProfile = (ImageView) convertView.findViewById(R.id.profileImages);
name.setText(department.getUsrFNm() + " " + department.getUsrLNm());
volleySingleton = VolleySingleton.getInstance();
imageLoader = volleySingleton.getImageLoader();
requestQueue = volleySingleton.getRequestQueue();
String UsrPrf = department.getUsrPicture();
RequestParse.loadImages(UsrPrf, userProfile);
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
/*#Override
public boolean isEnabled(int position) {
return position % 2 == 0 ? false : true;
}*/
#Override
public Filter getFilter() {
return new Filter() {
#Override
public String convertResultToString(Object resultValue) {
return ((ShareWithArticle) resultValue).getUsrFNm()+ " " + ((ShareWithArticle) resultValue).getUsrLNm();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
mDepartments_Suggestion.clear();
for (ShareWithArticle department : mDepartments_All) {
if (department.getUsrFNm().toLowerCase().startsWith(constraint.toString().toLowerCase())) {
mDepartments_Suggestion.add(department);
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = mDepartments_Suggestion;
filterResults.count = mDepartments_Suggestion.size();
return filterResults;
} else {
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mDepartments.clear();
if (results != null && results.count > 0) {
// avoids unchecked cast warning when using mDepartments.addAll((ArrayList<Department>) results.values);
List<?> result = (List<?>) results.values;
for (Object object : result) {
if (object instanceof ShareWithArticle) {
mDepartments.add((ShareWithArticle) object);
}
}
} else if (constraint == null) {
// no filter, add entire original list back in
mDepartments.addAll(mDepartments_All);
}
notifyDataSetChanged();
}
};
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am getting this error-Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
This is what i have done!
PeopleListFragment
**PeopleListFragment**
public class PeopleListFragment extends Fragment{
public static final String DISPLAY_URL = ServiceAPI.URL_CONTACTS;
private static final String TAG = "PeopleListActivity";
public static final boolean DEBUG = Constant.DEBUG;
private ProgressDialog progressDialog;
public PeopleAdapter adapter;
private GetAllPeopleTask mGetAllPeople = null;
private Intent intent;
public static ListView mContactlistView;
public PeopleListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_people_list, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mContactlistView = (ListView) view.findViewById(R.id.people_list);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
List<People> contactList = new ArrayList<People>();
adapter = new PeopleAdapter(getActivity().getApplicationContext(),
R.layout.people_list_item, contactList);
mContactlistView.setAdapter(adapter);
mContactlistView.setTextFilterEnabled(true);
mContactlistView.setFastScrollEnabled(true);
mContactlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String empId = String.valueOf(adapter.getItem(position).getEmployeeId());
String name = String.valueOf(adapter.getItem(position).getFirstName());
intent = new Intent(getActivity(),
PeopleDetailsActivity.class);
intent.putExtra("EmployeeId", empId);
intent.putExtra("name", name);
startActivity(intent);
}
});
startAsyncTask();
TextView textView = new TextView(getContext());
textView.setText("Empty");
mContactlistView.setEmptyView(textView);
}
public void startAsyncTask() {
mGetAllPeople = new GetAllPeopleTask();
mGetAllPeople.execute(DISPLAY_URL, "12345678");
}
public class GetAllPeopleTask extends AsyncTask<String, Void, List<People>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading");
progressDialog.show();
}
#Override
protected ArrayList<People> doInBackground(String... params) {
ArrayList<People> peopleList = new ArrayList<>();
try {
URL url = new URL(params[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(40000);
httpURLConnection.setConnectTimeout(50000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setDoOutput(true);
JSONObject request = new JSONObject();
request.put("session", params[1]);
String bodyParams = request.toString();
if (DEBUG) {
Log.i(TAG, bodyParams);
}
httpURLConnection.setRequestProperty("Content-Length",
String.valueOf(bodyParams.getBytes().length));
DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
outputStream.writeBytes(bodyParams);
outputStream.flush();
outputStream.close();
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
Log.i(TAG, "Success");
} else {
Log.i(TAG, "Error Code :" + httpURLConnection.getResponseCode());
}
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Log.i(TAG, "Builder String : " + builder.toString());
JSONObject jsonObject = new JSONObject(builder.toString());
Log.i(TAG, "Response JSON : " + jsonObject.toString());
if (jsonObject.has("responseData")) {
JSONArray responseDataArr = jsonObject.optJSONArray("responseData");
for (int i = 0; i < responseDataArr.length(); i++) {
JSONObject peopleJSON = responseDataArr.optJSONObject(i);
People people = new People();
people.setEmployeeId(peopleJSON.optString("employeeId"));
people.setFirstName(peopleJSON.optString("firstName"));
people.setLastName(peopleJSON.optString("lastName"));
// Log.i("hebsiba ", "People first name" + people.getFirstName() + ", last name is " + people.getLastName()) ;
if((!people.getFirstName().isEmpty()) && (!people.getLastName().isEmpty())) {
peopleList.add(people);
}
if (DEBUG) {
Log.i(TAG, "People " + people.getEmployeeId());
}
}
}
} catch (IOException | JSONException e) {
Log.e(TAG, e.toString());
}
return peopleList;
}
#Override
protected void onPostExecute(List<People> people) {
super.onPostExecute(people);
Collections.sort(people, new Comparator<People>() {
#Override
public int compare(People lhs, People rhs) {
return lhs.getFirstName().compareToIgnoreCase(rhs.getFirstName());
}
});
adapter.addAll(people);
if (DEBUG) {
Log.i(TAG, adapter.getCount() + " ");
}
Log.v(TAG, String.valueOf(people.size()));
progressDialog.dismiss();
}
}
}
This is the PeopleAdapter
**PeopleAdapter**
public class PeopleAdapter extends ArrayAdapter<People> implements Filterable {
private PeopleListActivity activity;
private PeopleFilter peopleFilter;
private List<People> peopleList;
private List<People> filteredList;
public PeopleAdapter(Context applicationContext, int people_list_item, List<People> contactList) {
super(applicationContext, people_list_item, contactList);
filteredList = contactList;
getFilter();
}
#Override
public int getCount() {
return filteredList.size();
}
#Override
public People getItem(int i) {
return filteredList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
People peopleList = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.people_list_item, null);
holder = new ViewHolder();
holder.firstName = (TextView) convertView.findViewById(R.id.firstName);
holder.lastName = (TextView) convertView.findViewById(R.id.lastName);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.firstName.setText(peopleList.getFirstName());
holder.lastName.setText(peopleList.getLastName());
return convertView;
}
/**
* Get custom filter
* #return filter
*/
#Override
public Filter getFilter() {
if (peopleFilter == null) {
peopleFilter = new PeopleFilter();
}
return peopleFilter;
}
static class ViewHolder {
TextView firstName;
TextView lastName;
}
private class PeopleFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint!=null && constraint.length()>0) {
ArrayList<People> tempList = new ArrayList<>();
// search content in friend list
for (People user : peopleList) {
if (user.getFirstName().toLowerCase().contains(constraint.toString().toLowerCase())) {
tempList.add(user);
}
}
filterResults.count = tempList.size();
filterResults.values = tempList;
} else {
filterResults.count = peopleList.size();
filterResults.values = peopleList;
}
return filterResults;
}
/**
* Notify about filtered list to ui
* #param constraint text
* #param results filtered result
*/
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
filteredList = (ArrayList<People>) results.values;
notifyDataSetChanged();
}
}
}
And this is PeopleListActivity
**PeopleListActivity**
public class PeopleListActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
private PeopleListFragment fragment;
private FragmentManager displayFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.argb(255, 180, 110, 60));
}
setContentView(R.layout.activity_people);
Toolbar toolbar = (Toolbar) findViewById(R.id.people_toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_back_arrow);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PeopleListActivity.this, NavigationActivity.class);
startActivity(intent);
}
});
displayFragment = getSupportFragmentManager();
fragment = new PeopleListFragment();
displayFragment.beginTransaction().add(R.id.people_fragment, fragment).commit();
if (savedInstanceState == null) {
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
SearchManager searchManager =(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =(SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
// searchView.setIconifiedByDefault(false);
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(this);
return true;
// return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
PeopleAdapter peopleAdapter = (PeopleAdapter) PeopleListFragment.mContactlistView.getAdapter();
peopleAdapter.getFilter().filter(newText);
return true;
}
}
Could anyone help me with this..?
Assign some value to filteredList when you create the Adapter
Example:
public PeopleAdapter(Context applicationContext, int people_list_item, List<People> contactList) {
super(applicationContext, people_list_item, contactList);
filteredList = contactList;
getFilter();
}
filteredList is null when getCount() is called. Instantiate it first or make sure filteredList has some content.
I found solutions for filters on ListView and SearchView on RecyclerView separately, but I wish to combine them. Is it even possible?
Yes it is possible Your RecyclerView.Adapter can implement Filterable. After that you have to override Filter getFilter() method.
You have to define your own filter as is shown in the code below:
#Override
public Filter getFilter() {
return new YourFilterClass();
}
YourFilterClass
class YourFilterClass extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
//Here you have to implement filtering way
final FilterResults results = new FilterResults();
//logic to filtering
results.values = ...
results.count = ...
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
// here you can use result - (f.e. set in in adapter list)
}
}
Example
public class UserListAdapter extends RecyclerView.Adapter<UserListAdapter.ViewHolder> implements Filterable {
private final List<User> userList;
private final List<User> filteredUserList;
private UserFilter userFilter;
public UserListAdapter(Context context) {
this.userList =new ArrayList<>();
this.filteredUserList = new ArrayList<>();
}
///... other methods
#Override
public Filter getFilter() {
if(userFilter == null)
userFilter = new UserFilter(this, userList);
return userFilter;
}
private static class UserFilter extends Filter {
private final UserListAdapter adapter;
private final List<User> originalList;
private final List<User> filteredList;
private UserFilter(UserListAdapter adapter, List<User> originalList) {
super();
this.adapter = adapter;
this.originalList = new LinkedList<>(originalList);
this.filteredList = new ArrayList<>();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
filteredList.clear();
final FilterResults results = new FilterResults();
if (constraint.length() == 0) {
filteredList.addAll(originalList);
} else {
final String filterPattern = constraint.toString().toLowerCase().trim();
for (final User user : originalList) {
if (user.getName().contains(filterPattern)) {
filteredList.add(user);
}
}
}
results.values = filteredList;
results.count = filteredList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
adapter.filteredUserList.clear();
adapter.filteredUserList.addAll((ArrayList<User>) results.values);
adapter.notifyDataSetChanged();
}
}
}
After that in the place when you want to filtering call:
userListAdapter.getFilter().filter(text)
Here is complete sample code
Model Class
public class Skills {
int id;
String skill;
boolean isSelected;
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSkill() {
return skill;
}
public void setSkill(String skill) {
this.skill = skill;
}
}
Adapter Class
private static final String TAG = SkillAdapter.class.getSimpleName();
protected List<Skills> mOriginalData = new ArrayList<>();
protected List<Skills> mResultData = new ArrayList<>();
protected Activity mActivity;
OnRecyclerViewClick onRecyclerViewClick;
private ItemFilter mFilter = new ItemFilter();
public SkillAdapter(Activity activity, OnRecyclerViewClick onRecyclerViewClick) {
mActivity = activity;
this.onRecyclerViewClick = onRecyclerViewClick;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_skill,
parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Skills data = mResultData.get(position);
try {
final ViewHolder viewHolder = (ViewHolder) holder;
if (data != null) {
viewHolder.checkSkill.setText(data.getSkill());
viewHolder.checkSkill.setChecked(data.isSelected());
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return mResultData.size();
}
public void addItem(Skills exam) {
mOriginalData.add(exam);
mResultData.add(exam);
int index = mOriginalData.indexOf(exam);
notifyItemInserted(index);
}
public void removeItem(int index) {
mOriginalData.remove(index);
notifyItemRemoved(index);
}
public void removeItem(Skills exam) {
int index = mOriginalData.indexOf(exam);
mOriginalData.remove(exam);
notifyItemRemoved(index);
}
public Filter getFilter() {
return mFilter;
}
public Skills getItem(int index) {
return mOriginalData.get(index);
}
public void replaceItem(int index, Skills audioMeta) {
mOriginalData.set(index, audioMeta);
notifyItemChanged(index);
}
public class ViewHolder extends RecyclerView.ViewHolder {
CheckBox checkSkill;
public ViewHolder(View itemView) {
super(itemView);
checkSkill = (CheckBox) itemView.findViewById(R.id.chkSkill);
checkSkill.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onRecyclerViewClick.onItemClick(v, getLayoutPosition());
}
});
}
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
int count = mOriginalData.size();
final ArrayList<Skills> tempFilterList = new ArrayList<Skills>(count);
String filterableString;
for (int i = 0; i < count; i++) {
filterableString = mOriginalData.get(i).getSkill();
if (filterableString.toLowerCase().contains(filterString)) {
tempFilterList.add(mOriginalData.get(i));
}
}
results.values = tempFilterList;
results.count = tempFilterList.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mResultData.clear();
mResultData = (ArrayList<Skills>) results.values;
notifyDataSetChanged();
}
}
In Activity Use
mAdapter = new SkillAdapter(SkillsActivity.this, SkillsActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
recyclerView.setAdapter(mAdapter);
Then Filter
editSearch.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) {
mAdapter.getFilter().filter(editSearch.getText().toString());
}
});
Inside Fragment Class declare that:
protected List<User> mDataset;
protected List<User> mDataOrigin;
then inside onCreate add same source destination to both dataSet ant dataOrigin
mDataset = getObjectsFromDB();
mDataOrigin = getObjectsFromDB();
Finally use the magic function:
private void filterRecyclerView(String charText){
charText = charText.toLowerCase();
clearDataSet();
if (charText.length() == 0) {
mDataset.addAll(mDataOrigin);
} else {
for (User user : mDataOrigin) {
if (user.getName().toLowerCase().contains(charText)) {
mDataset.add(user);
}
}
}
mAdapter.notifyDataSetChanged();
}
Notice User is the list content you can replace with your Object have fun :)