Recyclerview Loadmore Not Working After Search - android

Past Few days,Facing this problem .RecyclerView onscroll to Loadmore and EditText Search works fine.But When i search data and Get Respective Result List and Then if I Scroll RecyclerView then Loadmore not working .
MainActivity
public class MainActivity extends FragmentActivity {
private RecyclerView mRecyclerView;
private LinearLayoutManager mLayoutManager;
private EditText editsearch;
private RecyclerAdapter mAdapter;
private int ival = 1;
private int loadLimit = 10;
ArrayList<Student> mDataSet = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Student> my_Dataset = getDataSet();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RecyclerAdapter(my_Dataset);
mRecyclerView.setAdapter(mAdapter);
editsearch = (EditText) findViewById(R.id.et_search);
// add the listener for EditText
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
mAdapter.filter(text);
}
});
mRecyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(
mLayoutManager) {
#Override
public void onLoadMore(int current_page) {
loadMoreData();
}
});
}
private ArrayList<Student> getDataSet()
{
for (int i = 1; i <=10; i++)
{
Student std=new Student();
std.setName("Root" + i);
mDataSet.add(std);
}
return mDataSet;
}
private void loadMoreData() {
loadLimit = ival +5;
for (int i = ival; i <= loadLimit; i++) {
Student st = new Student("Student " + i,false);
mDataSet.add(st);
ival++;
}
mAdapter.notifyDataSetChanged();
}
}
RecyclerAdapter
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<Student> mDataset;
private ArrayList<Student> mCleanCopyDataset;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public ViewHolder(View v) {
super(v);
mTextView = (TextView) v.findViewById(R.id.tv_recycler_item);
}
}
public RecyclerAdapter(ArrayList<Student> dataset) {
mDataset = dataset;
mCleanCopyDataset = mDataset;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycler_item, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTextView.setText(mDataset.get(position).getName());
}
#Override
public int getItemCount() {
return mDataset.size();
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
mDataset = new ArrayList<Student>();
if (charText.length() == 0) {
mDataset.addAll(mCleanCopyDataset);
} else {
for (Student item : mCleanCopyDataset) {
/* if (item.toLowerCase(Locale.getDefault()).contains(charText)) {
mDataset.add(item);
}*/
if(item.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
mDataset.add(item);
}
}
}
notifyDataSetChanged();
}
}
Here is EndlessRecyclerOnScrollListener
I am new in Android-studio .Does any guys meet this issue?Any help would be greatly appreciated.

The problem is that you're losing your reference where you want to add your items. Your current steps are:
Create list in mainactivity ArrayList<Student> mDataSet = new ArrayList();
Create adapter in mainactivty and pass my_Dataset (my_Dataset is mDataSet)
mAdapter = new RecyclerAdapter(my_Dataset);
Init adapter (you save the reference of mDataSet here)
mDataset = dataset; mCleanCopyDataset = mDataset;
Filter mDataset = new ArrayList<Student>(); here you lose your reference
Solution
Rename mDataset to mFilteredDataSet inside your adapter and change your constructor like that:
public RecyclerAdapter(ArrayList<Student> dataset) {
mFilteredDataset = new ArrayList<>(); // init your filtered dataset just one time and clear it on filtering
mFilteredDataset.addAll(dataset); // here you have your copy of the dataset
mCleanCopyDataset = dataset; // this is your reference of the complete dataset
}
Change mDataset = new ArrayList<Student>(); in your filter function
to
mFilteredDataset.clear()
Don't forget to call mAdapter.filter() at the end of your loadMoreData() because you add more data to your adapter but the new added data is not included in your filtered list.

Related

How to set Recyclview items on TextView in android

