FirebaseRecyclerAdapter paggination on recyclerView - android

I wanted paggination with RecyclerView using firebase real data base not firestone. With FirebaseRecyclerAdapter which is provided my google.So RecyclerView is reverse order so because of that top is at the bottom.Need to load 5 item each time when user reach top of the list .
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private TextView username;
private TextView post;
private AdapterComment adapterComment;
private ArrayList<Comment> commentArrayList;
public static String GetAllFeed = "";
private LinearLayoutManager mLayoutManager, mDetailLayoutManager;
private Dialog dialog, detailDialog;
// [START define_database_reference]
private DatabaseReference mDatabase;
// [END define_database_reference]
RecyclerView recyclerView;
private DatabaseReference mPostReference;
//Solution for descending list on refresh
private int pastVisibleItems;
private int visibleItemCount;
private int totalItemCount,visibleLast;
AdapterImage adapterImage;
ArrayList arrayList;
ValueEventListener postListener, notifyListener;
private FirebaseRecyclerAdapter<Post, PostViewHolder> mAdapter;
float screenX;
int posSet = 0, showNotification = 0,mLastKey=0;
Query postsQuery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference();
GetAllFeed = FeedHelper.NODE_FEED;
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mRecyclerView = findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
username = findViewById(R.id.username);
post = findViewById(R.id.textView);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(MainActivity.this);
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
mRecyclerView.setLayoutManager(mLayoutManager);
((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().build();
StrictMode.setThreadPolicy(policy);
} catch (Exception e) {
e.printStackTrace();
}
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, PostActivity.class);
startActivity(intent);
}
});
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().build();
StrictMode.setThreadPolicy(policy);
} catch (Exception e) {
e.printStackTrace();
}
if (AppClass.isInternetConnected()) {
//use to set the user name with two different text and size
SpannableStringBuilder builder = new SpannableStringBuilder();
String s = Utility.getSharedPreferenceString(MainActivity.this, Constants.FirstName) + " " +
Utility.getSharedPreferenceString(MainActivity.this, Constants.LastName);
String s1 = " " + getString(R.string.log_in);
SpannableString span1 = new SpannableString(s);
span1.setSpan(new RelativeSizeSpan(1f), 0, s.length(), 0); // set size
span1.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.textColor)), 0, s.length(), 0);// set color
builder.append(span1);
SpannableString span2 = new SpannableString(s1);
span2.setSpan(new RelativeSizeSpan(.6f), 0, s1.length(), 0); // set size
span2.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.textColor1)), 0, s1.length(), 0);// set color
builder.append(span2);
username.setText(builder, TextView.BufferType.SPANNABLE);
AppClass.getAppinstance().showLoadingDialog(MainActivity.this);
getData();
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
Log.d("newState", "" + newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisibleItems = mLayoutManager.findFirstVisibleItemPosition();
if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {
visibleLast = mLayoutManager.findLastVisibleItemPosition();
if (AppClass.isInternetConnected()) {
getData();
} else {
AppClass.getAppinstance().showToast(getString(R.string.internet));
}
}
}
});
} else {
AppClass.getAppinstance().showToast(getString(R.string.internet));
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mAdapter != null) {
mAdapter.stopListening();
}
}
#Override
public void onStart() {
super.onStart();
if (mAdapter != null) {
mAdapter.startListening();
}
}
#Override
public void onStop() {
super.onStop();
if (mAdapter != null) {
mAdapter.stopListening();
}
}
public void getData() {
if (mLastKey==0) {
postsQuery = FirebaseDatabase.getInstance().getReference().child(GetAllFeed).orderByKey().
limitToLast(6);
}else {
postsQuery = FirebaseDatabase.getInstance().getReference().child(GetAllFeed).orderByKey().
endAt(mLastKey).limitToLast(7);
}
FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<Post>()
.setQuery(postsQuery, Post.class)
.build();
mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(options) {
#Override
public PostViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
return new PostViewHolder(inflater.inflate(R.layout.feed_item, viewGroup, false));
}
#Override
protected void onBindViewHolder(final PostViewHolder viewHolder, final int position, final Post model) {
final DatabaseReference postRef = getRef(position);
viewHolder.titleView.setText(model.lastName);
}
};
mRecyclerView.setAdapter(mAdapter);
notifyListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mLastKey= Integer.parseInt(dataSnapshot.getKey());
if (showNotification == 0) {
showNotification = (int) dataSnapshot.getChildrenCount();
} else if (dataSnapshot.getChildrenCount() > showNotification) {
showNotification = (int) dataSnapshot.getChildrenCount();
Snackbar.make(mRecyclerView, "New post available to see post click on Top.", Snackbar.LENGTH_LONG)
.setAction("Top", new View.OnClickListener() {
#Override
public void onClick(View v) {
mLayoutManager.scrollToPositionWithOffset(mAdapter.getItemCount() - 1, 0);
}
})
.show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
// [START_EXCLUDE]
Toast.makeText(MainActivity.this, "Failed to load post.",
Toast.LENGTH_SHORT).show();
// [END_EXCLUDE]
}
};
postsQuery.addValueEventListener(notifyListener);
AppClass.getAppinstance().dismissLoadingDialog();
}
}

Related

The items added multiple times into the RecyclerView with pagining

