How to set Recyclview items on TextView in android - 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.

Related

Recycler view that should change according to filter doesn't update correctly

I have an activity that shows a edit text where the user can input a filter and a recycler view that shows a list of cities that contain the information on that filter... However, I have an issue where the recycler view size updates to match the sql query result but does not change the information itself (i.e. if the sql query returns 4 cities the recycle view shows the first 4 cities in alphabetical order). What could be happening?
My adapter and my activity, respectively:
public class FilterCidadeAdapter extends RecyclerView.Adapter<FilterCidadeAdapter.ViewHolder> {
private int layoutResourceId;
private ArrayList<Cidade> data;
private Context context;
private RecyclerView list;
public ArrayList<Cidade> cidades = new ArrayList<>();
public FilterCidadeAdapter(Context context, int layoutResourceId, ArrayList<Cidade> data){
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#NonNull
#Override
public FilterCidadeAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
list = (RecyclerView) parent;
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_cidade_filtered, parent,false);
FilterCidadeAdapter.ViewHolder mh = new FilterCidadeAdapter.ViewHolder(v);
return mh;
}
#Override
public void onBindViewHolder(#NonNull FilterCidadeAdapter.ViewHolder holder, int position) {
final Cidade item = data.get(position);
final DataBaseHelper db = Sessao.getInstance().getDb(context);
holder.nome.setText(item.getCidade());
holder.btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, ListaProspeccoesActivity.class);
i.putExtra("selection", item.getCidade());
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return cidades.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView nome;
ImageButton btnSelect;
public ViewHolder(View itemView) {
super(itemView);
this.nome = itemView.findViewById(R.id.tv_Cidade);
this.btnSelect = itemView.findViewById(R.id.img_selecionar);
}
}
}
public class FilterProspeccaoActivity extends AppCompatActivity {
private EditText et_cidade_filtro;
private RecyclerView lista;
private LinearLayout linear;
private int cont = 0;
private FilterCidadeAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_fitrar_cidade);
super.onCreate(savedInstanceState);
try {
getSupportActionBar().hide();
} catch (Exception e) {
}
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(Color.parseColor("#009342"));
}
} catch (Exception e) {
}
et_cidade_filtro = findViewById(R.id.et_filtrar_cidade);
Cidade cidade = new Cidade(-1, "CIDADES", "");
ArrayList<Cidade> cidades = cidade.getAll(FilterProspeccaoActivity.this, null);
// cidades.add(0, cidade);
lista = findViewById(R.id.list_cidade);
adapter = new FilterCidadeAdapter(FilterProspeccaoActivity.this,R.layout.item_cidade_filtered,cidades);
try {
LinearLayoutManager lm = new LinearLayoutManager(this);
lista.setLayoutManager(lm);
lista.addItemDecoration(new DividerItemDecoration(lista.getContext(), lm.getOrientation()));
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
cont = 1;
handler.postDelayed(this, 0);
}
}, 500);
lista.setAdapter(adapter);
lista.getLayoutManager().scrollToPosition(Integer.MAX_VALUE / 2);
} catch (Exception e) {
apagarLista();
}
et_cidade_filtro.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) {
reload();
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void apagarLista() {
linear.setVisibility(View.GONE);
}
#Override
protected void onResume() {
super.onResume();
reload();
}
public void reload() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
DataBaseHelper db = Sessao.getInstance().getDb(FilterProspeccaoActivity.this);
Cidade cidade = new Cidade();
ArrayList<Cidade> cidades = cidade.findCidadesByNome(FilterProspeccaoActivity.this, et_cidade_filtro.getText().toString());
adapter.cidades.clear();
adapter.cidades.addAll(cidades);
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
}
});
}
});
thread.start();
}
}

How to get the Key when i clicked the item on recyclerview?