This is my main screen and i want when i click on Select All checkbox then check all checkboxes and set all checkbox's text on below textView(Just text). I successfully select all checkboxes but can't set text on textbox with separate commas, with the help of adapter i get the list of whole data but can't set it on main activity textview layout. plz suggest me any helpful way for done this. Thnakyou.
public class MainActivity extends AppCompatActivity {
CheckBox checkboxAll;
EditText editSearch;
RecyclerView recyclerView;
TextView dataList;
MainAdapter mainAdapter;
DataAdapter dataAdapter;
List<MainModel> list;
List<String> showList = new ArrayList<>();
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = this.getSharedPreferences("prefs", Context.MODE_PRIVATE);
recyclerView = findViewById(R.id.recyclerView);
checkboxAll = findViewById(R.id.checkboxAll);
dataList = findViewById(R.id.dataList);
editSearch = findViewById(R.id.editSearch);
editSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String editValue = String.valueOf(charSequence);
filter(editValue);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
checkboxAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (checkboxAll.isChecked()) {
mainAdapter.selectAll();
} else {
mainAdapter.unselectAll();
}
}
});
list = new ArrayList<>();
String[] cityname = getResources().getStringArray(R.array.cityList);
for (int i = 0; i < cityname.length; i++) {
MainModel mainModel = new MainModel(false, cityname[i]);
list.add(mainModel);
}
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
mainAdapter = new MainAdapter(MainActivity.this, list);
recyclerView.setAdapter(mainAdapter);
}
private void filter(String searchValue) {
ArrayList<MainModel> filteredList = new ArrayList<>();
for (MainModel item : list) {
if (item.getCityName().toLowerCase().contains(searchValue.toLowerCase())) {
filteredList.add(item);
}
}
mainAdapter.filterList(filteredList);
}
}
Adapter is:-
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
Context context;
List<MainModel> cityList = new ArrayList<>();
int checkValue = 0;
List<String> allValues;
SharedPreferences sharedPreferences;
public MainAdapter(Context context, List<MainModel> list) {
sharedPreferences = context.getSharedPreferences("prefs", Context.MODE_PRIVATE);
this.context = context;
this.cityList = list;
}
public void selectAll() {
checkValue = 1;
notifyDataSetChanged();
}
public void unselectAll() {
checkValue = 2;
notifyDataSetChanged();
}
#NonNull
#Override
public MainAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_items, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MainAdapter.ViewHolder holder, int position) {
holder.itemName.setText(cityList.get(position).getCityName());
if (checkValue == 1) {
holder.itemCheckBox.setChecked(true);
} else if (checkValue == 2) {
holder.itemCheckBox.setChecked(false);
}
}
#Override
public int getItemCount() {
return cityList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CheckBox itemCheckBox;
TextView itemName;
public ViewHolder(#NonNull View itemView) {
super(itemView);
itemCheckBox = itemView.findViewById(R.id.itemCheckBox);
itemName = itemView.findViewById(R.id.itemName);
}
}
public void filterList(ArrayList<MainModel> filteredList) {
cityList = filteredList;
notifyDataSetChanged();
}
}
You can acheive it using Interface, I am addding below code snipet
class MainActivity extends AppCompatActivity implements MainAdapter.MyRecyclerClickListener {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
MainAdapter mainAdapter = new MainAdapter(MainActivity.this, list);
recyclerView.setAdapter(mainAdapter);
mainAdapter.setClickListener(this);
}
#Override
public void onAllItemSelected(String text) {
// set on TextView
}
#Override
public void onAllItemUnSelected(String text) {
// set on TextView toi clear all previous value
}
}
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
private MyRecyclerClickListener myRecyclerClickListener;
public void selectAll() {
checkValue = 1;
StringBuilder stringBuilder = new StringBuilder();
for (MainModel cityModel : cityList) {
stringBuilder.append(cityModel.getCityName()).append(",");
}
myRecyclerClickListener.onAllItemSelected(stringBuilder.toString());
notifyDataSetChanged();
}
public void unselectAll() {
checkValue = 2;
myRecyclerClickListener.onAllItemUnSelected("");
notifyDataSetChanged();
}
public void setClickListener(MyRecyclerClickListener myRecyclerClickListener){
this.myRecyclerClickListener = myRecyclerClickListener
}
public interface MyRecyclerClickListener{
void onAllItemSelected(String text);
void onAllItemUnSelected(String text);
}
}
On the event when all check boxes are selected you update an observable field which is binded to your text view. You post the updated string to that observable and you should see them on the text view.