I am working on android app with java. and now I have to do messaging activities. I use RecyclerView to display the messages items. Also my messages Api is work with pagining, every time I send the last id and the server return the previous 10 messages.(Page size is 10). For filling the RecyclerView I use an Adapter but my problem is, that the item is added multiple times into the RecyclerView.
I will put my activity code and the adapter code
My Activity:
public class ConversationsActivity extends RootActivity implements ConversationsAdapter.ConversationOnClickHandler {
RetrofitBuilder rB = new RetrofitBuilder();
IApi service = rB.retrofit.create(IApi.class);
String authorization;
RecyclerView rv;
ConversationsAdapter adapter;
ProgressBar progressBar;
LinearLayoutManager layoutManager;
//declare it as global var for future cancel refresh
private SwipeRefreshLayout swipeLayout;
boolean wasSwiped;
// initialise loading state
boolean mIsLoading, mIsLastPage = false;
// amount of items you want to load per page
final int pageSize = 10;
int mCurrentPage =0;
int lastId;
boolean f;
int p =1;
private AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.7F);
int chatId, to;
String senderType, name, to_type;
TextView no_data;
Button btnActionBar11, send;
TextView tvActionBar;
EditText message;
Context context;
ArrayList<Conversation.Data> conversationArrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversations);
context = this;
adapter = new ConversationsAdapter(this,context);
Intent intent = getIntent();
chatId = intent.getIntExtra("chatId",0);
Intent intent1 = getIntent();
senderType = intent1.getStringExtra("senderType");
Intent intent2 = getIntent();
name = intent2.getStringExtra("name");
Intent intent3 = getIntent();
to = intent3.getIntExtra("from",0);
Intent intent4 = getIntent();
to_type = intent4.getStringExtra("from_type");
buttonClick.setDuration(500);
authorization = checkAuthorization();
setContentView(R.layout.activity_conversations);
progressBar = (ProgressBar) findViewById(R.id.progress);
tvActionBar = (TextView) findViewById(R.id.tvActionBar);
tvActionBar.setText(name);
layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
layoutManager.setReverseLayout(true);
adapter.setHasStableIds(true);
// layoutManager.setStackFromEnd(true);
rv = (RecyclerView) findViewById(R.id.ConversationList);
no_data = (TextView) findViewById(R.id.no_data);
message = (EditText) findViewById(R.id.message);
send = (Button) findViewById(R.id.send);
rv.setLayoutManager(layoutManager);
btnActionBar11 = (Button) findViewById(R.id.btnActionBar11);
btnActionBar11.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), ChatActivity.class);
startActivity(intent);
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(message.getText().length() > 0){
sendMessage();
}
}
});
getConversation();
rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
// number of visible items
int visibleItemCount = ((LinearLayoutManager)recyclerView.getLayoutManager()).getChildCount();
// number of items in layout
int totalItemCount = ((LinearLayoutManager)recyclerView.getLayoutManager()).getItemCount();
// the position of first visible item
int firstVisibleItemPosition = ((LinearLayoutManager)recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
boolean isNotLoadingAndNotLastPage = !mIsLoading && !mIsLastPage;
// flag if number of visible items is at the last
boolean isAtLastItem = firstVisibleItemPosition + visibleItemCount >= totalItemCount;
// validate non negative values
boolean isValidFirstItem = firstVisibleItemPosition >= 0;
// validate total items are more than possible visible items
boolean totalIsMoreThanVisible = totalItemCount >= pageSize;
// flag to know whether to load more
boolean shouldLoadMore = isValidFirstItem && isAtLastItem && totalIsMoreThanVisible && isNotLoadingAndNotLastPage;
if (shouldLoadMore) loadMoreItems(false);
}
});
Intent intent11 = getIntent();
wasSwiped = intent11.getBooleanExtra("wasSwiped",false);
//where you initialize your views:
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
wasSwiped = true;
//your method to refresh content
Intent intent = new Intent(getApplicationContext(), ConversationsActivity.class)
.putExtra("chatId", chatId)
.putExtra("senderType", senderType)
.putExtra("name",name)
.putExtra("from", to)
.putExtra("from_type", to_type)
.putExtra("wasSwiped", wasSwiped);
startActivity(intent);
}
});
if(wasSwiped){
//don't forget to cancel refresh when work is done
if(swipeLayout.isRefreshing()) {
swipeLayout.setRefreshing(false);
}
}
}
#Override
public void onClickConversation(Conversation.Data conversation) {
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(getApplicationContext(), ChatActivity.class);
startActivity(intent);
}
public void sendMessage(){
Call<Message> call = service.sendMessage(authorization, to, to_type, message.getText().toString());
call.enqueue(new Callback<Message>() {
#Override
public void onResponse(Call<Message> call, Response<Message> response) {
if(response.isSuccessful()){
if(response.body()!= null)
if(response.body().getData() != null);
message.setText("");
getConversation();
//
// adapter.notifyDataSetChanged();
} else {
if(response.body()!= null)
if(response.body().getMessage() != null)
Toast.makeText(getApplicationContext(),"error: " + response.body().getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<Message> call, Throwable t) {
Toast.makeText(getApplicationContext(),"error: " + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
public void getConversation(){
Call<Conversation> call = service.getConversation(authorization,chatId,"LANDLORD");
call.enqueue(new Callback<Conversation>() {
#Override
public void onResponse(Call<Conversation> call, Response<Conversation> response) {
if(conversationArrayList != null)
if(!conversationArrayList.isEmpty())
conversationArrayList.clear();
if(response.isSuccessful()){
if(response.body()!= null)
if(response.body().getData() != null)
if(response.body().getData().size() > 0){
if (!conversationArrayList.isEmpty())
conversationArrayList.clear(); //The list for update recycle view
adapter.notifyDataSetChanged();
for(int i =0; i < response.body().getData().size(); i++){
conversationArrayList.add(response.body().getData().get(i));
if( i == ( response.body().getData().size() -1 ))
lastId = conversationArrayList.get(conversationArrayList.size() - 1).getId();
}
progressBar.setVisibility(View.GONE);
if (conversationArrayList.isEmpty()) {
rv.setVisibility(View.GONE);
no_data.setVisibility(View.VISIBLE);
}
else {
rv.setVisibility(View.VISIBLE);
no_data.setVisibility(View.GONE);
progressBar.setVisibility(View.GONE);
configureRecyclerView(conversationArrayList);
}
} else {
progressBar.setVisibility(View.GONE);
no_data.setVisibility(View.VISIBLE);
rv.setVisibility(View.GONE);
}
} else {
Toast.makeText(getApplicationContext(),"error: " + response.body().getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<Conversation> call, Throwable t) {
Toast.makeText(getApplicationContext(),"error: " + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
private void configureRecyclerView(ArrayList chat) {
rv = (RecyclerView) findViewById(R.id.ConversationList);
rv.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
rv.setLayoutManager(linearLayoutManager);
adapter = new ConversationsAdapter(this,context);
adapter.setConversationData(chat);
adapter.notifyDataSetChanged();
rv.setAdapter(adapter);
}
private void loadMoreItems(boolean isFirstPage) {
mIsLoading = true;
f = isFirstPage;
p = p +1;
Call<Conversation> call = service.getConversationPagenation(authorization,chatId,senderType, lastId);
call.enqueue(new Callback<Conversation>() {
#Override
public void onResponse(Call<Conversation> call, Response<Conversation> response) {
if(response.isSuccessful()){
if(response.body() != null)
if(response.body().getData()!= null) {
// conversationArrayList.clear();
for(int i =0; i < response.body().getData().size(); i++){
conversationArrayList.add(response.body().getData().get(i));
if( i == ( response.body().getData().size() -1 ))
lastId = conversationArrayList.get(conversationArrayList.size() - 1).getId();
}
progressBar.setVisibility(View.GONE);
if(conversationArrayList == null){
rv.setVisibility(View.GONE);
no_data.setVisibility(View.VISIBLE);
return;
}
else if (!f) {
if (!conversationArrayList.isEmpty())
adapter.notifyDataSetChanged();
adapter.addAll(conversationArrayList);
// conversationArrayList.clear(); //The list for update recycle view
}
else {
rv.setVisibility(View.VISIBLE);
no_data.setVisibility(View.GONE);
configureRecyclerView(conversationArrayList);
}
if(conversationArrayList.size() > 0)
lastId = conversationArrayList.get(conversationArrayList.size() - 1).getId();
mIsLoading = false;
mIsLastPage = mCurrentPage == lastId;
mCurrentPage = lastId;
}
}
}
#Override
public void onFailure(Call<Conversation> call, Throwable t) {
Log.e("SomeActivity", t.getMessage());
}
});
}
public String checkAuthorization(){
SharedPreferences settings = getSharedPreferences("log",0);
return settings.getString("Authorization", null);
}
}
My Adapter:
public class ConversationsAdapter extends
RecyclerView.Adapter<ConversationsAdapter.ConversationsAdapterViewHolder> {
private Context context;
private ArrayList<Conversation.Data> mConversation;
private ConversationsAdapter.ConversationOnClickHandler mConversationOnClickHandler;
private static SharedPreferences pref;
public ConversationsAdapter(ConversationsAdapter.ConversationOnClickHandler conversationOnClickHandler, Context _context) {
mConversationOnClickHandler = conversationOnClickHandler;
pref = _context.getSharedPreferences("log", Context.MODE_PRIVATE);
}
public void setConversationData(ArrayList<Conversation.Data> conversation) {
mConversation = conversation;
notifyDataSetChanged();
}
public void addAll(ArrayList<Conversation.Data> newList) {
int lastIndex = mConversation.size() - 1;
mConversation.addAll(newList);
notifyItemRangeInserted(lastIndex, newList.size());
}
#Override
public ConversationsAdapter.ConversationsAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View contactView = inflater.inflate(R.layout.row_msg, parent, false);
// Return a new holder instance
ConversationsAdapter.ConversationsAdapterViewHolder viewHolder = new ConversationsAdapter.ConversationsAdapterViewHolder(contactView);
return viewHolder;
}
#Override
public void onBindViewHolder(ConversationsAdapter.ConversationsAdapterViewHolder viewHolder, int position) {
Conversation.Data conversation = mConversation.get(position);
TextView tv1 = viewHolder.tv1;
TextView tv2 = viewHolder.tv2;
// SharedPreferences preferences = context.getSharedPreferences("log", Context.MODE_PRIVATE);
String agentId = pref.getString("agentId", "");
String from_type = conversation.getFromType();
int from = conversation.getFrom();
if((agentId.equals(String.valueOf(from))) && from_type.equals("AGENT")){
tv2.setVisibility(View.GONE);
tv1.setVisibility(View.VISIBLE);
tv1.setText(conversation.getBody());
}
else {
tv2.setVisibility(View.VISIBLE);
tv1.setVisibility(View.GONE);
tv2.setText(conversation.getBody());
}
}
// Returns the total count of items in the list
#Override
public int getItemCount() {
if(mConversation == null) {
return 0;
}
return mConversation.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public void setHasStableIds(boolean hasStableIds) {
super.setHasStableIds(hasStableIds);
}
public class ConversationsAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public final TextView tv1;
public final TextView tv2;
public ConversationsAdapterViewHolder(View view) {
super(view);
tv1 = (TextView) view.findViewById(R.id.tvMsgR);
tv2 = (TextView) view.findViewById(R.id.tvMsgL);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int position = getAdapterPosition();
Conversation.Data selectedNotifiction = mConversation.get(position);
mConversationOnClickHandler.onClickConversation(selectedNotifiction);
}
}
public interface ConversationOnClickHandler {
void onClickConversation(Conversation.Data conversation);
}
public long myTimeInMillis(String givenDateString ){
// String givenDateString = "Tue Apr 23 16:08:28 GMT+05:30 2013";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long timeInMilliseconds = 0;
try {
Date mDate = sdf.parse(givenDateString);
timeInMilliseconds = mDate.getTime();
// System.out.println("Date in milli :: " + timeInMilliseconds);
} catch (ParseException e) {
e.printStackTrace();
}
return timeInMilliseconds;
}
}
any help or advice?
And thankyou
in your addAll() function on ConversationsAdapter class
int lastIndex = mConversation.size() - 1;
mConversation.clear();
mConversation.addAll(newList);
notifyItemRangeInserted(lastIndex, newList.size());
this should do the trick

Original List in adapter not updating once filtered something

When I scroll my list it follows the pagination as expected.
But when I open my search view and type something and reset the editText and try to load next list it does not update in adapter unless I swipe my fragments or hide the searchview.
In both the cases i set my edittext to null so it gets updated on that call thats where i think but need your help.
I did lots of search yesterday but unfortunately found nothing. Hope I'll find help here. Thanks
MainActivity
public class MainActivity extends AppCompatActivity {
#BindView(R.id.vp_horizontal_ntb)
ViewPager viewPager;
#BindView(R.id.ntb_horizontal)
TabLayout topNavigationBar;
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.appbar)
AppBarLayout mAppBar;
#BindView(R.id.searchIcon)
ImageView search;
#BindView(R.id.searchBoxLinOut)
LinearLayout searchBox;
#BindView(R.id.deleteSearchText)
ImageView deleteText;
#BindView(R.id.searchtext)
EditText et_search;
#BindView(R.id.imageView)
ImageView backButton;
String target = "nothing";
Context context;
Received_Fragment rf = new Received_Fragment();
Given_Fragment gf = new Given_Fragment();
InputMethodManager imm;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//StatusBarCompat.setStatusBarColor(this,
getResources().getColor(R.color.md_grey_300));
setContentView(R.layout.layouot_all_reviews);
ButterKnife.bind(this);
context = this;
viewPager.setOffscreenPageLimit(2);
viewPager.setCurrentItem(0);
viewPager.postDelayed(new Runnable() {
#Override
public void run() {
setPosition();
}
}, 100);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow(); // in Activity's onCreate() for instance
w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
imm = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
setUpTabs();
handleClicks();
}
private void handleClicks() {
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int
positionOffsetPixels) {
et_search.setText(null);
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
et_search.setText(null);
}
});
backButton.setOnClickListener(v -> {
onBackPressed();
});
search.setOnClickListener(v -> {
searchBox.bringToFront();
if (searchBox.getVisibility() == View.VISIBLE) {
hideSearch(searchBox);
} else {
showSearch(searchBox);
}
});
deleteText.setOnClickListener(v -> {
if (et_search.getText().length() > 1) {
et_search.setText(null);
} else hideSearch(searchBox);
});
et_search.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) {
if (s.toString().trim().length() == 0) {
rf.update();
gf.update();
}
}
#Override
public void afterTextChanged(Editable s) {
if (viewPager.getCurrentItem() == 0) {
rf.filter(s.toString());
} else
gf.filter(s.toString());
}
});
}
private void showSearch(View view) {
TranslateAnimation animate = new TranslateAnimation(
0, // fromXDelta
0, // toXDelta
-view.getHeight() * 2, // fromYDelta
0); // toYDelta
animate.setDuration(500);
animate.setFillAfter(false);
view.startAnimation(animate);
view.requestFocus();
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
view.setVisibility(View.VISIBLE);
backButton.setEnabled(false);
}
private void hideSearch(View view) {
TranslateAnimation animate = new TranslateAnimation(
0, // fromXDelta
0, // toXDelta
0, // fromYDelta
-view.getHeight() * 3); // toYDelta
animate.setDuration(500);
animate.setFillAfter(false);
view.startAnimation(animate);
view.setVisibility(View.INVISIBLE);
backButton.setEnabled(true);
et_search.setText(null);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
private void setPosition() {
target = getIntent().getStringExtra("WHERE");
if (target.equals("given")) {
switchFragment(1);
} else {
viewPager.setCurrentItem(0);
}
}
public void switchFragment(int target) {
viewPager.setCurrentItem(target);
}
private void setUpTabs() {
viewPager.setAdapter(new
FragmentPagerAdapter(getSupportFragmentManager()) {
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return rrf;
case 1:
return rgf;
default:
return new Default_Fragment();
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Received";
case 1:
return "Given";
default:
return "Error";
}
}
});
topNavigationBar.setupWithViewPager(viewPager);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
}
Received_Fragment
public class Received_Fragment extends Fragment {
#BindView(R.id.recyclerView)
RecyclerView recyclerView;
#BindView(R.id.shimmer_view_container)
ShimmerFrameLayout shimmerLayout;
#BindView(R.id.msg)
TextView message;
//Initialization of Classes
SessionManager session;
ApiClient apiClient;
List<ClassName> List = new ArrayList<>();
Boolean isScrolling = false;
boolean isDataLoaded = false;
int currentItem, totalItem, scrollOutItem;
//Properties to access
Context context;
String email;
String userId;
String access_token;
RecievedAdapter adapter;
BottomSheetBehavior sheetBehavior;
LinearLayoutManager linearLayoutManager;
private boolean isLastPage = false;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recycler_view_layout,
container, false);
ButterKnife.bind(this, view);
context = getContext();
session = new SessionManager(context);
HashMap<String, String> user = session.getUserDetails();
email = user.get(SessionManager.KEY_EMAIL);
access_token = user.get(SessionManager.KEY_ACCESS_TOKEN);
userId = user.get(SessionManager.KEY_USER_ID);
apiClient = ((Common)
getActivity().getApplication()).getClient().create(ApiClient.class);
shimmerLayout.startShimmerAnimation();
linearLayoutManager = new LinearLayoutManager(getContext());
adapter = new RecievedAdapter(List, context,
recyclerView);
adapter.setHasStableIds(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(feedsAdapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int
newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
currentItem = linearLayoutManager.getChildCount();
totalItem = linearLayoutManager.getItemCount();
scrollOutItem = linearLayoutManager.findFirstVisibleItemPosition();
if (!isScrolling && !isLastPage) {
if ((currentItem + scrollOutItem) >= totalItem && scrollOutItem >= 0) {
LoadMoreData();
}
}
}
});
getData();
return view;
}
public void filter(String text) {
feedsAdapter.notifyDataSetChanged();
List<Rating> temp = new ArrayList();
for (Rating d : feedsList) {
String tempF = "";
for (int i = 0; i < d.getFeatures().size(); i++) {
if (d.getFeatures().get(i).getName()!=null) {
tempF += d.getFeatures().get(i).getName()+",";
Log.d("This is name ", " Feature " + tempF);
if (tempF.toLowerCase().contains(text.toLowerCase())){
if (!temp.contains(d)){
temp.add(d);
}
}
}
}
if (d.getName().toLowerCase().contains(text.toLowerCase())&& !d.getAnonymous()) {
if (!temp.contains(d)){
temp.add(d);
}
}
}
//update recyclerview
feedsAdapter.updateList(temp);
}
private void getData() {
List.addAll(allRecieved);
List.remove(0);
adapter = new RecievedAdapter(List, context, recyclerView);
shimmerLayout.setVisibility(View.GONE);
recyclerView.setAdapter(feedsAdapter);
recyclerView.invalidate();
}
private void LoadMoreData() {
//Log.d("LoadMoreData", "Executing");
isScrolling = true;
if (allRecieved.get(0).getSize() == 0) {
isLastPage = true;
Toast.makeText(context, "That's All", Toast.LENGTH_SHORT).show();
} else {
isScrolling = false;
allGiven.remove(0);
if (!List.contains(allRecieved)) {
List.addAll(allRecieved);
adapter.notifyDataSetChanged();
} else {
Toast.makeText(context, "Call Repeated", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (adapter != null) {
adapter.onActivityResult(requestCode, resultCode, data);
}
}
public void update() {
adapter.updateOriginalList();
}
}
Given_Fragment
public class Given_Fragment extends Fragment {
#BindView(R.id.recyclerView)
RecyclerView recyclerView;
#BindView(R.id.shimmer_view_container)
ShimmerFrameLayout shimmerLayout;
#BindView(R.id.msg)
TextView message;
//Initialization of Classes
SessionManager session;
ApiClient apiClient;
List<ClassName> List = new ArrayList<>();
Boolean isScrolling = false;
boolean isDataLoaded = false;
int currentItem, totalItem, scrollOutItem;
//Properties to access
Context context;
String email;
String userId;
String access_token;
GivenAdapter adapter;
BottomSheetBehavior sheetBehavior;
LinearLayoutManager linearLayoutManager;
private boolean isLastPage = false;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recycler_view_layout,
container, false);
ButterKnife.bind(this, view);
context = getContext();
session = new SessionManager(context);
HashMap<String, String> user = session.getUserDetails();
email = user.get(SessionManager.KEY_EMAIL);
access_token = user.get(SessionManager.KEY_ACCESS_TOKEN);
userId = user.get(SessionManager.KEY_USER_ID);
apiClient = ((Common)
getActivity().getApplication()).getClient().create(ApiClient.class);
shimmerLayout.startShimmerAnimation();
linearLayoutManager = new LinearLayoutManager(getContext());
adapter = new GivenAdapter(List, context,
recyclerView);
adapter.setHasStableIds(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(feedsAdapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int
newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
currentItem = linearLayoutManager.getChildCount();
totalItem = linearLayoutManager.getItemCount();
scrollOutItem = linearLayoutManager.findFirstVisibleItemPosition();
if (!isScrolling && !isLastPage) {
if ((currentItem + scrollOutItem) >= totalItem && scrollOutItem >= 0) {
LoadMoreData();
}
}
}
});
getData();
return view;
}
public void filter(String text) {
feedsAdapter.notifyDataSetChanged();
List<Rating> temp = new ArrayList();
for (Rating d : feedsList) {
String tempF = "";
for (int i = 0; i < d.getFeatures().size(); i++) {
if (d.getFeatures().get(i).getName()!=null) {
tempF += d.getFeatures().get(i).getName()+",";
Log.d("This is name ", " Feature " + tempF);
if (tempF.toLowerCase().contains(text.toLowerCase())){
if (!temp.contains(d)){
temp.add(d);
}
}
}
}
if (d.getName().toLowerCase().contains(text.toLowerCase())&& !d.getAnonymous()) {
if (!temp.contains(d)){
temp.add(d);
}
}
}
//update recyclerview
feedsAdapter.updateList(temp);
}
private void getData() {
List.addAll(allgiven);
List.remove(0);
adapter = new GivenAdapter(List, context, recyclerView);
shimmerLayout.setVisibility(View.GONE);
recyclerView.setAdapter(feedsAdapter);
recyclerView.invalidate();
}
private void LoadMoreData() {
//Log.d("LoadMoreData", "Executing");
isScrolling = true;
if (allgiven.get(0).getSize() == 0) {
isLastPage = true;
Toast.makeText(context, "That's All", Toast.LENGTH_SHORT).show();
} else {
isScrolling = false;
allGiven.remove(0);
if (!List.contains(allgiven)) {
List.addAll(allgiven);
adapter.notifyDataSetChanged();
} else {
Toast.makeText(context, "Call Repeated", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (adapter != null) {
adapter.onActivityResult(requestCode, resultCode, data);
}
}
public void update() {
adapter.updateOriginalList();
}
}
Both Adapters are same am attaching only one
AllRecievedAdapter
public class AllRecievedAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
public int layout_feed = R.layout.layout_feed;
private List<ClassName> list = new ArrayList<>();
private Context context;
private SessionManager session;
private ApiClient apiClient;
private String email, access_token;
private UpvotesAdapter adapter;
private BottomSheetDialog bottomSheetDialog;
EditText location;
EditText dateView;
private Activity activity;
public AllRecievedAdapter(List<ClassName> listList, Context applicationContext, RecyclerView recyclerView) {
this.list = listList;
this.context = applicationContext;
this.activity = (Activity) context;
this.templist = listList;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
session = new SessionManager(context);
apiClient = ((Common) ((Activity) context).getApplication()).getClient().create(ApiClient.class);
HashMap<String, String> user = session.getUserDetails();
email = user.get(SessionManager.KEY_EMAIL);
access_token = user.get(SessionManager.KEY_ACCESS_TOKEN);
View view = LayoutInflater.from(parent.getContext()).inflate(layout_feed, parent, false);
AllRecievedAdapter.ViewHolderReview listViewHolder = new AllRecievedAdapter.ViewHolderReview(view);
return listViewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
holder.userName.setText(list.get(holder.getAdapterPosition()).getName());
GlideApp.with(context).load(list.get(holder.getAdapterPosition()).getImage()).into(holder.userImage);
}
#Override
public int getItemCount() {
return list.size();
}
public void updateList(List<Rating> temp) {
list = temp;
notifyDataSetChanged();
}
public void updateOriginalList(){
list = templist;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.userName)
TextView userName;
#BindView(R.id.userImage)
CircleImageView userImage;
public ViewHolderReview(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
If you need any extra information please let me know.
Call feedsAdapter.notifyDataSetChanged(); after updating the List. You are calling notifyDataSetChanged() before the list gets updated when the edittext is reset. Your filter method updates the list in the adapter but you are doing notifyDataSetChanged before the list is getting updated. You need to do it after

I am not able to load more pages using Endless RecyclerView ScrollListener

I am using Recyclerview to achieve endless recyclerview scroll listener. Now it loading only page = 1 and page = 2 while scrolling but it not loading another pages, and I added EndlessRecyclerViewScrollListener class from github.
Activity
public class AccountPagination extends AppCompatActivity implements RestCallback {
String UserId, rollname, username, name, fname, lname, emailid, contact_no, gender1, date_of_birth, country_id, postal_code, profession_response, Street_Address, City;
NonScrollListView listItem;
public static AccountStatementAdapter adapter;
ArrayList<AccountStatementModel> AccountStatementList;
AccountsSortingAdapter adapterSort;
AccountsTenRecordsAdapter adapterTenRecords;
ArrayList<AccountStatementModel> AccountDetailsList;
ArrayList<AccountStatementModel> AccountSortingList;
ArrayList<AccountStatementModel> AccountTenRecordsList;
ArrayList<AccountStatementModel> androidVersions;
List<AccountStatementModel> AccountList;
RecyclerView recyclerView;
int userPage = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account_pagination);
initViews();
recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
callAccountStatementAPI(userPage);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(linearLayoutManager);
// recyclerView.setAdapter(adapter);
recyclerView.addOnScrollListener(new EndlessRecyclerViewScrollListener(linearLayoutManager) {
#Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
userPage++;
callAccountStatementAPI(userPage);
}
});
//RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
//RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 1);
}
public void initViews() {
Intent i = getIntent();
UserId = i.getStringExtra("id");
name = SharedPref.read(SharedPref.FIRST_NAME, "") + "\t" + SharedPref.read(SharedPref.LAST_NAME, "");
String Hello = "Hello " + name;
getSupportActionBar().setSubtitle(Hello);
}
private void callAccountStatementAPI(final int page) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("user_id", SharedPref.read(SharedPref.USER_ID, ""));
map.put("page", String.valueOf(page));
RestService.getInstance(AccountPagination.this).getAccount1(map, new MyCallback<ArrayList<AccountStatementModel>>(AccountPagination.this,
AccountPagination.this, true, "Loading ...", GlobalVariables.SERVICE_MODE.ACCOUNT_STATEMENT));
}
#Override
public void onFailure(Call call, Throwable t, GlobalVariables.SERVICE_MODE mode) {
}
#Override
public void onSuccess(Response response, GlobalVariables.SERVICE_MODE mode) {
switch (mode) {
case ACCOUNT_STATEMENT:
androidVersions = (ArrayList<AccountStatementModel>) response.body();
AccountPaginationAdapter adapter = new AccountPaginationAdapter(getApplicationContext(), androidVersions);
androidVersions.addAll((Collection<? extends AccountStatementModel>) response.body());
adapter.notifyItemRangeInserted(adapter.getItemCount(), androidVersions.size()-2);
recyclerView.setAdapter(adapter);
break;
}
}
}
Adapter Class
public class AccountPaginationAdapter extends RecyclerView.Adapter<AccountPaginationAdapter.ViewHolder> {
private ArrayList<AccountStatementModel> android_versions;
private Context context;
private String TAG = "On Click";
String main_url = "http://www.consumer1st.in/ccb/";
public AccountPaginationAdapter(Context context, ArrayList<AccountStatementModel> android_versions) {
this.context = context;
this.android_versions = android_versions;
}
#Override
public AccountPaginationAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.accountpagination_item_list, viewGroup, false);
return new AccountPaginationAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(AccountPaginationAdapter.ViewHolder viewHolder, final int position) {
viewHolder.lable_name.setText(android_versions.get(position).getRemarks());
viewHolder.icon_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String icoon_index_id = android_versions.get(position).getId();
String iconn_id = android_versions.get(position).getUserId();
}
});
}
#Override
public int getItemCount() {
return android_versions.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView lable_name;
ImageView icon_image;
public ViewHolder(View view) {
super(view);
icon_image = (ImageView) itemView.findViewById(R.id.icon_image);
lable_name = (TextView) itemView.findViewById(R.id.lable_name);
}
}
}
Try this you will get perfect result.
int pastVisiblesItems, visibleItemCount, totalItemCount;
recyclerView.addOnScrollListener(new
RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dy > 0) {
visibleItemCount = layoutManager.getChildCount();
totalItemCount = layoutManager.getItemCount();
pastVisiblesItems = layoutManager.findFirstVisibleItemPosition();
if (loading && totalItemCount >= (pastVisiblesItems + 50)) {
userPage++;
callAccountStatementAPI(userPage);
Log.v("...", "Last Item Wow !");
//Do pagination.. i.e. fetch new data
}
}
}
});
Below the code will work But this code totally wrong way actually u are calling every api hit to creating new adapter and adding list. See more pagination examples and change it.. See reference here.
Write a method in Adapter Class:
public void addMoreItems(ArrayList<AccountStatementModel> newItems){
androidVersions.addAll(newItems);
}
Write Activity:
case ACCOUNT_STATEMENT:
androidVersions = (ArrayList<AccountStatementModel>) response.body();
AccountPaginationAdapter adapter = new AccountPaginationAdapter(getApplicationContext(), androidVersions);
androidVersions.addAll((Collection<? extends AccountStatementModel>) response.body());
adapter.addMoreItems(androidVersions);
adapter.notifyItemRangeInserted(adapter.getItemCount(), androidVersions.size()-2);
recyclerView.setAdapter(adapter);
break;
}

