RxAndroid network calls makes the app lagging on back navigation - android-recyclerview

my android application keeps lagging on back navigation after i implemented the network calls.For network calls I'm using rxandroid/retrofit. I've tried to fix it using both single & observable. Both makes the app lagging the same way.This is my code while using observable. Lagging occurs while loading data to recyclerviews. So I have added the adapter class also.
#Override
public void onResume() {
super.onResume();
getMenuByShopAndCategoryId(categoryRequest.getId(), Utility.getShop(getActivity()));
}
private void getMenuByShopAndCategoryId(int categoryId, int shopId){
Repository.getInstance()
.getMenuByShopAndCategoryId(categoryId,shopId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Response<MenuResponse>>() {
#Override
public void onSubscribe(Disposable d) {
disposable.add(d);
}
#Override
public void onNext(Response<MenuResponse> menuResponse) {
//other calculations
}
}
#Override
public void onError(Throwable e) {
//error handling
}
#Override
public void onComplete() {
}
});
}
#Override
public void onDestroy() {
disposable.dispose();
super.onDestroy();
}
public Observable<Response<MenuResponse>> getMenuByShopAndCategoryId(#NonNull int category_id, #NonNull int shop_id) {
return apiService.getMenuByShopAndCategoryId(category_id,shop_id);
}
public class MenuItemsAdapter extends RecyclerView.Adapter<MenuItemsAdapter.ViewHolder> {
private Context context;
private ArrayList<MenuResponse.MenuRequest> menuItemArrayList;
private ListRowMenuItemsBinding binding;
private MenuItemsAdapterHandler menuItemsAdapterHandler;
public MenuItemsAdapter(Context context, ArrayList<MenuResponse.MenuRequest> menuItemArrayList) {
this.context = context;
this.menuItemArrayList = menuItemArrayList;
}
#NonNull
#Override
public MenuItemsAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.list_row_menu_items, viewGroup, false);
menuItemsAdapterHandler = new MenuItemsAdapterHandler(context);
binding.setHandler(menuItemsAdapterHandler);
configureLabels();
return new ViewHolder(binding);
}
#Override
public void onBindViewHolder(#NonNull MenuItemsAdapter.ViewHolder viewHolder, int i) {
viewHolder.binding.lblItemName.setText(menuItemArrayList.get(i).getMenuName());
viewHolder.binding.lblPrice.setText("MVR " + String.format("%.2f", Double.valueOf(menuItemArrayList.get(i).getSubTotal())));
if (menuItemArrayList.get(i).getAvailability().equals(Constants.AVAILABLE)){
binding.lblAvailability.set(context, HuqTypogrphyStyle.CAPS_BUTTON_GREEN);
viewHolder.binding.lblAvailability.setText("AVAILABLE");
} else {
binding.lblAvailability.set(context, HuqTypogrphyStyle.CAPS_BUTTON_RED);
viewHolder.binding.lblAvailability.setText("NOT AVAILABLE");
}
viewHolder.binding.setMenuItem(menuItemArrayList.get(i));
viewHolder.binding.executePendingBindings();
}
#Override
public int getItemCount() {
return menuItemArrayList.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
public class ViewHolder extends RecyclerView.ViewHolder {
ListRowMenuItemsBinding binding;
public ViewHolder(#NonNull ListRowMenuItemsBinding listRowMenuItemsBinding) {
super(listRowMenuItemsBinding.getRoot());
this.binding = listRowMenuItemsBinding;
}
}
private void configureLabels() {
binding.lblItemName.set(context, HuqTypogrphyStyle.H2_HEADING);
binding.lblPrice.set(context, HuqTypogrphyStyle.BODY_GRAY);
binding.lblAvailability.set(context, HuqTypogrphyStyle.BODY_GRAY);
}
}

Try moving the api call from on Resume to onCreate.

Related

Access Activity from ViewManager in React Native