Get selected item position in Recyclerview

I am using Recyclerview. I added a menu with Recyclerview. I want to make a switch case in Recyclerview. So when I click on item 1, when I click on item 2, I click on step 3. When I click on my item .. I want to call a function. Currently I tried to read the position of the items with getAdapterPosition, but the output is always -1. For example, when I click on model, when I click on model2, I want to call a function.
Main2Activity
public class Main2Activity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
RecyclerView navRecyclerView;
LinearLayoutManager layoutManager;
ArrayList<NavigationDataModel> arrayList = new ArrayList<>();
NavigationAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
navigationView.setNavigationItemSelectedListener(this);
navRecyclerView = findViewById(R.id.navRecyclerView);
navRecyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
navRecyclerView.setLayoutManager(layoutManager);
DividerItemDecoration divider = new DividerItemDecoration(
navRecyclerView.getContext(),
DividerItemDecoration.VERTICAL
);
divider.setDrawable(ContextCompat.getDrawable(getBaseContext(), R.drawable.diveder_recycler));
navRecyclerView.addItemDecoration(divider);
initArray();
adapter = new NavigationAdapter(this, arrayList);
navRecyclerView.setAdapter(adapter);
private void initArray() {
NavigationDataModel model = new NavigationDataModel();
model.setIcon(R.mipmap.avatar);
model.setTitle("Hesabım");
arrayList.add(model);
NavigationDataModel model2 = new NavigationDataModel();
model2.setIcon(R.mipmap.sss3);
model2.setTitle("S.S.S");
arrayList.add(model2);
}
NavigationAdapter
public class NavigationAdapter extends RecyclerView.Adapter<NavigationAdapter.ViewHolder> {
Context context;
ArrayList<NavigationDataModel> arrayList = new ArrayList<>();
public NavigationAdapter(Context context, ArrayList<NavigationDataModel> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.navigationrecyclerview_adapter11, parent, false);
final ViewHolder holder = new ViewHolder(view);
holder.navTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = holder.getAdapterPosition();
System.out.println("asdasdadasd" + position);
}
});
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.navIcon.setImageResource(arrayList.get(position).getIcon());
holder.navIconNew.setImageResource(arrayList.get(position).getIcon());
holder.rootView.setBackgroundColor(arrayList.get(position).getColor());
holder.navTitle.setText(arrayList.get(position).getTitle());
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView navIcon, navIconNew;
TextView navTitle;
LinearLayout rootView;
public ViewHolder(View itemView) {
super(itemView);
rootView = itemView.findViewById(R.id.rootView);
navIcon = itemView.findViewById(R.id.navIcon);
navIconNew = itemView.findViewById(R.id.navIconNew);
navTitle = itemView.findViewById(R.id.navTitle);
Toast.makeText(context, String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.navIcon.setImageResource(arrayList.get(position).getIcon());
holder.navIconNew.setImageResource(arrayList.get(position).getIcon());
holder.rootView.setBackgroundColor(arrayList.get(position).getColor());
holder.navTitle.setText(arrayList.get(position).getTitle());
holder.navTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// use position herer
}
});
}

RecyclerView: wrong position in filtered List