Refresh new data in RecyclerView on Android

I want develop android application for one website. I read website posts from json and show its in RecyclerView every 10 posts and when user scrolling on RecyclerView show more 10 post and go to end! in this project i use okHTTP v3 and RecyclerView!
I want gonna put a button and when click on this button, load new data (if there was new data).
Button codes:
// Refresh Data
toolbar_refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoadData();
}
});
}
Main Activity codes:
public class Main_page extends AppCompatActivity {
private static final long RIPPLE_DURATION = 250;
private Toolbar toolbar;
private RelativeLayout root;
private ImageView menu_image, toolbar_refresh;
private RecyclerView main_recyclerView;
private MainAdapter_loadMore mAdaper;
private List<MainDataModel> dataModels = new ArrayList<MainDataModel>();
protected Handler handler;
private RelativeLayout loadLayout;
private LinearLayoutManager mLayoutManager;
private int pageCount = 1;
String ServerAddress = ServerIP.getIP();
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
// Init
handler = new Handler();
context = getApplicationContext();
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
mLayoutManager = new LinearLayoutManager(this);
loadLayout = (RelativeLayout) findViewById(R.id.main_empty_layout);
toolbar_refresh = (ImageView) toolbar.findViewById(R.id.toolbar_update);
// Toolbar
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
}
// Load First Data
LoadData();
// Menu
root = (RelativeLayout) findViewById(R.id.main_root);
View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
root.addView(guillotineMenu);
menu_image = (ImageView) toolbar.findViewById(R.id.toolbar_logo);
new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), menu_image)
.setStartDelay(RIPPLE_DURATION)
.setActionBarViewForAnimation(toolbar)
.setClosedOnStart(true)
.build();
// RecyclerView and setData
main_recyclerView = (RecyclerView) findViewById(R.id.main_recycler);
main_recyclerView.setHasFixedSize(true);
main_recyclerView.setLayoutManager(mLayoutManager);
mAdaper = new MainAdapter_loadMore(this, main_recyclerView, dataModels);
main_recyclerView.setAdapter(mAdaper);
// Load More data
mAdaper.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
dataModels.add(null);
mAdaper.notifyItemInserted(dataModels.size() - 1);
LoadMoreData(pageCount);
}
});
// Refresh Data
toolbar_refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoadData();
}
});
}
#Subscribe
public void onEvent(List<MainDataModel> mainInfoModels) {
if (dataModels.size() > 0) {
dataModels.remove(dataModels.size() - 1);
mAdaper.notifyItemRemoved(dataModels.size());
mAdaper.setLoaded();
}
mAdaper.add(mainInfoModels);
mAdaper.notifyDataSetChanged();
pageCount++;
if (dataModels.isEmpty()) {
main_recyclerView.setVisibility(View.GONE);
loadLayout.setVisibility(View.VISIBLE);
} else {
main_recyclerView.setVisibility(View.VISIBLE);
loadLayout.setVisibility(View.GONE);
}
}
private void LoadData() {
MainDataInfo dataInfo = new MainDataInfo();
// here getMainDataInfo() should return the server response
dataInfo.getMainDataInfo(this);
}
private void LoadMoreData(int pageNumber) {
MainDataInfo_loadMore dataInfo_loadMore = new MainDataInfo_loadMore();
// here getMainDataInfo() should return the server response
dataInfo_loadMore.getMainDataInfo_loadMore(this, pageNumber);
}
}
Adapter codes:
public class MainAdapter_loadMore extends RecyclerView.Adapter {
private List<MainDataModel> mDateSet;
private Context mContext;
private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0;
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;
private boolean loading;
private OnLoadMoreListener onLoadMoreListener;
public MainAdapter_loadMore(Context context, RecyclerView recyclerView, List<MainDataModel> dataSet) {
this.mContext = context;
this.mDateSet = dataSet;
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView
.getLayoutManager();
recyclerView
.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView,
int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager
.findLastVisibleItemPosition();
if (!loading
&& totalItemCount <= (lastVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
#Override
public int getItemViewType(int position) {
return mDateSet.get(position) != null ? VIEW_ITEM : VIEW_PROG;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
if (viewType == VIEW_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.post_card_layout, parent, false);
vh = new DataViewHolder(v);
} else {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.progressbar_item, parent, false);
vh = new ProgressViewHolder(v);
}
return vh;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof DataViewHolder) {
((DataViewHolder) holder).main_post_title.setText(mDateSet.get(position).getTitle());
Glide.with(mContext)
.load(mDateSet.get(position).getThumbnail())
.placeholder(R.drawable.post_image)
.crossFade()
.into(((DataViewHolder) holder).main_post_image);
((DataViewHolder) holder).main_post_content.setText(Html.fromHtml(mDateSet.get(position).getContent()));
} else {
((ProgressViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
}
}
public void setLoaded() {
loading = false;
}
#Override
public int getItemCount() {
return mDateSet.size();
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
public void remove(int position) {
mDateSet.remove(position);
notifyItemRemoved(position);
}
public void clear() {
mDateSet.clear();
notifyDataSetChanged();
}
public void add(List<MainDataModel> models) {
mDateSet.addAll(models);
notifyDataSetChanged();
}
public void update(List<MainDataModel> models) {
mDateSet.clear();
mDateSet.addAll(models);
notifyDataSetChanged();
}
public class DataViewHolder extends RecyclerView.ViewHolder {
private TextView main_post_title, main_post_content;
private ImageView main_post_image;
public DataViewHolder(View itemView) {
super(itemView);
main_post_title = (TextView) itemView.findViewById(R.id.post_content_title);
main_post_image = (ImageView) itemView.findViewById(R.id.post_picture_image);
main_post_content = (TextView) itemView.findViewById(R.id.post_content_text);
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public AVLoadingIndicatorView progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = (AVLoadingIndicatorView) v.findViewById(R.id.avloadingIndicatorView);
}
}
}
AsyncTask code (LoadData codes) :
public class MainDataInfo {
private Context mContext;
private String ServerAddress = ServerIP.getIP();
public void getMainDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress + "page=1");
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<MainDataModel> infoModels;
#Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
//String url = (String) params[0];
Request request = new Request.Builder()
.url(ServerAddress + "page=1")
.cacheControl(CacheControl.FORCE_NETWORK)
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("posts");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
JSONObject images = postObject.optJSONObject("thumbnail_images");
JSONObject imagesPair = images.optJSONObject("medium");
int id = postObject.getInt("id");
String title = postObject.getString("title");
String content = postObject.getString("content");
String thumbnail = imagesPair.getString("url");
Log.d("Data", "Post id: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post title: " + thumbnail);
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(id, title, content, thumbnail));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
}
}
}
}
When use this method LoadData(); in button action, not load new data just copy fist 10 post and load again this first 10 post!
How can i fix it and when click on Button click action, load new data ?
Attention : Please don't give me negative points, help me and i really need you helps! thanks all <3
I dont understand your code but in your AsyncTask this method should like that :
public void getMainDataInfo(Context context,int page) {
mContext = context;
new getInfo().execute(ServerAddress + "page="+page);
}
In your code you always getting page=1, there is no paging parameter in method
You can use SwipeRefreshLayout for this.