How are you? I have a some issues in my project.
Here is my code.
public class ViewManager extends ViewGroupManager<FrameLayout> {
public static final String REACT_CLASS = "RNNativeFlip";
public final int COMMAND_CREATE = 1;
private ReactApplicationContext context;
public ViewManager(ReactApplicationContext context) {
this.context = context;
}
#NonNull
#Override
public String getName() {
return REACT_CLASS;
}
#Override
protected FrameLayout createViewInstance(ThemedReactContext reactContext) {
return new FrameLayout(reactContext);
}
#Nullable
#Override
public Map<String, Integer> getCommandsMap() {
return MapBuilder.of("create", COMMAND_CREATE);
}
#Override
public void receiveCommand(
#NonNull FrameLayout root,
int commandId,
#Nullable ReadableArray args
) {
super.receiveCommand(root, commandId, args);
int reactNativeViewId = args.getInt(0);
int commandIdInt = commandId;
switch (commandIdInt) {
case COMMAND_CREATE:
createFragment(root, reactNativeViewId);
break;
default: {}
}
}
public void createFragment(FrameLayout root, int reactNativeViewId) {
final MainFragment myFragment = new MainFragment();
FragmentActivity activity;
activity = (FragmentActivity) this.context.getCurrentActivity();
activity.getSupportFragmentManager()
.beginTransaction()
.replace(reactNativeViewId, myFragment, String.valueOf(reactNativeViewId))
.commit();
}
}
No longer possible to access Activity from getCurrentActivity()
I know one method to use ReactContextBaseJavaModule but I don't know how to use this in ViewManger.
Please help me. Thank you

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());
}

paging library not showing anything in recyclerview

i'm trying to load bunch of list from room database, with paging library, but somehow that i don't really understand, the list never shown up
i add a repository class between dao and viewmodel, not sure if its the problem but, i configure Paged.list and pagedlistbuilder in there
i've also try to put some breakpoint in pagedListAdapter, but it never called
DAO
#Query("SELECT * FROM DictIndonesia")
public abstract DataSource.Factory<Integer, DictIndonesia> getAllPaged();
REPOSITORY
public class DictRepository {
PagedList.Config pagedListConfid;
.....
public DictRepository(Application application) {
db = DictIndoDatabase.getINSTANCE(application);
indDao = db.dictIdDao();
.....
pagedListConfid = (new PagedList.Config.Builder()
.setEnablePlaceholders(true)
.setPrefetchDistance(10)
.setPageSize(20).build());
}
......
public LiveData<PagedList<DictIndonesia>> getAllWordPaged() {
return new LivePagedListBuilder<>(
indDao.getAllPaged(), pagedListConfid).build();
}
viewmodel
public LiveData<PagedList<DictIndonesia>> getAllWordPaged() {
return dictRepository.getAllWordPaged();
}
ADAPTER
public class WordIndAdapterPaged extends PagedListAdapter<DictIndonesia,WordIndAdapterPaged.WordHolder> {
public WordIndAdapterPaged() {
super(diffcallBack);
}
#NonNull
#Override
public WordHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler, parent, false);
return new WordHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull WordHolder holder, int position) {
holder.bindTo(getItem(position));
}
private static final DiffUtil.ItemCallback<DictIndonesia> diffcallBack = new DiffUtil.ItemCallback<DictIndonesia>() {
#Override
public boolean areItemsTheSame(#NonNull DictIndonesia oldItem, #NonNull DictIndonesia newItem) {
return oldItem.getIdIndo() == newItem.getIdIndo();
}
#Override
public boolean areContentsTheSame(DictIndonesia oldItem, #NonNull DictIndonesia newItem) {
return oldItem == newItem;
}
};
public class WordHolder extends RecyclerView.ViewHolder {
...............
WordHolder(View view) {
super(view);
...............
}
void bindTo(DictIndonesia dictIndonesia) {
word.setText(Html.fromHtml(dictIndonesia.getWord()));
meaning.setText(Html.fromHtml(dictIndonesia.getMeaning()));
}
}
Fragment
public class Fdashboard extends Fragment {
#BindView(R.id.rv_global)
RecyclerView rvGlobal;
private Unbinder unbinder;
WordIndAdapterPaged wordIndAdapterPaged;
private WordViewModel wordViewModel;
public Fdashboard() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_fdashboard, container, false);
unbinder = ButterKnife.bind(this, v);
wordViewModel = ViewModelProviders.of(getActivity()).get(WordViewModel.class);
wordIndAdapterPaged = new WordIndAdapterPaged();
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
rvGlobal.setLayoutManager(layoutManager);
rvGlobal.setAdapter(wordIndAdapterPaged);
wordViewModel.getAllWordPaged().observe(this, dictIndonesias -> {
wordIndAdapterPaged.submitList(dictIndonesias); //i think the problem maybe around here
});
return v;
}

Restore scroll position

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);