Skip to main content

Offline Load More Data with RecyclerView in android.

Step 1. Create a project step by step

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<include layout="@layout/layout_toolbar" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycleView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp" />
</LinearLayout> 

 layout_toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:layout_height="?android:attr/actionBarSize"
android:background="@color/purple_200"/>
</LinearLayout>


MainActivity.Java
public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private RecyclerView mRecyclerView;
private List<UserModel> mUsers = new ArrayList<>();
private UserAdapter mUserAdapter;

public static OnLoadMoreListener mOnLoadMoreListener;

public static boolean isLoading;

private int visibleThreshold = 5;

private int lastVisibleItem, totalItemCount;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setTitle("LoadMoreRecycleView");
for (int i = 0; i < 10; i++) {
UserModel user = new UserModel();
user.setName("Name " + i);
user.setEmail("vimalku" + i + "@gmail.com");
mUsers.add(user);
}
mRecyclerView = (RecyclerView) findViewById(R.id.recycleView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mUserAdapter = new UserAdapter(this, mUsers);
mRecyclerView.setAdapter(mUserAdapter);
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
mRecyclerView.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 (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (mOnLoadMoreListener != null) {
mOnLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
});
mUserAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override public void onLoadMore() {
Log.e("haint", "Load More");
mUsers.add(null);
mUserAdapter.notifyItemInserted(mUsers.size() - 1);
//Load more data for reyclerview
new Handler().postDelayed(new Runnable() {
@Override public void run() {
Log.e("haint", "Load More 2");
//Remove loading item
mUsers.remove(mUsers.size() - 1);
mUserAdapter.notifyItemRemoved(mUsers.size());
//Load data
int index = mUsers.size();
int end = index + 10;
for (int i = index; i < end; i++) {
UserModel user = new UserModel();
user.setName("Name " + i);
user.setEmail("vimalku" + i + "@gmail.com");
mUsers.add(user);
}
mUserAdapter.notifyDataSetChanged();
mUserAdapter.setLoaded();
}
}, 5000);
}
});
}
static class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public LoadingViewHolder(View itemView) {
super(itemView);
progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
}
}

}
layout_user_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
card_view:cardCornerRadius="5dp"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?android:selectableItemBackground">
<TextView android:id="@+id/tvName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Name"
android:textColor="@android:color/black"
android:textSize="18sp" />
<TextView android:id="@+id/tvEmailId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/tvName"
android:layout_margin="5dp"
android:text="Email Id"
android:textColor="@android:color/black"
android:textSize="12sp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
  
layout_loading_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ProgressBar android:id="@+id/progressBar1"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_height="wrap_content" />
</LinearLayout>


 
 
UserAdapter.Java:
class UserAdapter extends RecyclerView.Adapter <RecyclerView.ViewHolder > {
private Context context;
private List<UserModel> mUsers;

private final int VIEW_TYPE_ITEM = 0;

private final int VIEW_TYPE_LOADING = 1;

public UserAdapter(Context context, List<UserModel> mUsers) {
this.context = context;
this.mUsers = mUsers;
}

public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
MainActivity.mOnLoadMoreListener = mOnLoadMoreListener;
}
@Override public int getItemViewType(int position) {
return mUsers.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
View view = LayoutInflater.from(context).inflate(R.layout.layout_user_item, parent, false);
return new UserViewHolder(view);
} else if (viewType == VIEW_TYPE_LOADING) {
View view = LayoutInflater.from(context).inflate(R.layout.layout_loading_item, parent, false);
return new MainActivity.LoadingViewHolder(view);
}
return null;
}
@Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof UserViewHolder) {
UserModel user = mUsers.get(position);
UserViewHolder userViewHolder = (UserViewHolder) holder;
userViewHolder.tvName.setText(user.getName());
userViewHolder.tvEmailId.setText(user.getEmail());
} else if (holder instanceof MainActivity.LoadingViewHolder) {
MainActivity.LoadingViewHolder loadingViewHolder = (MainActivity.LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
@Override
public int getItemCount() {
return mUsers == null ? 0 : mUsers.size();
}

static class UserViewHolder extends RecyclerView.ViewHolder {
public TextView tvName;
public TextView tvEmailId;
public UserViewHolder(View itemView) {
super(itemView);
tvName = (TextView) itemView.findViewById(R.id.tvName);
tvEmailId = (TextView) itemView.findViewById(R.id.tvEmailId);
}
}
public void setLoaded() {
MainActivity.isLoading = false;
}
}
UserModel.Java:
public class UserModel {
private String name;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
OnLoadMoreListener interface:
public interface OnLoadMoreListener {
void onLoadMore();

 

Comments

Popular posts from this blog

How to call Post type API using Retrofit in Android?

Step by Step Implementation Step 1: Create a New Project Step 2: Add the below dependency in your build.gradle file Navigate to the Gradle Scripts > build.gradle (Module:app) and add the below dependency in the dependencies section.  // below dependency for using the retrofit implementation ‘com.squareup.retrofit2:retrofit:2.9.0’ implementation ‘com.squareup.retrofit2:converter-gson:2.5.0’ After adding this dependency sync your project and now move towards the AndroidManifest.xml part.   Step 3: Adding permissions to the internet in the AndroidManifest.xml file Navigate to the app > AndroidManifest.xml and add the below code to it.  <!--permissions for INTERNET--> <uses-permission android:name="android.permission.INTERNET"/> Step 4: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.  <?xml version="1.0"...

How to call Post API using Retrofit in Android using Jetpack Compose?

Note: If you are seeking Java code for Jetpack Compose , please note that Jetpack Compose is only available in Kotlin . It uses features such as coroutines , and the handling of @Composable annotations is handled by a Kotlin compiler. There is no method for Java to access these. Therefore, you cannot use Jetpack Compose if your project does not support Kotlin. Step By Step Implementation Step 1: Create a New Project in Android Studio We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project. Step 2: Add the below dependency to your build.gradle File Navigate to the Gradle Scripts > build.gradle (Module:app) and add the below dependency in the dependencies section.  // below dependency for using the retrofit implementation ‘com.squareup.retrofit2:retrofit:2.9.0’ implementation ‘com.squareup.retrofit2:converter-gson:2.5.0’ After adding this dependency sync your project and now move towards the AndroidManifes...

A Simple Data Binding Example

  Step-1: Enable data binding to android project ADD below line to your app level build.gradle file. android {     buildFeatures {         dataBinding = true     } }  Setp-2 : Add all your XML layout design inside this <layout></layout> tag <?xml version="1.0" encoding="utf-8"?> <layout     xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"> <androidx.constraintlayout.widget.ConstraintLayout     android:id="@+id/main"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity">     <TextView         android:id="@+id/greeting_text_view"         android:layout_width="wrap_content"         android:lay...