Cannot scroll up because of endless scroll - setOnScrollListener

I'm making app with Swipe down to refresh functionality. And it works fine.
Here the code I used:
swipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_container);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeColors(Color.CYAN, Color.MAGENTA, Color.YELLOW, Color.BLUE, Color.CYAN);
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int topRowVerticalPostion = (mRecyclerView == null || mRecyclerView.getChildCount() == 0) ? 0 : mRecyclerView.getChildAt(0).getTop();
swipeRefreshLayout.setEnabled(dx == 0 && topRowVerticalPostion >= 0);
}
});
Then I added Swipe up to load more functionality. But after that I noticed, that I cannot scroll up to previous item, when before I scrolled down to N-th item. When I tried scroll up, it call RefreshLayout.
Code I used (https://gist.github.com/ssinss/e06f12ef66c51252563e):
mRecyclerView.setOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
#Override
public void onLoadMore(int current_page) {
Log.d("SCROLL PAST UPDATE", "You hit me");
//maintain scroll position
int lastFirstVisiblePosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
((LinearLayoutManager) mRecyclerView.getLayoutManager()).scrollToPosition(lastFirstVisiblePosition);
loadMore(articles);
}
});
Full code:
public class Tab3 extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
private boolean isLoading = true;
int currentFirstVisibleItem, currentVisibleItemCount, currentScrollState, SCROLL_STATE_IDLE = 0;
public static final String TAG = "MyRecyclerList";
private List<ListItems> listItemsList = new ArrayList<ListItems>();
private RecyclerView mRecyclerView;
private MyRecyclerViewAdapter2 mAdapter;
protected LinearLayoutManager mLayoutManager;
private int page = 1;
private int post_count;
private String count;
private String jsonCategory;
private static final String url = "http://example.com/api/get_category_posts/?slug=";
private static final String articles = "article/";
private ProgressDialog progressDialog;
SwipeRefreshLayout swipeRefreshLayout;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_3,container,false);
mRecyclerView = (RecyclerView) v.findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
updateList(articles);
swipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_container);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeColors(Color.CYAN, Color.MAGENTA, Color.YELLOW, Color.BLUE, Color.CYAN);
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int topRowVerticalPostion = (mRecyclerView == null || mRecyclerView.getChildCount() == 0) ? 0 : mRecyclerView.getChildAt(0).getTop();
swipeRefreshLayout.setEnabled(dx == 0 && topRowVerticalPostion >= 0);
}
});
mRecyclerView.setOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
#Override
public void onLoadMore(int current_page) {
Log.d("SCROLL PAST UPDATE", "You hit me");
//maintain scroll position
int lastFirstVisiblePosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
((LinearLayoutManager) mRecyclerView.getLayoutManager()).scrollToPosition(lastFirstVisiblePosition);
loadMore(articles);
}
});
return v;
}
public void updateList (String category) {
page = 1;
category = url + category;
mAdapter = new MyRecyclerViewAdapter2(getActivity(), listItemsList);
mRecyclerView.setAdapter(mAdapter);
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
mAdapter.clearAdapter();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, category, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
swipeRefreshLayout.setRefreshing(false);
try {
JSONArray posts = response.getJSONArray("posts");
post_count = response.getInt("count");
for (int i = 0; i < post_count; i++) {
JSONObject singlePost = posts.getJSONObject(i);
ListItems item = new ListItems();
try {
item.setTitle(singlePost.getString("title_plain"));
item.setSlug(singlePost.getString("slug"));
item.setUrl(singlePost.getString("url"));
item.setContent(singlePost.getString("content"));
item.setDate(singlePost.getString("date"));
item.setThumbnail(singlePost.getString("thumbnail"));
}catch (JSONException e){
//item.setThumbnail("drawable://" + R.drawable.website_placeholder);
e.printStackTrace();
}
//jsonCategory = singlePost.getString()
listItemsList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse (VolleyError error) {
VolleyLog.d(TAG, "Помилка" + error.getMessage());
swipeRefreshLayout.setRefreshing(false);
}
});
queue.add(jsonObjectRequest);
}
public void loadMore (String category) {
page = page + 1;
category = url + category + "&page=" + page;
mAdapter = new MyRecyclerViewAdapter2(getActivity(), listItemsList);
mRecyclerView.setAdapter(mAdapter);
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
showProgressDialog();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, category, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hideProgressDialog();
try {
JSONArray posts = response.getJSONArray("posts");
post_count = response.getInt("count");
for (int i = 0; i < post_count; i++) {
JSONObject singlePost = posts.getJSONObject(i);
//JSONArray singlePost = response.getJSONArray("posts").getJSONObject(i);
ListItems item = new ListItems();
try {
item.setTitle(singlePost.getString("title_plain"));
item.setSlug(singlePost.getString("slug"));
item.setUrl(singlePost.getString("url"));
item.setContent(singlePost.getString("content"));
item.setDate(singlePost.getString("date"));
item.setThumbnail(singlePost.getString("thumbnail"));
}catch (JSONException e){
//item.setThumbnail("drawable://" + R.drawable.website_placeholder);
e.printStackTrace();
}
//jsonCategory = singlePost.getString()
listItemsList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse (VolleyError error) {
VolleyLog.d (TAG, "Помилка" + error.getMessage());
hideProgressDialog();
}
});
queue.add(jsonObjectRequest);
}
public void showProgressDialog () {
if(progressDialog == null){
progressDialog = new ProgressDialog(this.getActivity());
progressDialog.setMessage("Будь ласка, зачекайте...");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
}
public void hideProgressDialog () {
if(progressDialog != null){
progressDialog.dismiss();
progressDialog = null;
}
}
#Override
public void onRefresh(){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
updateList(articles);
mAdapter.notifyDataSetChanged();
}
}, 1000);
}
}
solved by deleting this:
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int topRowVerticalPostion = (mRecyclerView == null || mRecyclerView.getChildCount() == 0) ? 0 : mRecyclerView.getChildAt(0).getTop();
swipeRefreshLayout.setEnabled(dx == 0 && topRowVerticalPostion >= 0);
}
});
And add this to mRecyclerView.setOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int topRowVerticalPostion = (mRecyclerView == null || mRecyclerView.getChildCount() == 0) ? 0 : mRecyclerView.getChildAt(0).getTop();
swipeRefreshLayout.setEnabled(dx == 0 && topRowVerticalPostion >= 0);
}
if you use this library 'com.lzy.widget:view-core:0.2.1' and integration with SwipeRefresh add this code, work for me.
scrollableLayout.setOnScrollListener(new HeaderViewPager.OnScrollListener() {
#Override
public void onScroll(int currentY, int maxY) {
pagerHeader.setTranslationY(currentY / 2);
int topRowVerticalPostion = (rvRestaurant == null || rvRestaurant.getChildCount() == 0) ? 0 : rvRestaurant.getChildAt(0).getTop();
mSwipeRefreshLayout.setEnabled(currentY == 0 && topRowVerticalPostion >= 0);
}
});

Categories

Resources