Restore scroll position - android-recyclerview

I have a simple fragment which retrieve data from Firebase database.
I use firebase recycler view to display retrieving data. And after scrolling or screen rotation I can't force recycler view (or linear layout manager) restore scroll position.
I found here some answers but they don't work.
My code is:
public class NewsListFragment extends ParentNewsFragment {
static int color_naval, color_black;
private boolean mProcessLikes = false;
private DatabaseReference mDatabaseLikes;
private DatabaseReference mDatabaseViews;
private FirebaseAuth mAuth;
private int position = 0;
public static NewsListFragment getInstance() {
return new NewsListFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDatabaseReference = FirebaseDatabase.getInstance().getReference()
.child("App_news");
mDatabaseLikes = FirebaseDatabase.getInstance().getReference().child("news_likes");
mDatabaseViews = FirebaseDatabase.getInstance().getReference().child("news_views");
mAuth = FirebaseAuth.getInstance();
mQuery = mDatabaseReference.orderByChild("pos").startAt("100");
color_naval = getResources().getColor(R.color.colorPrimary);
color_black = getResources().getColor(R.color.colorBlack);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.rv_choose, container, false);
rv = (RecyclerView) rootView.findViewById(R.id.rv_choose);
lm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(lm);
rv.setHasFixedSize(true);
return rootView;
}
#Override
public void onPause() {
super.onPause();
position = lm.findFirstVisibleItemPosition();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("position", position);
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if(savedInstanceState != null) {
position = savedInstanceState.getInt("position");
}
}
#Override
public void onResume() {
super.onResume();
if (position != 0) {
lm.scrollToPosition(position);
showToast(position+"");
}
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<NewsList, NewsListViewHolder> adapter =
new FirebaseRecyclerAdapter<NewsList, NewsListViewHolder>(
NewsList.class,
R.layout.frag_newslist_card_view,
NewsListViewHolder.class,
mQuery
) {
#Override
protected void populateViewHolder(NewsListViewHolder viewHolder, final NewsList model, int position) {
final String post_key = getRef(position).getKey();
viewHolder.setDate(model.getDate()+",");
viewHolder.setTime(model.getTime());
viewHolder.setTitle(model.getTitle());
viewHolder.setImage(getContext(), model.getImage());
viewHolder.setEye(model.getCode());
viewHolder.setThumb(post_key);
viewHolder.thumb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProcessLikes = true;
mDatabaseLikes.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLikes){
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){
mDatabaseLikes.child(post_key).child(mAuth.getCurrentUser().getUid())
.removeValue();
mProcessLikes = false;
}
else {
mDatabaseLikes.child(post_key).child(mAuth.getCurrentUser().getUid())
.setValue("like");
mProcessLikes = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabaseViews.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseViews.child(post_key).child(mAuth.getCurrentUser().getUid())
.setValue("view");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mChooserListener.chooseNews(model.getCode());
}
});
}
};
rv.setAdapter(adapter);
}
public static class NewsListViewHolder extends RecyclerView.ViewHolder {
//some text here
}
}
method showToast in the end shows real number of position but recyclerview starts from the beginning.
any ideas?

Make sure you are not reloading data from the server or wherever you are retrieving data.
Add is not null check in your fragment's onCreateView or activity's onCreate like:
if(savedInstanceState != null){
...
}else{
loadData();
}

Replace your linear layout manager with something similar to the following. I have used this implementation many times when using RecyclerView in fragments. Let me know how it goes
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
yourItem.setLayoutManager(mLayoutManager);

Related

Cannot retrieve data from database (FIREBASE) to recycler view

