I have used this solution to filter my RecyclerView. Using the solution I was able to get the result while typing. But when I clear the search widget I don't get the full list instead I get the empty RecyclerView.
This is how my result looks like.
https://imgur.com/nwyetEd
This is my Adapter
public class ContactsAdapter extends RecyclerView.Adapter<ContactViewHolder> {
private LayoutInflater inflater;
private ContactViewHolder viewHolder;
private ArrayList<Contact> contactsList = new ArrayList<>();
private VolleySingleton volleySingleton;
private ImageLoader imageLoader;
boolean fromMyContacts;
Context context;
public ContactsAdapter(Context context, boolean fromMyContacts){
inflater = LayoutInflater.from(context);
this.context = context;
volleySingleton = VolleySingleton.getsInstance();
imageLoader = volleySingleton.getImageLoader();
this.fromMyContacts = fromMyContacts;
}
public void setContactsList(ArrayList<Contact> contactsList){
this.contactsList = contactsList;
notifyItemRangeChanged(0, contactsList.size());
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.contact_list, parent, false);
viewHolder = new ContactViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ContactViewHolder holder, int position) {
Contact current = contactsList.get(position);
viewHolder.name.setText(current.name);
viewHolder.phone.setText(current.phone);
viewHolder.city.setText(current.location + ", " + current.city);
if(fromMyContacts) {
if (current.verified) {
viewHolder.verified.setImageResource(R.drawable.ic_check_circle);
} else {
viewHolder.verified.setImageResource(R.drawable.ic_cancel);
}
}
String image_url = current.image_url;
if(!image_url.equals("null")){
Picasso.with(context).load(image_url).into(viewHolder.contactIcon);
}else{
viewHolder.contactIcon.setImageResource(R.drawable.contact_icon);
}
}
#Override
public int getItemCount() {
return contactsList.size();
}
public Contact removeItem(int position){
final Contact contacts = contactsList.remove(position);
notifyItemRemoved(position);
return contacts;
}
public void addItem(int position, Contact contactList){
contactsList.add(position, contactList);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition){
final Contact contacts = contactsList.remove(fromPosition);
contactsList.add(toPosition, contacts);
notifyItemMoved(fromPosition, toPosition);
}
public void animateTo(List<Contact> contacts){
applyAndAnimateRemovals(contacts);
applyAndAnimateAdditions(contacts);
applyAndAnimateMovedItems(contacts);
}
private void applyAndAnimateRemovals(List<Contact> newModels) {
for (int i = contactsList.size() - 1; i >= 0; i--) {
final Contact model = contactsList.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<Contact> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final Contact model = newModels.get(i);
if (!contactsList.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(List<Contact> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final Contact model = newModels.get(toPosition);
final int fromPosition = contactsList.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
}
And this is my Model
public class Contact {
String name;
String phone;
String city;
String location;
Boolean verified;
String image_url;
public Contact(String name, String phone, String city, String location, Boolean verified, String image_url){
this.name = name;
this.phone = phone;
this.city = city;
this.location = location;
this.verified = verified;
this.image_url = image_url;
}
}
This is the Activity where I use my filter
public class MyContactsActivity extends AppCompatActivity implements View.OnClickListener, SearchView.OnQueryTextListener {
private RecyclerView recyclerView;
private ContactsAdapter adapter;
private NetworkChecker networkChecker;
private SessionManager sessionManager;
private AppConfig appConfig;
private RelativeLayout loading, retry;
private Button tryAgain;
AlertHelper alertHelper;
final ArrayList<Contact> contactArrayList = new ArrayList<>();
String url;
DebugHelper debugHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_contacts);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
debugHelper = new DebugHelper();
loading = (RelativeLayout) findViewById(R.id.loadingPanel);
retry = (RelativeLayout) findViewById(R.id.retry);
tryAgain = (Button) findViewById(R.id.tryAgainButton);
tryAgain.setOnClickListener(this);
alertHelper = new AlertHelper(this);
networkChecker = new NetworkChecker(this);
sessionManager = new SessionManager(this);
appConfig = new AppConfig();
String phone = sessionManager.getLoggedInUserPhone();
url = appConfig.getApiUrlForSpecificContacts(phone);
recyclerView = (RecyclerView) findViewById(R.id.contactsView);
adapter = new ContactsAdapter(getApplicationContext(), true);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
sendJsonRequest(url);
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
TextView phone = (TextView) view.findViewById(R.id.contact_phone);
TextView name = (TextView) view.findViewById(R.id.contact_name);
Intent i = new Intent(getApplicationContext(), ContactProfileActivity.class);
i.putExtra("selected_user_phone", phone.getText());
i.putExtra("selected_user_name", name.getText());
startActivity(i);
}
})
);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), AddContactActivity.class));
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private void sendJsonRequest(String url) {
if (networkChecker.networkAvailable()) {
loading.setVisibility(View.VISIBLE);
RequestQueue requestQueue = VolleySingleton.getsInstance().getmRequestQueue();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.setVisibility(View.GONE);
retry.setVisibility(View.GONE);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("contact_info");
if(jsonArray != null){
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject currentContact = jsonArray.getJSONObject(i);
String name = currentContact.getString("name");
String phone = currentContact.getString("phone");
String city = currentContact.getString("city");
String address = currentContact.getString("address");
Boolean verified = currentContact.getBoolean("verified");
String image_url = currentContact.getString("image_url");
Contact contact = new Contact(name, phone, city, address, verified, image_url);
contactArrayList.add(contact);
}
adapter.setContactsList(contactArrayList);
}
else{
alertHelper.displayDialog("No Contacts Found.");
}
}catch (Exception e){
retry.setVisibility(View.VISIBLE);
tryAgain.setClickable(true);
alertHelper.displayDialog(getString(R.string.action_failed_try_again));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
retry.setVisibility(View.VISIBLE);
tryAgain.setClickable(true);
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
alertHelper.displayDialog(getString(R.string.connection_failed));
} else {
alertHelper.displayDialog(getString(R.string.action_failed_try_again));
}
}
});
requestQueue.add(stringRequest);
} else {
retry.setVisibility(View.VISIBLE);
tryAgain.setClickable(true);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.contact_list_menu, menu);
debugHelper.L("Search Click Vayo");
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tryAgainButton:
sendJsonRequest(url);
break;
}
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
final List<Contact> filteredModelList = filter(contactArrayList, query);
adapter.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
return true;
}
private List<Contact> filter(List<Contact> models, String query) {
query = query.toLowerCase();
if(query.equals("")) { return contactArrayList; }
final List<Contact> filteredModelList = new ArrayList<>();
for (Contact model : models) {
final String text = model.name.toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
Can anyone help me please?
assuming contactsList is var with the full contacts
private List<Contact> filter(List<Contact> models, String query) {
query = query.toLowerCase();
if(query.equals("")) { return contactsList; }
final List<Contact> filteredModelList = new ArrayList<>();
for (Contact model : models) {
final String text = model.name.toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
He has defined in this way:
public void setModels(List<ExampleModel> models) {
mModels = new ArrayList<>(models);
}
Initialize like the way he has done.
Your soultion would be:
this.contactsList = new ArrayList<>(contactsList);
You need to move your filter() method from your Activity to your Adapter. At your Adapter add one additional variable to hold a copy of unfiltered dataset. In your case, you need contactsList and copyOfContactsList variables.
Change your Adapter's constructor as follows:
public class ContactsAdapter extends RecyclerView.Adapter<ContactViewHolder> {
....
private ArrayList<Contact> contactsList = new ArrayList<>();
private ArrayList<Contact> copyOfContactsList = new ArrayList<>();
....
public ContactsAdapter(Context context, ArrayList<Contact> dataSet, boolean fromMyContacts){
...
this.contactsList = dataSet;
copyOfContactsList.addAll(dataSet);
...
}
and this is the filter method to be added to your Adapter:
public void filter(String text) {
if(text.isEmpty()){
contactsList.clear();
contactsList.addAll(copyOfContactsList);
} else{
ArrayList<Contact> result = new ArrayList<>();
text = text.toLowerCase();
for(Contact item: copyOfContactsList){
if(item.getName().toLowerCase().contains(text)){
result.add(item);
}
}
contactsList.clear();
contactsList.addAll(result);
}
notifyDataSetChanged();
}
Related
i want to make a filter search function to my jsonobject array in recyclerview
i tried the getfilter in my adapter and pass it to my add_detail
but it gives me force close when i type a text in my app_detail activity
heres my app_detail.java :
public class app_detail extends AppCompatActivity implements PemrogramanAdapter.OnItemClickListener {
TextView nametxt;
ImageView imageView,listimageview;
private RecyclerView mRecyclerView;
private List<Object> mRecyclerViewItems = new ArrayList<>();
private SearchView searchView;
PemrogramanAdapter pemrogramanAdapters;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_detail);
nametxt = (TextView) findViewById(R.id.list_app_text_detail);
imageView = (ImageView) findViewById(R.id.list_app_image_detail);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setTitle("test");
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view1);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
PemrogramanAdapter pemrogramanAdapter = new PemrogramanAdapter(this,mRecyclerViewItems);
mRecyclerView.setAdapter(pemrogramanAdapter);
pemrogramanAdapter.setmListener(app_detail.this);
tambahMenuItemDariJson();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView)menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
pemrogramanAdapters.getFilter().filter(s);
return false;
}
#Override
public boolean onQueryTextChange(String s) {
pemrogramanAdapters.getFilter().filter(s);
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.action_search)
return true;
if(id == android.R.id.home)
this.finish();
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if(!searchView.isIconified())
{
searchView.setIconified(true);
return;
}
super.onBackPressed();
Animatoo.animateZoom(app_detail.this);
}
private void tambahMenuItemDariJson() {
try{
String jsonDataString = readJsonDataDariFile();
JSONArray menuItemsJsonArray = new JSONArray(jsonDataString);
for(int i = 0; i<menuItemsJsonArray.length(); ++i){
JSONObject menuItemObject =menuItemsJsonArray.getJSONObject(i);
String txt_id_app = menuItemObject.getString("id_app");
String txt_title = menuItemObject.getString("masalah");
String txt_id = menuItemObject.getString("id");
String txt_keterangan = menuItemObject.getString("ket");
String txt_langkah = menuItemObject.getString("langkah");
item item = new item(txt_id_app,txt_id,txt_title,txt_keterangan,txt_langkah);
mRecyclerViewItems.add(item);
}
} catch (IOException | JSONException exception){
Log.e(guidesoftware.class.getName(),"Tidak BISA BUKA FILE JSON!",exception);
}
}
private String readJsonDataDariFile() throws IOException {
InputStream inputStream = null;
StringBuilder builder = new StringBuilder();
//menentukan konten
Intent intent = this.getIntent();
int position = intent.getExtras().getInt("POS_KEY");
int jsonlocation = 0;
//kondisi per lokasi
if(position == 0){
jsonlocation = R.raw.pemrograman_octave;
}else if(position == 1){
jsonlocation = R.raw.pemrograman_netbeans;
}else if(position == 2){
jsonlocation = R.raw.pemrograman_devcpp;
}else if(position == 3){
jsonlocation = R.raw.pemrograman_notepad;
}
try {
String jsonDataString = null;
inputStream = getResources().openRawResource(jsonlocation);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
while ((jsonDataString = bufferedReader.readLine()) != null){
builder.append(jsonDataString);
}
}finally {
if(inputStream != null){
inputStream.close();
}
}
return new String(builder);
}
#Override
public void onItemSelected(int position) {
Intent detailIntent = new Intent(this,fortest.class);
item clickeditem = (item) mRecyclerViewItems.get(position);
detailIntent.putExtra(EXTRA_MASALAH,clickeditem.getMasalah());
detailIntent.putExtra(EXTRA_KETERANGAN,clickeditem.getKet());
detailIntent.putExtra(EXTRA_LANGKAH,clickeditem.getLangkah());
startActivity(detailIntent);
}}
and here is my pemrogramanAdapter.java :
public class PemrogramanAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable{
private static final int MENU_ITEM_VIEW_TYPE = 0;
private final Context context;
private final List<Object> recyclerViewItem;
private List<Object> filterrecyclerViewItem;
private OnItemClickListener mListener;
public PemrogramanAdapter(Context context, List<Object> recyclerViewItem) {
this.context = context;
this.recyclerViewItem = recyclerViewItem;
this.filterrecyclerViewItem = recyclerViewItem;
}
public void setmListener(OnItemClickListener mListener) {
this.mListener = mListener;
}
public class MenuItemViewHolder extends RecyclerView.ViewHolder{
public TextView txt_title,txt_keterangan;
public ImageView txt_image;
public MenuItemViewHolder(View view){
super(view);
txt_title = (TextView)view.findViewById(R.id.title);
txt_keterangan = (TextView)view.findViewById(R.id.isi);
txt_image = (ImageView)view.findViewById(R.id.avatar);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
mListener.onItemSelected(position);
}
}
}
});
}
}
#Override
public int getItemCount() {
return recyclerViewItem.size();
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
switch (i){
case MENU_ITEM_VIEW_TYPE:
default:
View menuItemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_layout,viewGroup,false);
return new MenuItemViewHolder(menuItemLayoutView);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
int viewType = getItemViewType(position);
switch (viewType){
case MENU_ITEM_VIEW_TYPE:
default:
MenuItemViewHolder menuItemViewHolder = (MenuItemViewHolder) holder;
item menuItem = (item) recyclerViewItem.get(position);
menuItemViewHolder.txt_title.setText(menuItem.getMasalah());
menuItemViewHolder.txt_keterangan.setText(menuItem.getKet());
menuItemViewHolder.txt_image.setImageResource(R.drawable.pemrog_netbeans);
}
}
public interface OnItemClickListener{
void onItemSelected (int position);
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String searchString = charSequence.toString();
if(searchString.isEmpty())
filterrecyclerViewItem = recyclerViewItem; //for se kembalikan item yg di search ke semula
else{
List<Object> resultList = new ArrayList<>();
for(Object data : recyclerViewItem)
{
item item = new item();
if(item.getMasalah().toLowerCase().contains(searchString.toLowerCase() ))
resultList.add(item);
}
filterrecyclerViewItem = resultList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = filterResults;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults filterResults) {
filterrecyclerViewItem = (ArrayList<Object>)filterResults.values;
notifyDataSetChanged();
}
};
}
}
i want to make the filter search works on my jsonObject in app_detail.java
I have a recyclerview with some data and I have a searchview, and filter is working just fine. But un-filtering not working. I can't get the whole data in the recyclerview after un-filter. No data is showing. I have to re-open the activity to get data. I tried to used two data sets. But i have no idea where to use them.
My Fragment.
public class YourDealerListFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static final String STATE_DEALER_LIST = "state_dealer_list";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private VollySingleton vollySingleton;
private RequestQueue requestQueue;
private RecyclerView recyclerView;
private DealerListAdapter dlAdapter;
private HashMap<String, String> hashMap;
private ArrayList<SuggestGetSet> dealerList = new ArrayList<>();
private ArrayList<SuggestGetSet> filteredDealerList = new ArrayList<>();
private String repNo;
private StaggeredGridLayoutManager staggeredGridLayoutManager;
private GridMenuFragment mGridMenuFragment;
private Toolbar toolbar;
private ItemSorter itemSorter;
private Button sortButton;
private SearchView searchView;
private ProgressView progressView;
public static List<String> disChannel;
public YourDealerListFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment YourDealerListFragment.
*/
// TODO: Rename and change types and number of parameters
public static YourDealerListFragment newInstance(String param1, String param2) {
YourDealerListFragment fragment = new YourDealerListFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
vollySingleton = VollySingleton.getsInstance();
requestQueue = vollySingleton.getmRequestQueue();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_your_dealer_list, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.dealerListRecyclerView);
progressView = (ProgressView) view.findViewById(R.id.pViewew);
itemSorter = new ItemSorter();
dlAdapter = new DealerListAdapter();
disChannel = new ArrayList<String>();
repNo = UserLogIn.getRepNo();
if (savedInstanceState != null) {
dealerList = savedInstanceState.getParcelableArrayList(STATE_DEALER_LIST);
dlAdapter.setDealertList(dealerList);
} else {
getJsonRequest();
}
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.frame_layout);
frameLayout.getBackground().setAlpha(0);
final FloatingActionsMenu fabMenu = (FloatingActionsMenu) view.findViewById(R.id.fab_menu);
final FloatingActionButton fabName = (FloatingActionButton) view.findViewById(R.id.fab_name);
final FloatingActionButton fabCollection = (FloatingActionButton) view.findViewById(R.id.fab_collection);
fabName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onSortByName();
fabMenu.collapse();
}
});
fabMenu.setOnFloatingActionsMenuUpdateListener(new FloatingActionsMenu.OnFloatingActionsMenuUpdateListener() {
#Override
public void onMenuExpanded() {
frameLayout.getBackground().setAlpha(240);
frameLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
fabMenu.collapse();
return true;
}
});
}
#Override
public void onMenuCollapsed() {
frameLayout.getBackground().setAlpha(0);
frameLayout.setOnTouchListener(null);
}
});
searchView = (SearchView) view.findViewById(R.id.dealerNameSearchView);
searchView.setOnQueryTextListener(listener);
//custom context menu
mGridMenuFragment = GridMenuFragment.newInstance(R.drawable.background);
setupGridMenu();
mGridMenuFragment.setOnClickMenuListener(new GridMenuFragment.OnClickMenuListener() {
#Override
public void onClickMenu(GridMenu gridMenu, int position) {
switch (position) {
case 0:
Intent intent = new Intent(getActivity(), SelectItem.class);
getActivity().finish();
startActivity(intent);
getActivity();
break;
}
}
});
//dealers' recycler view item click
recyclerView.addOnItemTouchListener(new NavigationDrawerFragment.RecycleTouchListner(getActivity(), recyclerView, new NavigationDrawerFragment.ClickListener() {
#Override
public void onClick(View view, int position) {
FragmentTransaction tx = getActivity().getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main_frame, mGridMenuFragment);
tx.addToBackStack(null);
tx.commit();
}
}));
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
final ArrayList<SuggestGetSet> filteredModelList = new ArrayList<>();
for (SuggestGetSet movie : filteredModelList) {
filteredModelList.add(movie);
}
dlAdapter = new DealerListAdapter(filteredModelList, getActivity());
recyclerView.setAdapter(dlAdapter);
}
//search dealer from search view
SearchView.OnQueryTextListener listener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
final ArrayList<SuggestGetSet> filteredModelList = filter(dealerList, s);
dlAdapter.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
return true;
}
};
private ArrayList<SuggestGetSet> filter(ArrayList<SuggestGetSet> models, String query) {
query = query.toLowerCase();
final ArrayList<SuggestGetSet> filteredModelList = new ArrayList<>();
for (SuggestGetSet model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
//custom context menu data
private void setupGridMenu() {
List<GridMenu> menus = new ArrayList<>();
menus.add(new GridMenu("Order", R.drawable.nnn));
menus.add(new GridMenu("Banking", R.drawable.n));
menus.add(new GridMenu("Credit Note", R.drawable.nn));
menus.add(new GridMenu("Cheques", R.drawable.nnnn));
menus.add(new GridMenu("Invoice Dispatch", R.drawable.nnnnn));
menus.add(new GridMenu("Goods Return", R.drawable.nnnnnn));
mGridMenuFragment.setupMenu(menus);
}
private void getJsonRequest() {
progressView.start();
final SQLiteHandler sqLiteHandler = new SQLiteHandler(getActivity().getApplicationContext());
Cursor cr = sqLiteHandler.getData(sqLiteHandler);
cr.moveToFirst();
do {
repNo = cr.getString(0);
} while (cr.moveToNext());
cr.close();
CustomJsonObjectRequest request = new CustomJsonObjectRequest(Request.Method.POST, AppConfig.URL_JSON_DEALER_LIST, hashMap, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressView.stop();
try {
JSONObject jsonObject = new JSONObject(String.valueOf(response));
if (jsonObject.names().get(0).equals("feed")) {
dealerList = parseJsonResponse(response);
dlAdapter.setDealertList(dealerList);
JSONArray arrayAchSum = response.getJSONArray("feedd");
for (int i = 0; i < arrayAchSum.length(); i++) {
JSONObject obj3 = arrayAchSum.getJSONObject(i);
String a = obj3.getString("dis_channel");
disChannel.add(a);
}
} else {
Toast.makeText(getActivity(), "No Dealers Available", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
/*dealerList = parseJsonResponse(response);
dlAdapter.setDealertList(dealerList);*/
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
protected Map<String, String> getParams() throws AuthFailureError {
hashMap = new HashMap<String, String>();
hashMap.put("repNo", repNo);
return hashMap;
}
};
requestQueue.add(request);
request.setRetryPolicy(new DefaultRetryPolicy(15 * 1000, 0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
private ArrayList<SuggestGetSet> parseJsonResponse(JSONObject response) {
ArrayList<SuggestGetSet> groupList = new ArrayList<>();
if (response != null || response.length() > 0) {
try {
JSONArray arrayDelaers = response.getJSONArray(KEY_FEED_NAME);
for (int i = 0; i < arrayDelaers.length(); i++) {
JSONObject currentObject = arrayDelaers.getJSONObject(i);
String rep = currentObject.getString(KEY_REP_ID);
String name = currentObject.getString(KEY_REP_NAME);
String dealerId = currentObject.getString(KEY_DEALER_ID);
SuggestGetSet delaers = new SuggestGetSet();
delaers.setId(rep);
delaers.setName(name);
delaers.setDealerId(dealerId);
groupList.add(delaers);
}
//Toast.makeText(getApplicationContext(), productList.toString(), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
return groupList;
}
public void onSortByName() {
itemSorter.sortItemByName(dealerList);
dlAdapter.notifyDataSetChanged();
}
public static interface ClickListener {
public void onClick(View view, int position);
//public void onLongClick(View view, int position);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_DEALER_LIST, dealerList);
}
}
My Adapter class.
public class DealerListAdapter extends RecyclerView.Adapter<DealerListAdapter.ViewHolderDealerList> {
private LayoutInflater layoutInflater;
public Context mcontext;
private List<SuggestGetSet> dealerArrayList;
private List<SuggestGetSet> originalDealerArrayList;
Typeface type;
private static String selectedRepId, selectedDealerId, selectedDealerName;
public DealerListAdapter() {
}
public DealerListAdapter(Context context) {
layoutInflater = LayoutInflater.from(context);
type = Typeface.createFromAsset(context.getAssets(), "helvr.ttf");
}
public static String getDealerName() {
return selectedDealerName;
}
public static String getDealerID() {
return selectedDealerId;
}
public static String getRepID() {
return selectedRepId;
}
public DealerListAdapter(ArrayList<SuggestGetSet> dList, Context context) {
this.mcontext = context;
layoutInflater = LayoutInflater.from(context);
dealerArrayList = new ArrayList<>(dList);
originalDealerArrayList = new ArrayList<>(dList);
type = Typeface.createFromAsset(context.getAssets(), "helvr.ttf");
}
public void setDealertList(ArrayList<SuggestGetSet> dealerAList) {
this.dealerArrayList = dealerAList;
originalDealerArrayList = new ArrayList<>(dealerAList);
notifyItemRangeChanged(0, dealerArrayList.size());
}
#Override
public ViewHolderDealerList onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.custom_dealer_list_layout, parent, false);
ViewHolderDealerList viewHolderDealerList = new ViewHolderDealerList(view);
return viewHolderDealerList;
}
#Override
public void onBindViewHolder(ViewHolderDealerList holder, int position) {
final SuggestGetSet model = dealerArrayList.get(position);
holder.bind(model);
final int pos = position;
holder.dealerName.setText(dealerArrayList.get(position).getName());
holder.dealerName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedDealerId = dealerArrayList.get(pos).getDealerId();
selectedRepId = dealerArrayList.get(pos).getId();
selectedDealerName = dealerArrayList.get(pos).getName();
Toast.makeText(layoutInflater.getContext(), dealerArrayList.get(pos).getName() + " / " + dealerArrayList.get(pos).getDealerId() + " / " + dealerArrayList.get(pos).getId(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return dealerArrayList.size();
}
public void setModels(ArrayList<SuggestGetSet> models) {
dealerArrayList = new ArrayList<>(models);
}
static class ViewHolderDealerList extends RecyclerView.ViewHolder {
private TextView dealerName, dealerId;
public ViewHolderDealerList(View itemView) {
super(itemView);
dealerName = (TextView) itemView.findViewById(R.id.yourDelaerName);
//dealerId = (TextView) itemView.findViewById(R.id.txtDelaerCollection);
}
public void bind(SuggestGetSet model) {
dealerName.setText(model.getName());
}
}
//search animations
public SuggestGetSet removeItem(int position) {
final SuggestGetSet model = dealerArrayList.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, SuggestGetSet model) {
dealerArrayList.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final SuggestGetSet model = dealerArrayList.remove(fromPosition);
dealerArrayList.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
public void animateTo(ArrayList<SuggestGetSet> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
private void applyAndAnimateMovedItems(ArrayList<SuggestGetSet> models) {
for (int toPosition = dealerArrayList.size() - 1; toPosition >= 0; toPosition--) {
final SuggestGetSet model = dealerArrayList.get(toPosition);
final int fromPosition = models.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
notifyDataSetChanged();
}
private void applyAndAnimateAdditions(ArrayList<SuggestGetSet> models) {
for (int i = 0, count = dealerArrayList.size(); i < count; i++) {
final SuggestGetSet model = dealerArrayList.get(i);
if (!models.contains(model)) {
addItem(i, model);
}
}
notifyDataSetChanged();
}
private void applyAndAnimateRemovals(ArrayList<SuggestGetSet> models) {
for (int i = dealerArrayList.size() - 1; i >= 0; i--) {
final SuggestGetSet model = dealerArrayList.get(i);
if (!models.contains(model)) {
removeItem(i);
}
}
notifyDataSetChanged();
}
}
Just Modify your function and Add check for null or "" .
it will work fine
private ArrayList<SuggestGetSet> filter(ArrayList<SuggestGetSet> models, String query) {
if(TextUtils.isEmpty(query)){
return models;
}
query = query.toLowerCase();
final ArrayList<SuggestGetSet> filteredModelList = new ArrayList<>();
for (SuggestGetSet model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
I am currently using searchView to filter results on a RecyclerView. The problem is when the fragment is initialized, the list won't appear not until I click on the search icon on the toolbar and type some texts on it. I've tried modifying the codes. Take a look specifically at the adapter and holder classes, if you'll try to exchange my current codes to these:
public MembershipActivationAdapter(Context context, List<Member> members){
this.context = context;
this.mMembers = members;
}
and
#Override
public MembershipActivationViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
final View itemView = LayoutInflater.from(context).inflate(R.layout.member_activation_content, viewGroup, false);
}
,it will show the list upon calling the fragment however if I'll type something on the SearchView, it seems to function only as a one way filter. It will filter names but whenever I'll try to remove a character or a text on the searchview, it won't show the list back. Please help me with this. These are my codes:
Adapter & ViewHolder class:
public class MembershipActivationAdapter extends RecyclerView.Adapter<MembershipActivationAdapter.MembershipActivationViewHolder> {
private final List<Member> mMembers;
private final LayoutInflater inflater;
//private final Context context;
public MembershipActivationAdapter(Context context, List<Member> members){
inflater = LayoutInflater.from(context);
mMembers = new ArrayList<>(members);
//this.context = context;
//this.mMembers = members;
}
#Override
public int getItemCount() {
return mMembers.size();
}
#Override
public void onBindViewHolder(MembershipActivationViewHolder holder, final int position) {
final Member m = mMembers.get(position);
holder.name.setText(m.getName());
holder.email.setText(m.getEmail());
if(m.getStatus().equals("Active")){
holder.status.setText(Html.fromHtml("<font color='#00CD00'>" + m.getStatus() + "</font>"));
}else{
holder.status.setText(Html.fromHtml("<font color='#ff0000'>" + m.getStatus() + "</font>"));
}
}
#Override
public MembershipActivationViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
final View itemView = inflater.inflate(R.layout.member_activation_content, viewGroup, false);
return new MembershipActivationViewHolder(itemView);
//final View itemView = LayoutInflater.from(context).inflate(R.layout.member_activation_content, viewGroup, false);
}
public static class MembershipActivationViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public final TextView name;
public final TextView email;
public final TextView status;
public MembershipActivationViewHolder(View v) {
super(v);
v.setOnClickListener(this);
name = (TextView) v.findViewById(R.id.member_name);
email = (TextView) v.findViewById(R.id.member_email);
status = (TextView) v.findViewById(R.id.member_status);
}
}
public List<Member> getMemberList() {
return mMembers;
}
public void animateTo(List<Member> members) {
applyAndAnimateRemovals(members);
applyAndAnimateAdditions(members);
applyAndAnimateMovedItems(members);
}
private void applyAndAnimateRemovals(List<Member> newMembers) {
for (int i = mMembers.size() - 1; i >= 0; i--) {
final Member member = mMembers.get(i);
if (!newMembers.contains(member)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<Member> newMembers) {
for (int i = 0, count = newMembers.size(); i < count; i++) {
final Member member = newMembers.get(i);
if (!mMembers.contains(member)) {
addItem(i, member);
}
}
}
private void applyAndAnimateMovedItems(List<Member> newMembers) {
for (int toPosition = newMembers.size() - 1; toPosition >= 0; toPosition--) {
final Member member = newMembers.get(toPosition);
final int fromPosition = mMembers.indexOf(member);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
public Member removeItem(int position) {
final Member member = mMembers.remove(position);
notifyItemRemoved(position);
return member;
}
public void addItem(int position, Member member) {
mMembers.add(position, member);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final Member member = mMembers.remove(fromPosition);
mMembers.add(toPosition, member);
notifyItemMoved(fromPosition, toPosition);
}
}
Fragment Class:
public class MembershipActivationFragment extends Fragment implements SearchView.OnQueryTextListener{
private static String url = "http://www.xxxxx.org/portal/webservices/get_members.php";
private List<Member> memberList;
private RecyclerView recyclerView;
private MembershipActivationAdapter adapter;
private String pid;
private ProgressDialog progressDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.member_activation, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.members_recycler_view);
setHasOptionsMenu(true);
memberList = new ArrayList<>();
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.show();
populate();
return rootView;
}
public void populate(){
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
hidePDialog();
String name, email, status;
Member member;
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject object = jsonArray.getJSONObject(i);
name = object.getString("firstname") + " " + object.getString("lastname");
email = object.getString("email");
if(Integer.parseInt(object.getString("activated"))==1){
status = "Active";
}else{
status = "Not Active";
}
member = new Member(name, email, status);
memberList.add(member);
} catch (Exception e) {
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
volleyError.printStackTrace();
}
});
AppController.getInstance().addToRequestQueue(request);
adapter = new MembershipActivationAdapter(getActivity(), memberList);
recyclerView.setAdapter(adapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search_menu, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextChange(String query) {
final List<Member> filteredMemberList = filter(memberList, query);
adapter.animateTo(filteredMemberList);
recyclerView.scrollToPosition(0);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
private List<Member> filter(List<Member> members, String query) {
query = query.toLowerCase();
final List<Member> filteredModelList = new ArrayList<>();
for (Member member : members) {
final String text = member.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(member);
}
}
return filteredModelList;
}
private void hidePDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
}
}
RecyclerView container xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/members_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
Content class:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5dip">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name here"
android:textStyle="bold"
android:id="#+id/member_name"
android:layout_centerVertical="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="email#gmail.com"
android:id="#+id/member_email"
android:layout_below="#+id/member_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="email#gmail.com"
android:id="#+id/member_status"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</LinearLayout>
Model Class:
public class Member {
private String name;
private String email;
private String status;
public Member(String name, String email, String status) {
this.name = name;
this.email = email;
this.status = status;
}
public Member(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
Atlast! I was able to find the resolution for this. Kudos to the developer himself, Xaver Kapeller!
public void populate(){
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
// hidePDialog();
String email, status;
// Member member;
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject object = jsonArray.getJSONObject(i);
final String name = object.getString("firstname") + " " + object.getString("lastname");
email = object.getString("email");
if(Integer.parseInt(object.getString("activated"))==1){
status = "Active";
}else{
status = "Not Active";
}
mModels.add(new ExampleModel(name));
// member = new Member(name, email, status);
} catch (Exception e) {
}
}
mAdapter = new ExampleAdapter(getActivity(), mModels);
mRecyclerView.setAdapter(mAdapter);
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
volleyError.printStackTrace();
}
});
AppController.getInstance().addToRequestQueue(request);
}
Just tranfer these two lines of code inside onResponse() and everything will work perfectly fine:
mAdapter = new ExampleAdapter(getActivity(), mModels);
mRecyclerView.setAdapter(mAdapter);
I'm trying to implement searchview. It works somehow, but the problem is that after you start typing it is one-way street. You get the info but if you delete text, you won't get the result as it was in the beginning. I'm working with cardviews.
Marker is a model(gettitle etc.)
My Adapter:
public class AdapterRestavracije extends
RecyclerView.Adapter<AdapterRestavracije.ViewHolderRestavracije> {
ArrayList<Marker> arrayList;
private LayoutInflater layoutInflater;
private VolleySingleton mVolleySingleton;
Context context;
public AdapterRestavracije(Context context, ArrayList<Marker> models) {
layoutInflater = LayoutInflater.from(context);
this.context = context;
mVolleySingleton = VolleySingleton.getsIstance();
arrayList = new ArrayList<Marker>(models);
// this.arrayList = new ArrayList<Marker>();
}
public void setRestaurants(ArrayList<Marker> arrayList) {
this.arrayList = arrayList;
notifyItemChanged(0, arrayList.size());
}
#Override
public ViewHolderRestavracije onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.restaurants_rview, parent, false);
ViewHolderRestavracije viewHolder = new ViewHolderRestavracije(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolderRestavracije holder, int position) {
Marker currentRest = arrayList.get(position);
holder.name.setText(currentRest.getTitle());
holder.address.setText(currentRest.getAddress());
holder.placilo.setText(currentRest.getValue_of_charge() + " €");
holder.oddaljenost.setText(currentRest.getOddaljenost());
holder.idrestavracije.setText(currentRest.getId());
try {
holder.ratingBarOverall.setRating(Float.parseFloat(currentRest.getOverallRating()));
} catch (Exception e) {
holder.ratingBarOverall.setRating(0);
}
Log.d("RESTAVRACIJEEEEE", currentRest.getTitle());
}
#Override
public int getItemCount() {
return arrayList.size();
}
class ViewHolderRestavracije extends RecyclerView.ViewHolder {
private TextView name, oddaljenost, address, textPlacilo, placilo, idrestavracije;
private RatingBar ratingBarOverall;
private int id;
public View view;
public ViewHolderRestavracije(View itemView) {
super(itemView);
view = itemView;
name = (TextView) itemView.findViewById(R.id.tvNameRestaurant);
oddaljenost = (TextView) itemView.findViewById(R.id.tvOddaljenost);
address = (TextView) itemView.findViewById(R.id.tvAddress);
textPlacilo = (TextView) itemView.findViewById(R.id.tvDoplacilo);
placilo = (TextView) itemView.findViewById(R.id.tvDoplaciloEvri);
idrestavracije = (TextView) itemView.findViewById(R.id.idrestavracije);
ratingBarOverall = (RatingBar) itemView.findViewById(R.id.ratingOverallRestavracije);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//id = getAdapterPosition();
//Log.d("CLICKED", idrestavracije.getText().toString() + "");
//Log.d("CLICKED", name.getText().toString() + "");
String idrest = idrestavracije.getText().toString();
// Log.d("CLICKED", intid + "");
// Intent i = new Intent(context, RestaurantActivity.class);
// i.putExtra("ID_rest", intid);
// context.startActivity(i);
Intent i = new Intent(context, RestaurantActivity.class);
Bundle bundle = new Bundle();
bundle.putString("ID_rest", idrest);
i.putExtras(bundle);
context.startActivity(i);
}
});
}
}
////PRIPRAVA ZA SEARCH//////
public void animateTo(ArrayList<Marker> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
private void applyAndAnimateRemovals(ArrayList<Marker> newModels) {
for (int i = arrayList.size() - 1; i >= 0; i--) {
final Marker model = arrayList.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(ArrayList<Marker> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final Marker model = newModels.get(i);
if (!arrayList.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(ArrayList<Marker> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final Marker model = newModels.get(toPosition);
final int fromPosition = arrayList.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
public Marker removeItem(int position) {
final Marker model = arrayList.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, Marker model) {
arrayList.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final Marker model = arrayList.remove(fromPosition);
arrayList.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
////PRIPRAVA ZA SEARCH//////
}
MY FRAGMENT:
---OTHER CODE----
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
recyclerView = (RecyclerView) view.findViewById(R.id.listRestaurants);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// recyclerView.setItemAnimator(new DefaultItemAnimator());
listRestaurants = new ArrayList<Marker>();
jsonRequest(latitude, longitude);
adapterRestavracije = new AdapterRestavracije(getActivity(),listRestaurants);
recyclerView.setAdapter(adapterRestavracije);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main_menu2, menu);
MenuItem item = menu.findItem(R.id.action_search);
final SearchView sv = (SearchView) MenuItemCompat.getActionView(item);
sv.setOnQueryTextListener(this);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onQueryTextSubmit(String query) {
// Utils.LogDebug("Submitted: "+query);
Log.d("Clicked: ", query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
// Utils.LogDebug("Changed: " + newText);
final ArrayList<Marker> filteredModelList = filter(listRestaurants, query);
adapterRestavracije.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
//Log.d("Query Changed: ", query);
return false;
}
private ArrayList<Marker> filter(ArrayList<Marker> listRestaurants, String query) {
query = query.toLowerCase();
final ArrayList<Marker> filteredModelList = new ArrayList<Marker>();
for (Marker model : listRestaurants) {
final String text = model.getTitle().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
---OTHER CODE----
Thanks for the help.
Wow, fixed the problem. The problem was that the arraylist wasn't declared as final. So now that i did that it works :).
Example:
before:
List<ExampleModel> mModels;
after:
private final List<ExampleModel> mModels;
http://i.stack.imgur.com/HZ3v6.png
this is the picture of the recycler view
i dont understand what might be causing this problem. so please guys can you give a probablity of what might be the reason.
Thanks in Advance.
public class ProductAdaptor extends RecyclerView.Adapter<ProductAdaptor.ProductViewHolder> {
//implements Filterable {
private final LayoutInflater inflator;
private final List<ProductInfo> products;
private Context context;
private ProductAdapterListener listener;
ImageLoader imageLoader = VolleySingleton.getInstance().getImageLoader();
//private List<ProductInfo> BackupProducts= Collections.emptyList();
ProductInfo current;
public ProductAdaptor(Context context, List<ProductInfo> data, ProductAdapterListener listener) {
inflator = LayoutInflater.from(context);
products = data;
this.context = context;
this.listener = listener;
//BackupProducts=data;
}
#Override
public ProductAdaptor.ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflator.inflate(R.layout.custom_product, parent, false);
ProductViewHolder holder = new ProductViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ProductAdaptor.ProductViewHolder holder, final int position) {
current = products.get(position);
holder.title.setText(current.getName());
holder.icon.setImageUrl(current.getImage(), imageLoader);
holder.price.setText("Price: Rs. " + current.getPrice());
holder.description.setText(current.getDescription());
holder.add_Cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
products.get(position).setQuantity(Integer.parseInt(holder.etQuantity.getText().toString()));
listener.onAddToCartPressed(products.get(position));
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Reading Position", "" + current.getId());
Intent base = new Intent(context, Products.class);
base.putExtra("product_id", Integer.parseInt(products.get(position).getId()));
base.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
context.startActivity(base);
}
});
}
public void setData(List<ProductInfo> list) {
products.clear();
products.addAll(list);
notifyDataSetChanged();
}
/*
public void flushFilter(){
products.clear();
products.addAll(BackupProducts);
notifyDataSetChanged();
}*/
public void animateTo(List<ProductInfo> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
private void applyAndAnimateRemovals(List<ProductInfo> newModels) {
for (int i = products.size() - 1; i >= 0; i--) {
final ProductInfo model = products.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<ProductInfo> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final ProductInfo model = newModels.get(i);
if (!products.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(List<ProductInfo> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final ProductInfo model = newModels.get(toPosition);
final int fromPosition = products.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
public ProductInfo removeItem(int position) {
final ProductInfo model = products.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, ProductInfo model) {
products.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final ProductInfo model = products.remove(fromPosition);
products.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
#Override
public int getItemCount() {
return products.size();
}
/*
#Override
public Filter getFilter() {
//flushFilter();
return new CardFilter(this,BackupProducts);
}
*/
public interface ProductAdapterListener {
void onAddToCartPressed(ProductInfo product);
}
static class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
NetworkImageView icon;
TextView price;
TextView description;
LinearLayout add_Cart;
TextView etQuantity;
public ProductViewHolder(final View itemView) {
super(itemView);
icon = (NetworkImageView) itemView.findViewById(R.id.productImage);
title = (TextView) itemView.findViewById(R.id.productName);
price = (TextView) itemView.findViewById(R.id.productPrice);
description = (TextView) itemView.findViewById(R.id.productDescription);
add_Cart = (LinearLayout) itemView.findViewById(R.id.add_cart);
etQuantity = (TextView) itemView.findViewById(R.id.quanity);
}
#Override
public void onClick(View v) {
}
}
/*
//FILTER THE SEARCH RESULTS
private static class CardFilter extends Filter {
private final ProductAdaptor adapter;
private final List<ProductInfo> originalList;
private final List<ProductInfo> filteredList;
private CardFilter(ProductAdaptor adapter, List<ProductInfo> originalList) {
super();
this.adapter = adapter;
this.originalList = new LinkedList<ProductInfo>(originalList);
this.filteredList = new ArrayList<ProductInfo>();
}
#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 ProductInfo productInfo : originalList) {
if (productInfo.getName().toLowerCase().trim().contains(filterPattern)) {
filteredList.add(productInfo);
}
}
}
results.values = filteredList;
results.count = filteredList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
adapter.setData((ArrayList<ProductInfo>) results.values);
adapter.notifyDataSetChanged();
}
}
*/
}
Product Fragment
public class ProductFragment extends Fragment implements SearchView.OnQueryTextListener,ProductAdaptor.ProductAdapterListener {
private static final String TAG = ProductFragment.class.getSimpleName();
private ProductAdaptor adapter;
private RecyclerView recyclerView;
private RequestQueue requestQueue;
private VolleySingleton volleySingleton;
// To store all the products
private List<ProductInfo> productsList=new ArrayList<>();
ProductAdaptor.ProductAdapterListener listener;
//Progress dialog
private ProgressDialog pDialog;
public static ProductFragment newInstance() {
return new ProductFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
listener=this;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout=inflater.inflate(R.layout.product_fragment,container,false);
recyclerView= (RecyclerView) layout.findViewById(R.id.productList);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
pDialog.setMessage("Fetching products...");
showpDialog();
volleySingleton=VolleySingleton.getInstance();
requestQueue=volleySingleton.getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, AppConfig.URL_PRODUCTS, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//hide the progress dialog
hidepDialog();
adapter=new ProductAdaptor(getActivity(),parseJSONOResponse(response),listener);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(MyApplication.getAppContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Wait 20 seconds and don't retry more than once
requestQueue.add(jsObjRequest);
recyclerView.setAdapter(adapter);
return layout;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
}
/*
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main,menu);
final MenuItem item = menu.findItem(R.id.search);
final SearchView searchView = (android.support.v7.widget.SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
}
*/
public boolean PerformSearch(String searchString){
//adapter.getFilter().filter(searchString);
return true;
}
public void setDataSet(List<ProductInfo> newDataSet){
adapter=new ProductAdaptor(MyApplication.getAppContext(),newDataSet,this);
recyclerView.swapAdapter(adapter, false);
//new way of filtering data
}
private List<ProductInfo> parseJSONOResponse(JSONObject response){
try {
JSONArray products = response.getJSONArray("products");
for (int i = 0; i < products.length(); i++) {
JSONObject product = (JSONObject) products
.get(i);
String id = product.getString("product_id");
String name = product.getString("name");
String description = product
.getString("description");
String image = AppConfig.URL_IMAGE_PRODUCTS + product.getString("image");
BigDecimal price = new BigDecimal(product
.getString("price"));
ProductInfo p = new ProductInfo(id, name, description,
image, price);
productsList.add(p);
}
return productsList;
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
return productsList;
}
#Override
public void onAddToCartPressed(ProductInfo product) {
CartHandler cartHandler=new CartHandler(MyApplication.getAppContext());
Log.d("Insert: ", "Inserting ..");
if (cartHandler.getProductsInCartCount()==0) {
cartHandler.addProductInCart(product);
Toast.makeText(MyApplication.getAppContext(),
product.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
}
else{
ProductInfo temp=cartHandler.getProductInCart(Integer.parseInt(product.getId()));
if (temp!=null){
cartHandler.updateProduct(product);
Toast.makeText(MyApplication.getAppContext(),
product.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
}else
{
cartHandler.addProductInCart(product);
Toast.makeText(MyApplication.getAppContext(),
product.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
}
}
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
final List<ProductInfo> filteredModelList = filter(productsList, query);
adapter.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
return true;
}
private List<ProductInfo> filter(List<ProductInfo> models, String query) {
query = query.toLowerCase();
final List<ProductInfo> filteredModelList = new ArrayList<>();
for (ProductInfo model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
}
This problem is caused because of overlapping fragments and i was starting the fragment like this
fragment=ProductFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.replace(R.id.productFragment,fragment )
.commit();
so making it simply
fragment=ProductFragment.newInstance();
solved my problem.
Thanks guys for help #MohammadAllam