I have a RecyclerView list of CardView items. I then use a simple filter method with a SearchView widget to filter the list. When I then click on a filtered CardView to launch a CardViewDetails Activity, the UI is showing the CardView from the original List and not the filtered List. For example, I have a list of twenty items in the original List. When I enter a search constraint the filtered List correctly shows three CardViews in the RecyclerView. When I click on the third CardView in the List, the UI returns the third CardView from the original List and not the third CardView from the filtered List. What am I missing here?
Adapter:
public class MyRecylerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<ListItem> mListItems, filteredList;
Context mContext;
private RecyclerItemClickListener recyclerItemClickListener;
private RecyclerView mRecyclerView;
/**********************************************************/
private String searchString = "";
/**********************************************************/
public MyRecylerAdapter(Context context, List<ListItem> listItems) {
this.mContext = context;
this.mListItems = listItems;
this.filteredList = new ArrayList<>();
this.filteredList.addAll(this.mListItems);
}
// RecyclerItemClickListener is the public interface file used to reach the MainActivity
public void setOnItemClickListener(RecyclerItemClickListener recyclerItemClickListener) {
this.recyclerItemClickListener = recyclerItemClickListener;
}
// Get the Item's position.
public ListItem getItem(int position) {
return filteredList.get(position);
}
#Override
public int getItemCount() {
if (filteredList.size() >0) {
return filteredList.size();
}
else {
return mListItems.size();
}
}
public void setFilter(List<ListItem> listItems, String searchString) {
// Note: the String is to get s.toString() from the Main Activity SearchView.
filteredList = new ArrayList<>();
filteredList.addAll(listItems);
this.searchString = searchString;
notifyDataSetChanged();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_contact_item, parent, false);
final ItemHolder itemHolder = new ItemHolder(view);
// Attach a Click listener to the items's (row) view.
// itemView is from the ItemHolder() below.
// onItemClick is the click method in MainActivity.
itemHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int adapterPos = itemHolder.getAdapterPosition(); // get the item position.
if (adapterPos != RecyclerView.NO_POSITION) {
if (recyclerItemClickListener != null) {
// pass the item to the Main Activity
// through the RecyclerItemClickListener file and its
// public interface.
recyclerItemClickListener.onItemClick(itemHolder.itemView,adapterPos);
}
}
}
});
return itemHolder;
}
private static class ItemHolder extends RecyclerView.ViewHolder {
private TextView cardBlankText2;
private ItemHolder(View itemView) {
super(itemView);
cardBlankText2 = (TextView) itemView.findViewById(R.id.cardBlankText2);
}
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
final ListItem listItem = filteredList.get(position);
final ItemHolder itemHolder = (ItemHolder) holder;
itemHolder.cardBlankText2.setText(listItem.getTodo());
}
Activity:
public class MainActivity extends AppCompatActivity implements
RecyclerItemClickListener {
private List<ListItem> allList = new ArrayList<>();
private RecyclerView mRecyclerView;
private SQLiteDB sqLiteDB;
private MyRecylerAdapter adapter;
private CardView cardview;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sqLiteDB = SQLiteDB.getInstance(this);
mRecyclerView = (RecyclerView)findViewById(R.id.list_recyclerview);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(layoutManager);
allList = sqLiteDB.getAllDBItems();
adapter = new MyRecylerAdapter(this, allList);
adapter.setOnItemClickListener(this);
mRecyclerView.setAdapter(adapter);
}
#Override
public void onItemClick(View view, int position) {
cardview = (CardView) view;
cardview.setEnabled(false);
// Create a new intent to send data from this MainActivity to the CardViewDetails
// Activity.
Intent intent = new Intent(this,CardViewDetails.class);
ListItem listItem = adapter.getItem(position);
// Add the item object to the Intent. The item object can be used because the
// model class implements Parcelable so it holds all of the getters
// that can be snagged in the next Activity with the
// getParcelableExtra method.
intent.putExtra("item",listItem);
intent.putExtra("position",position);
startActivity(intent);
finish();
}
// SearchView
final EditText mSearchEditText = (EditText) mSearchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
mSearchEditText.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) {
final ArrayList<ListItem> filteredModelList = filter(allList, s.toString());
if (!mSearchView.isIconified() && filteredModelList.size() == 0) {
Toast.makeText(MainActivity.this, "Not Found", Toast.LENGTH_SHORT).show();
// re-load the list so the Adapter refreshes the RecyclerView list View.
adapter.clear();
adapter.addAll(allList);
} else if (!mSearchView.isIconified() && filteredModelList.size() > 0) {
adapter.setFilter(filteredModelList, s.toString());
mRecyclerView.scrollToPosition(0);
}
}
}
});
private ArrayList<ListItem> filter(List<ListItem> models, String query) {
query = query.toLowerCase();
final ArrayList<ListItem> filteredModelList = new ArrayList<>();
for (ListItem listItem : models) {
final String text = listItem.getTodo().toLowerCase();
final String text2 = listItem.getNote1().toLowerCase();
final String text3 = listItem.getNote2().toLowerCase();
if (text.contains(query) || text2.contains(query) ||
text3.contains(query)) {
filteredModelList.add(listItem);
}
}
return filteredModelList;
}
RecyclerItemClickListener:
public interface RecyclerItemClickListener {
void onItemClick(View view, int position);
}
CardViewDetails:
public class CardViewDetails extends AppCompatActivity {
private int position;
private SQLiteDB helper;
List<ListItem> listItems;
private CardView cardview;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
final CardView cardView = (CardView) findViewById(R.id.dets);
// Create a variable for the skychill footer text.
final TextView skychilltext5;
// A db helper instance is needed for the removeItem() below
// when the user Longclicks the skycard for deletion.
helper = new SQLiteDB(this);
// Get the position of the clicked on R. list CardView from
// the MainActivity's intent bundle.
Bundle extras = getIntent().getExtras();
if (extras != null) {
// get the CardView item using the int position from the
// MainActivity's onItemClick() and the putExtra in the intent.
position = extras.getInt("position",0); // 0 is default value
}
cb2 = (TextView) findViewById(R.id.cb2);
helper = new SQLiteDB(this);
listItems = new ArrayList<>();
listItems = helper.getAllDBItems();
cb2.setText(listItems.get(position).getTodo());
...
}
After applying filter the sql DB (getAllDBItems ) data remain same. You are passing only position to CardViewDetail. And the sql data is of original list.
You should pass your ListItem as parcelable to CardViewDetails instead of position. your problem will be solved.