I can't retrieve my data from database into recycler view. but when i add the data, the data successfully store into database. I cannot identified which part having a problem. Hoping someone can help me to solve this problem.
This is my adapter code.
public class UsersRecyclerAdapter extends RecyclerView.Adapter<UsersRecyclerAdapter.ViewHolder> {
Context context;
ArrayList<UsersItem> usersItemArrayList;
DatabaseReference databaseReference;
public UsersRecyclerAdapter(Context context, ArrayList<UsersItem> usersItemArrayList) {
this.context = context;
this.usersItemArrayList = usersItemArrayList;
databaseReference = FirebaseDatabase.getInstance().getReference();
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.activity_user_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
UsersItem USERS = usersItemArrayList.get(position);
holder.textBloodPressure.setText(USERS.getBloodPressure());
holder.textOxygenRate.setText(USERS.getOxygenRate());
holder.textPulseRate.setText(USERS.getPulseRate());
holder.textMedication.setText(USERS.getMedication());
holder.textTodayActivity.setText(USERS.getTodayActivity());
holder.textWaterIntake.setText(USERS.getWaterIntake());
holder.buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewDialogUpdate viewDialogUpdate = new ViewDialogUpdate();
viewDialogUpdate.showDialog(context, USERS.getUserID(), USERS.getBloodPressure(), USERS.getOxygenRate(), USERS.getPulseRate(), USERS.getMedication(), USERS.getTodayActivity(), USERS.getWaterIntake());
}
});
holder.buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewDialogConfirmDelete viewDialogConfirmDelete = new ViewDialogConfirmDelete();
viewDialogConfirmDelete.showDialog(context, USERS.getUserID());
}
});
}
#Override
public int getItemCount() {
return usersItemArrayList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView textBloodPressure, textOxygenRate, textPulseRate, textMedication, textTodayActivity, textWaterIntake;
Button buttonDelete;
Button buttonUpdate;
public ViewHolder(#NonNull View itemView) {
super(itemView);
textBloodPressure = itemView.findViewById(R.id.textBloodPressure);
textOxygenRate = itemView.findViewById(R.id.textOxygenRate);
textPulseRate = itemView.findViewById(R.id.textPulseRate);
textMedication = itemView.findViewById(R.id.textMedication);
textTodayActivity = itemView.findViewById(R.id.textTodayActivity);
textWaterIntake = itemView.findViewById(R.id.textWaterIntake);
buttonDelete = itemView.findViewById(R.id.buttonDelete);
buttonUpdate = itemView.findViewById(R.id.buttonUpdate);
}
}
enter image description here
This is add health details code. where data from this page will will store in "USERS" table and retrieve into recycler view.
public class AddJournal extends AppCompatActivity {
DatabaseReference databaseReference;
RecyclerView recyclerView;
ArrayList<UsersItem> usersItemArrayList;
UsersRecyclerAdapter adapter;
Button buttonAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_journal);
//start sini
FirebaseDatabase.getInstance().setPersistenceEnabled(true); // work offline
Objects.requireNonNull(getSupportActionBar()).hide();
databaseReference = FirebaseDatabase.getInstance().getReference();
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
usersItemArrayList = new ArrayList<>();
buttonAdd = findViewById(R.id.buttonAdd);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewDialogAdd viewDialogAdd = new ViewDialogAdd();
viewDialogAdd.showDialog(AddJournal.this);
}
});
readData();
}
private void readData() {
databaseReference.child("USERS").orderByChild("bloodPressure").addValueEventListener(new ValueEventListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
usersItemArrayList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
UsersItem USERS = dataSnapshot.getValue(UsersItem.class);
usersItemArrayList.add(USERS);
}
adapter = new UsersRecyclerAdapter(AddJournal.this, usersItemArrayList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
public class ViewDialogAdd {
public void showDialog(Context context) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.activity_alert_dialog_add_new_user);
EditText textBloodPressure = dialog.findViewById(R.id.textBloodPressure);
EditText textOxygenRate = dialog.findViewById(R.id.textOxygenRate);
EditText textPulseRate = dialog.findViewById(R.id.textPulseRate);
EditText textMedication = dialog.findViewById(R.id.textMedication );
EditText textTodayActivity = dialog.findViewById(R.id.textTodayActivity);
EditText textWaterIntake = dialog.findViewById(R.id.textWaterIntake);
Button buttonAdd = dialog.findViewById(R.id.buttonAdd);
Button buttonCancel = dialog.findViewById(R.id.buttonCancel);
buttonAdd.setText("ADD");
buttonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String id = "USERS" + new Date().getTime();
String bloodPressure = textBloodPressure.getText().toString();
String oxygenRate = textOxygenRate.getText().toString();
String pulseRate = textPulseRate.getText().toString();
String medication = textMedication.getText().toString();
String todayActivity = textTodayActivity.getText().toString();
String waterIntake = textWaterIntake.getText().toString();
if (bloodPressure.isEmpty() || oxygenRate.isEmpty() || pulseRate.isEmpty() || medication.isEmpty() || todayActivity.isEmpty() || waterIntake.isEmpty()) {
Toast.makeText(context, "Please Enter All data...", Toast.LENGTH_SHORT).show();
} else {
databaseReference.child("USERS").child(id).setValue(new UsersItem(id, bloodPressure, oxygenRate, pulseRate, medication, todayActivity, waterIntake));
Toast.makeText(context, "DONE!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
});
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
}
}

