Reputation: 31
I am new in android development. My application have timer like 8sec , 7sec ,6sec and so on... So i have put time in model class and using handler i am updating that model class value on every sec secondly i have to update my recycler view.. Here my code (till now i have tried this below)
public void startTimerUpdate() {
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<ProductDetail>>() {
}.getType();
arrayList = gson.fromJson(ReadSharePrefrence(getActivity(), ALLPRODUCT), type);
Log.d("UpdateTime", getTimeInCounter(arrayList.get(0).getCounter()));
recyclerAdapter.notifyDataSetChanged();
handler.postDelayed(runnable, 1000);
}
};
handler.postDelayed(runnable, 1000);
}
but at a every second i am getting 'UpdateTime' perfectly in my log but recyclerView is not updating.
Guide me
yes , i had bind arraylist to recyclerview adpater here is code.
recyclerAdapter = new HomeRecyclerAdapter(getActivity(), arrayList, getActivity().getSupportFragmentManager());
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(getActivity()));
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(recyclerAdapter);
Upvotes: 0
Views: 2892
Reputation: 11921
If you know the position of the item which you want to update it's data you can try to use notifyItemChanged(int position)
method of adapter instead of recyclerAdapter.notifyDataSetChanged();
Here's the link: https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#notifyItemChanged(int,%20java.lang.Object)
Notify any registered observers that the item at position has changed. Equivalent to calling notifyItemChanged(position, null);.
This is an item change event, not a structural change event. It indicates that any reflection of the data at position is out of date and should be updated. The item at position retains the same identity.
Edit:
If you have multiple items updated on timer you can take
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<ProductDetail>>() {
}.getType();
arrayList = gson.fromJson(ReadSharePrefrence(getActivity(), ALLPRODUCT), type);
this code block out of handler and just handle your operation getCounter() in handler. With this approach, you avoid doing read/write in handler in every 1 second.
Upvotes: 1
Reputation: 2576
try this in handler:
arrayList.clear();
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<ProductDetail>>() {
}.getType();
arrayList.addAll(gson.fromJson(ReadSharePrefrence(getActivity(), ALLPRODUCT), type));
recyclerAdapter.notifyDataSetChanged();
Upvotes: 1