I'm creating an application with search and recycler view.
Here is my search_adapter:
public class search_adapter extends RecyclerView.Adapter<search_adapter.SearchViewHolder> {
private Context context;
private DatabaseReference mDatabase;
ArrayList<String> fullNameList;
ArrayList<String> dDateList;
private OnItemClickListener mListener;
Snapshot snapshot;
public search_adapter(Context context, ArrayList<String> fullNameList, ArrayList<String> dDateList) {
this.context = context;
this.fullNameList = fullNameList;
this.dDateList = dDateList;
}
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public static class SearchViewHolder extends RecyclerView.ViewHolder{
CardView clickCard;
TextView full_Name;
TextView death_Date;
public SearchViewHolder(View itemView, final OnItemClickListener listener) {
super(itemView);
full_Name = (TextView) itemView.findViewById(R.id.person_name);
death_Date = (TextView) itemView.findViewById(R.id.person_death);
clickCard = (CardView) itemView.findViewById(R.id.cardClick);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(listener !=null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
#Override
public search_adapter.SearchViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater mInflater = LayoutInflater.from(context);
view = mInflater.inflate(R.layout.recyclerview_adapter,parent,false);
return new search_adapter.SearchViewHolder(view, mListener);
}
public void onBindViewHolder(SearchViewHolder holder, final int position) {
holder.full_Name.setText(fullNameList.get(position));
holder.death_Date.setText(dDateList.get(position));
}
#Override
public int getItemCount() {
return fullNameList.size();
}
In this class, i create the view for the recycler view with onclick listener
I also include an interface so that i can pass the position of the clicked item.
Here is my search_activity class:
public class SearchActivity extends AppCompatActivity implements search_adapter.OnItemClickListener{
private RecyclerView mPerson;
private EditText mFindField;
public DatabaseReference mDatabase;
ArrayList<String> fullNameList;
ArrayList<String> dDateList;
private search_adapter searchAdapter;
int position = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
//Database Access//
mDatabase = FirebaseDatabase.getInstance().getReference();
//Recycler View//
mPerson = (RecyclerView)findViewById(R.id.person_list);
mPerson.setHasFixedSize(true);
mPerson.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
mPerson.setLayoutManager(new GridLayoutManager(this,3));
mFindField = (EditText) findViewById(R.id.search_field);
fullNameList = new ArrayList<>();
dDateList = new ArrayList<>();
mFindField.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) {
}
#Override
public void afterTextChanged(Editable editable) {
if (!editable.toString().isEmpty()){
setAdapter(editable.toString());
} else {
fullNameList.clear();
dDateList.clear();
mPerson.removeAllViews();
}
}
});
}
private void setAdapter(final String searchedString) {
mDatabase.child("person").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
fullNameList.clear();
dDateList.clear();
mPerson.removeAllViews();
int counter = 0;
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
String full_name = snapshot.child("fullName").getValue(String.class);
String dDate = snapshot.child("dDate").getValue(String.class);
if (full_name.toLowerCase().contains(searchedString.toLowerCase())){
fullNameList.add(full_name);
dDateList.add(dDate);
counter++;
} else if (dDate.toLowerCase().contains(searchedString.toLowerCase())){
fullNameList.add(full_name);
dDateList.add(dDate);
counter++;
}
if (counter == 15)
break;
}
searchAdapter = new search_adapter(SearchActivity.this, fullNameList, dDateList);
mPerson.setAdapter(searchAdapter);
searchAdapter.setOnItemClickListener(SearchActivity.this);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//new search//
#Override
public void onItemClick(int position) {
}
this is where the passed position will go,
but my problem is, I don't know how to get the key of that passed position, I try using getRef like the others did but it's not working.
My goal is for the user to clicked a data on the recycler view, open a new intent, and view all of the details of that certain clicked data.
Please help.
You have a list of names and a list of dates in your adapter, in the same way you can generate and add a list of keys, and in the viewholder onBind method you can bind the key to a field in your viewholder. And instead of sending position in your on click listener you can send your key.

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 Loadmore Not Working After Search

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.

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