Recycler view lost after fragment replacement

I have a single activity which replaces a fragment containing a recycler view with a fragment containing details of the selected viewholder item. When the back button is pressed the fragment containing the recycler view is restored but the recycler view items are no longer displayed. However, views are restored upon device rotation. All model data is stored in a SQLite database and the adapter list is updated on resume of its fragment .
CrimeListFragment.Java
public class CrimeListFragment extends Fragment {
private Callbacks callbacks;
public interface Callbacks {
public void onItemSelected(UUID id);
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
callbacks = (Callbacks) context;
}
#Override
public void onDetach() {
super.onDetach();
callbacks = null;
}
private RecyclerView crimeListRecycler;
private CrimeListAdapter adapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
crimeListRecycler = view.findViewById(R.id.crime_list);
crimeListRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_crime_list, menu);
MenuItem showSubtitle = menu.findItem(R.id.show_subtitle);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.new_crime:
Crime crime = new Crime();
CrimeLab.get(getActivity()).addCrime(crime);
/*Intent intent = CrimeActivity.createIntent(getActivity(), crime.getId());
startActivity(intent);*/
callbacks.onItemSelected(crime.getId());
return true;
default:
return onOptionsItemSelected(item);
}
}
private void updateUI() {
List<Crime> crimes = CrimeLab.get(getActivity()).getCrimes();
if (adapter == null) {
adapter = new CrimeListAdapter(crimes);
crimeListRecycler.setAdapter(adapter);
} else {
adapter.setCrimesList(crimes);
adapter.notifyDataSetChanged();
}
}
public class CrimeListAdapter extends RecyclerView.Adapter<CrimeListAdapter.CrimeHolder> {
private List<Crime> crimeList;
public CrimeListAdapter(List<Crime> crimes) {
crimeList = crimes;
}
#NonNull
#Override
public CrimeHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(getActivity()).inflate(R.layout.list_item_crime, parent, false);
return new CrimeHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CrimeHolder holder, int position) {
Crime crime = crimeList.get(position);
holder.bind(crime);
}
#Override
public int getItemCount() {
return crimeList.size();
}
public void setCrimesList(List<Crime> crimes) {
crimeList = crimes;
}
public class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Crime crime;
private TextView crimeTitleTextView;
private TextView crimeDateTextView;
public CrimeHolder(#NonNull View itemView) {
super(itemView);
crimeTitleTextView = itemView.findViewById(R.id.crime_title);
crimeDateTextView = itemView.findViewById(R.id.crime_date);
itemView.setOnClickListener(this);
}
public void bind(Crime crime) {
this.crime = crime;
crimeTitleTextView.setText(crime.getTitle());
crimeDateTextView.setText(crime.getDate().toString());
}
#Override
public void onClick(View v) {
callbacks.onItemSelected(crime.getId());
/*Intent intent = CrimeActivity.createIntent(getActivity(), crime.getId());
startActivity(intent);*/
}
}
}
}
MasterActivity
public class MasterActivity extends AppCompatActivity implements CrimeListFragment.Callbacks {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = new CrimeListFragment();
fm.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
}
}
#Override
public void onItemSelected(UUID id) {
Fragment fragment = CrimeFragment.newInstance(id);
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
}
}
Please share your code. Something to check when you replace/add your fragment on top of recyclerview fragment.

How to implement an Action on Item Click in Order to show the result in CardView of RecyclerView