Recycler view does not refresh on filter - ArrayAdapter

I have an edit text and a recycler view, what I intend of the edit text is to use the input as a filter on the list. Here is my code:
Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_trains_view, container, false);
mountain.customwidgets.MontserratRegularAutoComplete editStationSearch =
(mountain.customwidgets.MontserratRegularAutoComplete)
view.findViewById(R.id.autoCompleteSource);
editStationSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
mAdapter.getFilter().filter(s);
}
});
RecyclerView mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
CsvReaderImpl csvReader = new CsvReaderImpl();
stationNameCodePojoArrayList = csvReader.ReadFromfile("data/stations.txt", getActivity());
mAdapter = new StationsRecyclerAdapter(getActivity(),stationNameCodePojoArrayList);
mRecyclerView.setAdapter(mAdapter);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL) {
#Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
// Do not draw the divider
}
});
return view;
}
Here is my adapter class:
public class StationsRecyclerAdapter extends RecyclerView.Adapter<StationsRecyclerAdapter.DataObjectHolder> implements Filterable {
private ArrayList<StationPojo> mDataset;
private StationTextFilter stationTextFilter;
private Context ctx;
public StationsRecyclerAdapter(Context ctx, ArrayList<StationPojo> myDataset) {
this.mDataset = (new ArrayList<>(myDataset));
this.ctx = ctx;
for (int i = 0; i < mDataset.size(); i++) {
System.out.println("mDatasset Original: " + Arrays.asList(mDataset.get(i).getStationName()));
}
}
#Override
public Filter getFilter() {
if (stationTextFilter == null) {
stationTextFilter = new StationTextFilter(this, mDataset);
}
return stationTextFilter;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View mView = LayoutInflater.from(ctx).inflate(R.layout.row_auto_complete, parent, false);
return new DataObjectHolder(mView);
}
public static class DataObjectHolder extends RecyclerView.ViewHolder {
TextView stationName;
TextView stationCode;
TextView stationElevation;
public DataObjectHolder(View itemView) {
super(itemView);
stationName = (TextView) itemView.findViewById(R.id.textStationName);
stationCode = (TextView) itemView.findViewById(R.id.textStationCode);
stationElevation = (TextView) itemView.findViewById(R.id.textStationElevation);
}
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.stationCode.setText(mDataset.get(position).getStationCode());
holder.stationElevation.setText(mDataset.get(position).getStationElevation());
holder.stationName.setText(mDataset.get(position).getStationName());
}
#Override
public int getItemCount() {
return mDataset.size();
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
And here is the Filter class:
public class StationTextFilter extends Filter {
private final StationsRecyclerAdapter adapter;
private List<StationPojo> mDataset;
private final List<StationPojo> filteredList;
public StationTextFilter(StationsRecyclerAdapter adapter, List<StationPojo> mDataset) {
super();
this.adapter = adapter;
this.mDataset = new ArrayList<>(mDataset);
this.filteredList = new ArrayList<>();
}
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
filteredList.clear();
final FilterResults results = new FilterResults();
if (charSequence.length() == 0) {
filteredList.addAll(mDataset);
} else {
final String filterPattern = charSequence.toString().toLowerCase().trim();
for (StationPojo item : mDataset) {
if (item.getStationName().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
System.out.println("Match found Word: " + filterPattern);
}
}
}
results.values = filteredList;
results.count = filteredList.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
mDataset.clear();
mDataset.addAll((ArrayList<StationPojo>) filterResults.values);
for (int i = 0; i < mDataset.size(); i++) {
System.out.println("mDatasset at filter: " + Arrays.asList(mDataset.get(i).getStationName()));
}
adapter.notifyDataSetChanged();
}
}
I am pretty sure that things work fine till the mDataset.addAll((ArrayList<StationPojo>) filterResults.values); as I can print the filtered results, somehow I am not able to know why notifyDatasetChanged does not work! Any headings?
Because your Adapter is referencing a different ArrayList and not the one in your StationTextFilter. See here
public StationTextFilter(StationsRecyclerAdapter adapter, List<StationPojo> mDataset) {
super();
this.adapter = adapter;
this.mDataset = new ArrayList<>(mDataset);
this.filteredList = new ArrayList<>();
}
The mDataset is the actual referenced ArrayList in your adapter, but here you are creating an entirely new ArrayList and thus does not get reflected in your notifyDataSetChanged.
One way to solve this is to not create a new ArrayList and use it as it is.
this.mDataset = mDataset;

RecyclerView dosent show any elements following is my code

Fragment_bookmovie2.java
public class Fragment_bookmovie2 extends android.support.v4.app.Fragment implements View.OnClickListener {
private static final String TAG ="Fragment_bookmovie2" ;
ArrayList<String> moviename= new ArrayList<>();
ArrayList<String> movieyear= new ArrayList<>();
ArrayList<String> moviebanner= new ArrayList<>();
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
Movie_listAdapter2 adapter ;
LinearLayout progress;
RelativeLayout ll;
public Fragment_bookmovie2() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Log.e(TAG,"reched on create");
// first step - retrieve object
Backendless.Persistence.of(Booking.class).find(new AsyncCallback<BackendlessCollection<Booking>>() {
#Override
public void handleResponse(BackendlessCollection<Booking> response) {
for(Booking booking : response.getData()) {
if(!moviename.contains(booking.getMovie().get(0).getMovie_Name())) {
moviename.add(booking.getMovie().get(0).getMovie_Name());
movieyear.add(booking.getMovie().get(0).getYear());
moviebanner.add("https://api.backendless.com/" + BackendSetting.APPLICATION_ID + "/" + BackendSetting.VERSION + "/files/mypics/" + booking.getMovie().get(0).getImage());
}
}
adapter.notifyDataSetChanged();
ll.removeView(progress);
}
#Override
public void handleFault(BackendlessFault fault) {
Toast.makeText(getActivity(), fault.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
moviename.add("haha");
movieyear.add("hello");
moviebanner.add("http://www.w3schools.com/css/trolltunga.jpg");
// Inflate the layout for this fragment
ll = (RelativeLayout) inflater.inflate(R.layout.fragment_bookmovie2, container, false);
progress = (LinearLayout) ll.findViewById(R.id.progress_bookingFrag);
recyclerView = (RecyclerView) ll.findViewById(R.id.recycle_movielist);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new Movie_listAdapter2(getActivity(),moviename,movieyear,moviebanner);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return ll;
}
#Override
public void onClick(View view) {
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
/*#Override
public void onButtonClickListnerProceed(Integer pos) {
Intent booking_screen_redirect = new Intent(getActivity(), BookingScreen2.class);
booking_screen_redirect.putExtra("movie_name",moviename.get(pos));
this.onPause();
startActivity(booking_screen_redirect);
getActivity().overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
}*/
}
Movie_listAdapter2.java
public class Movie_listAdapter2 extends RecyclerView.Adapter<Movie_listAdapter2.Movie_cards>{
final static String TAG="Movie_listAdapter2";
Context context_external;
ArrayList<String> moviename=new ArrayList<>();
ArrayList<String> movieyear=new ArrayList<>();
ArrayList<String> banner=new ArrayList<>();
public Movie_listAdapter2(Context context,ArrayList<String> resource, ArrayList<String> resource1, ArrayList<String> resource2) {
//set the context and the format of the layout inside the list item
//i.e R.layout.movie_list_adapter
//also the resource i.e the item names in an ArrayList
this.moviename = resource;
this.movieyear = resource1;
this.banner = resource2;
this.context_external=context;
Log.e(TAG,"size = "+movieyear.size()+" "+moviename.size());
}
public static class Movie_cards extends RecyclerView.ViewHolder {
CardView cv;
TextView movie_name;
TextView movie_year;
Button proceed;
ImageView movie_banner;
public Movie_cards(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.movie_list_card);
movie_name = (TextView)itemView.findViewById(R.id.tv_card_moviename);
movie_year = (TextView)itemView.findViewById(R.id.tv_card_movieyear);
movie_banner = (ImageView)itemView.findViewById(R.id.card_moviebanner);
proceed = (Button) itemView.findViewById(R.id.b_card_proceed);
}
}
#Override
public Movie_cards onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_card, parent, false);
Movie_cards pvh = new Movie_cards(v);
return pvh;
}
public void updateData(ArrayList<String> resource, ArrayList<String> resource1, ArrayList<String> resource2) {
this.moviename = resource;
this.movieyear = resource1;
this.banner = resource2;
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(final Movie_cards holder, final int position) {
holder.movie_name.setText(moviename.get(position));
holder.movie_year.setText(movieyear.get(position));
Picasso.with(context_external)
.load(banner.get(position))
.placeholder(R.drawable.placeholder)
.networkPolicy(NetworkPolicy.OFFLINE)
.error(R.drawable.placeholder)
.fit()
.into(holder.movie_banner, new Callback() {
#Override
public void onSuccess() {
//i.e image was loaded from cache
}
#Override
public void onError() {
//image was downloaded as it wasn't available in cache
Picasso.with(context_external)
.load(banner.get(position))
.placeholder(R.drawable.placeholder)
.error(R.drawable.warning)
.fit()
.into(holder.movie_banner);
}
});
holder.proceed.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent booking_screen_redirect = new Intent(context_external, BookingScreen2.class);
booking_screen_redirect.putExtra("movie_name",moviename.get(position));
context_external.startActivity(booking_screen_redirect);
//overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
}
});
}
#Override
public int getItemCount() {
return 0;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
the fragment displays empty and no items appear even though i have added the data to arraylists and passed to the adapter. please help . thanks in advance
Problem is in below code you are returning 0 that's why its not showing any item
#Override
public int getItemCount() {
return 0;
}
You should return your list's size here either moviename.size(); or movieyear.size()

Categories

Resources