I am very new to Android programming. I can't find a solution for my current problem which I've been trying to solve for days.
I want to click on item of populated Array List and get the position i.e. the searched word result in Cardview (neither ItemClickListener nor OnSuggestionListener did work here. Here is my code of MainActivity and I would be very thankful if somebody could help me out:
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
MaterialSearchBar materialSearchBar;
List<String> suggestList = new ArrayList<>();
Database database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//init View
recyclerView = (RecyclerView) findViewById(R.id.recycler_search);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
materialSearchBar = (MaterialSearchBar) findViewById(R.id.search_bar);
database = new Database(this);
materialSearchBar.setHint("Search");
materialSearchBar.setCardViewElevation(10);
loadSuggestList();
materialSearchBar.addTextChangeListener (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) {
List<String> suggest = new ArrayList<>();
for (String search : suggestList) {
if (search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
suggest.add(search);
}
materialSearchBar.setLastSuggestions(suggest);
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setOnSearchActionListener (new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
if (!enabled)
adapter = new SearchAdapter(getBaseContext(), database.getLughats());
recyclerView.setAdapter(adapter);
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString());
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
adapter = new SearchAdapter(this, database.getLughats());
recyclerView.setAdapter(adapter);
}
private void startSearch(String text) {
adapter = new SearchAdapter(this, database.getLughatByWort(text));
recyclerView.setAdapter(adapter);
}
private void loadSuggestList() {
suggestList = database.getWorts();
materialSearchBar.setLastSuggestions(suggestList);
}
}```
Let me know if I should post here also my AdapterCode for the ViewHolder.
Thank you for your help in advance!
Here ist my AdapterCode:
class SearchViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
RecyclerItemClick itemClickListener;
public TextView wort, praeteritum, partizip2, artikelGrammatik, uebersetzung1, uebersetzung2;
public ImageButton button1, button2;
public SearchViewHolder(#NonNull View itemView) {
super(itemView);
wort = (TextView)itemView.findViewById(R.id.wort);
praeteritum = (TextView)itemView.findViewById(R.id.praeteritum);
partizip2 = (TextView)itemView.findViewById(R.id.partizip2);
artikelGrammatik = (TextView)itemView.findViewById(R.id.artikelGrammatik);
uebersetzung1 = (TextView)itemView.findViewById(R.id.uebersetzung1);
uebersetzung2 = (TextView)itemView.findViewById(R.id.uebersetzung2);
button1 = (ImageButton)itemView.findViewById(R.id.button_id_1);
button2 = (ImageButton) itemView.findViewById(R.id.button_id_2);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
this.itemClickListener.onItemClickListener(v, getLayoutPosition());
}
public void setItemClickListener(RecyclerItemClick ic) {
this.itemClickListener = ic;
}
}
public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder> {
private Context context;
private List<Lughat> lughats;
public SearchAdapter(Context context, List<Lughat> lughats) {
this.context = context;
this.lughats = lughats;
}
#NonNull
#Override
public SearchViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
final View itemView = inflater.inflate(R.layout.layout_item, parent, false);
return new SearchViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final SearchViewHolder holder, final int position) {
holder.wort.setText(lughats.get(position).getWort());
holder.praeteritum.setText(lughats.get(position).getPraeteritum());
holder.partizip2.setText(lughats.get(position).getPartizip2());
holder.artikelGrammatik.setText(lughats.get(position).getArtikelGrammatik());
holder.uebersetzung1.setText(lughats.get(position).getUebersetzung1());
holder.uebersetzung2.setText(lughats.get(position).getUebersetzung2());
CharSequence praet;
praet = holder.praeteritum.getText();
if (praet.length() == 0) {
holder.praeteritum.setVisibility(View.GONE);
holder.button1.setVisibility(View.GONE);
} else {
holder.praeteritum.setVisibility(View.VISIBLE);
holder.button1.setVisibility(View.VISIBLE);
}
CharSequence part2;
part2 = holder.partizip2.getText();
if (part2.length() == 0) {
holder.partizip2.setVisibility(View.GONE);
} else {
holder.partizip2.setVisibility(View.VISIBLE);
}
CharSequence artGr;
artGr = holder.artikelGrammatik.getText();
if (artGr.length() == 0) {
holder.artikelGrammatik.setVisibility(View.GONE);
holder.button2.setVisibility(View.GONE);
} else {
holder.artikelGrammatik.setVisibility(View.VISIBLE);
holder.button2.setVisibility(View.VISIBLE);
}
CharSequence ueb2;
ueb2 = holder.uebersetzung2.getText();
if (ueb2.length() == 0) {
holder.uebersetzung2.setVisibility(View.GONE);
} else {
holder.uebersetzung2.setVisibility(View.VISIBLE);
}
holder.button1.setOnClickListener(new ToastMaker(context.getApplicationContext()));
holder.button2.setOnClickListener(new ToastMaker(context.getApplicationContext()));
holder.setItemClickListener(new RecyclerItemClick() {
#Override
public void onItemClickListener(View v, int position) {
Toast.makeText(context, "Begriff", Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return lughats.size();
}
}
If I do it also with OnClickListener it does not work too, it does not call the method startSearch.
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence text = materialSearchBar.getText();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
startSearch(text.toString());
}

how to confirm selected items in recyclerview item list and make selected on layout

i am preparing textview seat numbers list by using recyclerview grid layout manager. i can select the multiple items in the recyclerview list by red color. now i want to keep this seat item selected as red color when on cliking on confirm seat button. when i reopen the recyclerview list it should show the seat selected red color and other seat item in normal color.
confirm seat button clickconfrim seat button click
SelectionAdapter
'''
public class SelectionAdapter extends RecyclerView.Adapter<SelectionAdapter.MygridViewHolder> {
private Context applicationContext;
private ArrayList<Seatnos> list, selected;
public SelectionAdapter(Context applicationContext, ArrayList<Seatnos> list) {
this.applicationContext = applicationContext;
this.list = list;
this.selected = new ArrayList<>();
}
#NonNull
#Override
public MygridViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());
View view=layoutInflater.inflate(R.layout.list_layout_selection,parent,false);
return new MygridViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MygridViewHolder holder, final int position) {
final Seatnos seatnos = list.get(position);
holder.textView.setText(String.valueOf(position));
holder.textView.setText(seatnos.getTextno());
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selected.contains(seatnos)) {
selected.remove(seatnos);
unhighlightView(holder);
} else {
selected.add(seatnos);
highlightView(holder);
}
}
});
if (selected.contains(seatnos))
highlightView(holder);
else
unhighlightView(holder);
}
private void highlightView(MygridViewHolder holder) {
holder.itemView.setBackgroundColor(ContextCompat.getColor(applicationContext, R.color.red));
}
private void unhighlightView(MygridViewHolder holder) {
holder.itemView.setBackgroundColor(ContextCompat.getColor(applicationContext, android.R.color.transparent));
}
#Override
public int getItemCount() {
return list.size();
}
class MygridViewHolder extends RecyclerView.ViewHolder {
TextView textView;
MygridViewHolder(#NonNull View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.textViewsA);
}
}
public void addAll(ArrayList<Seatnos> list) {
clearAll(false);
this.list = list;
notifyDataSetChanged();
}
public void clearAll(boolean isNotify) {
list.clear();
selected.clear();
if (isNotify) notifyDataSetChanged();
}
public void clearSelected() {
selected.clear();
notifyDataSetChanged();
}
public void selectAll() {
selected.clear();
selected.addAll(list);
notifyDataSetChanged();
}
public ArrayList<Seatnos> getSelected() {
return selected;
}
}
'''
SeatSelectionactivity.java
'''
public class SeatSelectionActivity extends AppCompatActivity {
RecyclerView recyclerView;
Activity activity = SeatSelectionActivity.this;
Button btnGetSelected,btnreset;
FirebaseDatabase database;
DatabaseReference ref;
SelectionAdapter selectionAdapter;
ArrayList<Seatnos> list;
Update update;
ChildEventListener mChildListner;
ValueEventListener mValueEventListner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seat_selection);
btnGetSelected = (Button) findViewById(R.id.btconfirm);
recyclerView=(RecyclerView) findViewById(R.id.viewseat);
list = new ArrayList<>();
String uid = getIntent().getStringExtra(UpdateAdapter.USER_KEY);
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("updates").child(uid);
selectionAdapter=new SelectionAdapter(this, list);
RecyclerView.LayoutManager layoutManager=new GridLayoutManager(this,4);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
mValueEventListner = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Update update =dataSnapshot.getValue(Update.class);
update.setUid(dataSnapshot.getKey());
int seat= Integer.parseInt(update.getSeat());
ArrayList<String> array = new ArrayList<String>(seat);
for(long i=0; i<seat; i++) {
array.add(String.valueOf(i));
Seatnos seatnos = new Seatnos();
seatnos.setTextno(""+(i+1));
if(i==0){
seatnos.setChecked(true);
}
list.add(seatnos);
}
recyclerView.setAdapter(selectionAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
databaseReference.addValueEventListener(mValueEventListner);
}
public void reset(View view) {
}
public void bookconfirm(View view) {
if (selectionAdapter.getSelected().size() > 0) {
//ArrayList<Integer> mlist = new ArrayList<>();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < selectionAdapter.getSelected().size(); i++) {
stringBuilder.append(selectionAdapter.getSelected().get(i).getTextno());
stringBuilder.append("\n");
}
Toast.makeText(activity, String.format("Selected %d items", selectionAdapter.getSelected().size()), Toast.LENGTH_SHORT).show();
showToast(stringBuilder.toString().trim());
} else {
showToast("No Selection");
}
};
public void selectAll(View v) {
selectionAdapter.selectAll();
}
public void deselectAll(View v) {
selectionAdapter.clearSelected();
}
public void doAction(View v) {
Toast.makeText(activity, String.format("Selected %d items", selectionAdapter.getSelected().size()), Toast.LENGTH_SHORT).show();
}
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
'''
model class
'''
public class Seatnos implements Serializable {
String textno;
String sid;
private boolean isChecked = false;
public Seatnos() {
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean checked) {
isChecked = checked;
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public Seatnos(String textno) {
this.textno = textno;
}
public String getTextno() {
return textno;
}
public void setTextno(String textno) {
this.textno = textno;
}
}
'''
You would use shared preferences to save the state of the selected item:
Do this in onBindViewHolder:
#Override
public void onBindViewHolder(#NonNull final MygridViewHolder holder, final int position) {
final Seatnos seatnos = list.get(position);
holder.textView.setText(String.valueOf(position));
holder.textView.setText(seatnos.getTextno());
//read from preferences
SharedPreferences pref = getSharedPreferences("item", MODE_PRIVATE);
String state = pref.getString(String.valueOf(position)+"state", "default");
if(state.equals("selected")){
//selected
highlightView(holder);
}else{
//not selected
unhighlightView(holder);
}
//on click
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selected.contains(seatnos)) {
selected.remove(seatnos);
unhighlightView(holder);
//save state
SharedPreferences.Editor editor = getSharedPreferences("item", MODE_PRIVATE).edit();
editor.putString(String.valueOf(position)+"state", "not_selected");
editor.apply();
} else {
selected.add(seatnos);
highlightView(holder);
//save state
SharedPreferences.Editor editor = getSharedPreferences("item", MODE_PRIVATE).edit();
editor.putString(String.valueOf(position)+"state", "selected");
editor.apply();
}
}
});
......................
......................
......................
}
UPDATE:
Yes you should use the context passed to your adapter to access the shared prederences:
This:
getSharedPreferences("item", MODE_PRIVATE);
Becomes:
applicationContext.getSharedPreferences("item", MODE_PRIVATE);
This:
getSharedPreferences("item", MODE_PRIVATE).edit();
Becomes:
applicationContext.getSharedPreferences("item", MODE_PRIVATE).edit();

android only show first viewpager inside recyclerview

i have a viewpager with FragmentStatePagerAdapter inside recyclerview
and its show only the first row in recyclerview
please help me
viewpager adapter:
public class CustomPagerAdapter extends FragmentStatePagerAdapter {
private static int NUM_ITEMS = 3;
public CustomPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
Log.e("fragmentManager",fragmentManager.toString());
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
Fragment currentFragment;
switch (position) {
case 0:
currentFragment=new FirstFragment();
break;
case 1:
currentFragment=new SecondFragment();
break;
case 2:
currentFragment=new ThirdFragment();
break;
default:
currentFragment=new FirstFragment();
break;
}
return currentFragment;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
recyclerview adapter:
public class JobAdapter extends RecyclerView.Adapter<JobAdapter.JobHolder> {
private Context context;
private List<String> mJobList = new ArrayList<>();
public JobAdapter(List<String> mJobList,Context context) {
this.mJobList = mJobList;
this.context=context;
}
#Override
public JobHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.find_job_line_content, parent, false);
return new JobHolder(view);
}
#Override
public void onBindViewHolder(final JobHolder holder, int position) {
configurePagerHolder(holder, position);
}
private void configurePagerHolder(JobHolder holder, int position) {
//Job job= mJobList.get(position);
CustomPagerAdapter adapter = new CustomPagerAdapter(((MainActivity)context).getSupportFragmentManager());
holder.viewPager.setAdapter(adapter);
adapter.notifyDataSetChanged();
holder.viewPager.setCurrentItem(1);
Log.e("configurePagerHolder",position+"");
}
public int getItemCount() {``
return mJobList.size();
}
public class JobHolder extends RecyclerView.ViewHolder{
ViewPager viewPager;
public JobHolder(View itemView) {
super(itemView);
viewPager=(ViewPager)itemView.findViewById(R.id.slidesPager);
}
}
main:
public class MainActivity extends AppCompatActivity {
RecyclerView mRecyclerView;
JobAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView)findViewById(R.id.find_jobs_recyclerview);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL,false));
mRecyclerView.setHasFixedSize(true);
List<String> list=new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
adapter = new JobAdapter(list,this);
mRecyclerView.setAdapter(adapter);
}
}
Very late answer but it might help some people...
Try using ViewPager2 ( an improved version of ViewPager) : https://developer.android.com/training/animation/screen-slide-2
In my case it solved the problem.