SwipeRefreshLayout Tutorial and Examples
SwipeRefreshLayout exists as a support library and enables us implement the now popular Swipe to Refresh. Some call it Pull To Refresh,some drag to refresh but the concept is simple,pull or swipe down on your layout and this causes display of a small progress circle.We can then of course capitalize on that and refresh our dataset.
Example 1 - Android SwipeRefreshLayout with RecyclerView -> Simulate Updates
This is a Swipe To Refresh tutorial.
We want that when the user pulls at the top of our layout we refresh data. This is a very popular technique for refreshing data that is implemented by so many mobile apps.
In this case our widget is a recyclerview.
Let's go.
What we do :
- Custom RecyclerView with cardviews with images and text.
- Our data source is a simple arraylist.
- Use SwipeRefreshlayout.
- When user swipes down,we simulate downloading of fresh copies of data.
- We do this in background thread using handlers.
- Rebind the data to our recyclerview.
\===
1. Create Basic Activity Project
- First create an empty project in android studio. Go to File --> New Project.
- Type the application name and choose the company name.
- Choose minimum SDK.
- Choose Basic activity.
- Click Finish.
Basic activity will have a toolbar and floating action button already added in the layout
Normally two layouts get generated with this option:
No. | Name | Type | Description |
---|---|---|---|
1. | activity_main.xml | XML Layout | Will get inflated into MainActivity Layout.Typically contains appbarlayout with toolbar.Also has a floatingactionbutton. |
2. | content_main.xml | XML Layout | Will be included into activity_main.xml.You add your views and widgets here. |
3. | MainActivity.java | Class | Main Activity. |
In this example I used a basic activity.
The activity will automatically be registered in the android_manifest.xml. Android Activities are components and normally need to be registered as an application component.
If you've created yours manually then register it inside the <application>...<application>
as following, replacing the MainActivity
with your activity name:
<activity android_name=".MainActivity">
<intent-filter>
<action android_name="android.intent.action.MAIN" />
<category android_name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
You can see that one action and category are specified as intent filters. The category makes our MainActivity as launcher activity. Launcher activities get executed first when th android app is run.
Advantage of Creating Basic Activity project
You can optionally choose empty activity over basic activity for this project.
However basic activity has the following advantages:
No. | Advantage |
---|---|
1. | Provides us a readymade toolbar which gives us actionbar features yet easily customizable |
2. | Provides us with appbar layout which implements material design appbar concepts. |
3. | Provides a FloatinActionButton which we can readily use to initiate quick actions especially in examples like these. |
4. | Decouples our custom content views and widgets from the templating features like toolbar. |
Generated Project Structure
AndroidStudio will generate for you a project with default configurations via a set of files and directories.
Here are the most important of them:
No. | File | Major Responsibility |
---|---|---|
1. | build/ |
A directory containing resources that have been compiled from the building of application and the classes generated by android tools. Such a tool is the R.java file. R.java file normally holds the references to application resources. |
2. | libs/ |
To hold libraries we use in our project. |
3. | src/main/ |
To hold the source code of our application.This is the main folder you work with. |
4. | src/main/java/ |
Contains our java classes organized as packages. |
5. | src/main/res/ |
Contains our project resources folders as follows. |
6. | src/main/res/drawable/ |
Contains our drawable resources. |
7. | src/main/res/layout/ |
Contains our layout resources. |
8. | src/main/res/menu/ |
Contains our menu resources XML code. |
9. | src/main/res/values/ |
Contains our values resources XML code.These define sets of name-value pairs and can be strings, styles and colors. |
10. | AndroidManifest.xml |
This file gets autogenerated when we create an android project.It will define basic information needed by the android system like application name,package name,permissions,activities,intents etc. |
11. | build.gradle |
Gradle Script used to build the android app. |
2. Add Dependencies
In your build.gradle:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.2.1'
compile 'com.android.support:design:23.2.1'
compile 'com.android.support:cardview-v7:23.2.1'
}
3. Create User Interface
User interfaces are typically created in android using XML layouts as opposed by direct java coding.
This is an example fo declarative programming.
Advantages of Using XML over Java
No. | Advantage |
---|---|
1. | Declarative creation of widgets and views allows us to use a declarative language XML which makes is easier. |
2. | It's easily maintanable as the user interface is decoupled from your Java logic. |
3. | It's easier to share or download code and safely test them before runtime. |
4. | You can use XML generated tools to generate XML |
Here are our layouts for this project:
(a). activity_main.xml
- This layout gets inflated to MainActivity user interface.
- It includes the content_main.xml.
Here are some of the widgets, views and viewgroups that get employed"
No. | View/ViewGroup | Package | Role |
---|---|---|---|
1. | CordinatorLayout | android.support.design.widget |
Super-powered framelayout that provides our application's top level decoration and is also specifies interactions and behavioros of all it's children. |
2. | AppBarLayout | android.support.design.widget |
A LinearLayout child that arranges its children vertically and provides material design app bar concepts like scrolling gestures. |
3. | ToolBar | <android.support.v7.widget |
A ViewGroup that can provide actionbar features yet still be used within application layouts. |
4. | FloatingActionButton | android.support.design.widget |
An circular imageview floating above the UI that we can use as buttons. |
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
android_layout_width="match_parent"
android_layout_height="match_parent"
android_fitsSystemWindows="true"
tools_context="com.tutorials.hp.swiperefreshrecyclerview.MainActivity">
<android.support.design.widget.AppBarLayout
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android_id="@+id/toolbar"
android_layout_width="match_parent"
android_layout_height="?attr/actionBarSize"
android_background="?attr/colorPrimary"
app_popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android_id="@+id/fab"
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_layout_gravity="bottom|end"
android_layout_margin="@dimen/fab_margin"
android_src="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
(b). content_main.xml
This layout gets included in your activity_main.xml. We define recyclerview inside a SwipeRefreshLayout here.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android_layout_width="match_parent"
android_layout_height="match_parent"
android_paddingBottom="@dimen/activity_vertical_margin"
android_paddingLeft="@dimen/activity_horizontal_margin"
android_paddingRight="@dimen/activity_horizontal_margin"
android_paddingTop="@dimen/activity_vertical_margin"
app_layout_behavior="@string/appbar_scrolling_view_behavior"
tools_context="com.tutorials.hp.swiperefreshrecyclerview.MainActivity"
tools_showIn="@layout/activity_main">
<android.support.v4.widget.SwipeRefreshLayout
android_id="@+id/swiper"
android_layout_width="match_parent"
android_layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android_id="@+id/mRecycler"
android_layout_width="match_parent"
android_layout_height="match_parent"
>
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
(c). model.xml
RecyclerViewItem row model.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
android_orientation="horizontal" android_layout_width="match_parent"
android_layout_margin="10dp"
card_view_cardCornerRadius="10dp"
card_view_cardElevation="10dp"
android_layout_height="wrap_content">
<RelativeLayout
android_layout_width="match_parent"
android_layout_height="match_parent">
<ImageView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_id="@+id/movieImage"
android_padding="10dp"
android_src="@drawable/ghost" />
<TextView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_textAppearance="?android:attr/textAppearanceLarge"
android_text="Name"
android_id="@+id/nameTxt"
android_padding="10dp"
android_textColor="@color/colorAccent"
android_layout_below="@+id/movieImage"
android_layout_alignParentLeft="true"
/>
<TextView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_textAppearance="?android:attr/textAppearanceLarge"
android_text=" John Doe a former FBI Agent and now Physics teacher .is wrongly accussed of murdering an innocent child.He makes it his business to find the bad guys who did taht.He convinces hacker Aram to join him.....
"
android_id="@+id/descTxt"
android_padding="10dp"
android_layout_below="@+id/nameTxt"
android_layout_alignParentLeft="true"
/>
<TextView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_textAppearance="?android:attr/textAppearanceMedium"
android_text="TV Show"
android_id="@+id/posTxt"
android_padding="10dp"
android_layout_below="@+id/movieImage"
android_layout_alignParentRight="true" />
<CheckBox
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_id="@+id/chk"
android_layout_alignParentRight="true"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
SECTION 2 : Our Data Object
Spacecraft.java
Main Responsibility : IS A SINGLE DATA OBJECT
- Represents a single object.Here I'll use Movie.
- The object shall have various properties like name,image etc.
- Each object shall occupy a specific viewitem, here cardview.
package com.tutorials.hp.swiperefreshlistviewexample;
public class Movie {
private String name;
private int image;
public Movie(String name, int image) {
this.name = name;
this.image = image;
}
public String getName() {
return name;
}
public int getImage() {
return image;
}
}
SECTION 3 : Adapter class
ItemClickListener inetrface
Main Responsibility : DEFINES ITEMCLICK EVENT HANDER SIGNATURE
- Define our ListView ViewItem's signature for our OnItemClick methods.
package com.tutorials.hp.swiperefreshlistviewexample;
public interface ItemClickListener {
void onItemClick();
}
View Holder class
Main Responsibility : HOLD VIEWS FOR RECYCLING.
- In this case textviews and imageviews.
package com.tutorials.hp.swiperefreshlistviewexample;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class MyViewHolder implements View.OnClickListener {
ImageView img;
TextView nameTxt;
ItemClickListener itemClickListener;
public MyViewHolder(View v) {
img= (ImageView) v.findViewById(R.id.movieImage);
nameTxt= (TextView) v.findViewById(R.id.nameTxt);
v.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener ic)
{
this.itemClickListener=ic;
}
@Override
public void onClick(View v) {
this.itemClickListener.onItemClick();
}
}
Custom Adapter class
Main Responsibility : HELPS US BIND CUSTOM DATA TO LISTVIEW.
- You can use one line of code to bind simple data to listview.
- But for custom data like ours,we need an adapter to adapt it.
- We shall use BaseAdapter as our Base class.
- Our BaseAdapter subclass shall receive an arraylist and a context.
- We shall simulate fetching updates.
- We do this in background thread using Handlers.
- Meanwhile we show a progress circle.
package com.tutorials.hp.swiperefreshlistviewexample;
import android.content.Context;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
public class CustomAdapter extends BaseAdapter {
Context c;
ArrayList<Movie> movies;
SwipeRefreshLayout swipe;
LayoutInflater inflater;
public CustomAdapter(Context c, ArrayList<Movie> movies,SwipeRefreshLayout swipe) {
this.c = c;
this.movies = movies;
this.swipe=swipe;
}
@Override
public int getCount() {
return movies.size();
}
@Override
public Object getItem(int position) {
return movies.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(inflater==null)
{
inflater= (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if(convertView==null)
{
convertView=inflater.inflate(R.layout.model,parent,false);
}
MyViewHolder holder=new MyViewHolder(convertView);
holder.nameTxt.setText(movies.get(position).getName());
holder.img.setImageResource(movies.get(position).getImage());
holder.setItemClickListener(new ItemClickListener() {
@Override
public void onItemClick() {
Toast.makeText(c, movies.get(position).getName(), Toast.LENGTH_SHORT).show();
}
});
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refresh();
}
});
return convertView;
}
private void refresh()
{
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
movies.add(0,movies.get(new Random().nextInt(movies.size())));
CustomAdapter.this.notifyDataSetChanged();
swipe.setRefreshing(false);
}
},3000);
}
}
SECTION 4 : Our Activity
MainActivity class.
Main Responsibility : LAUNCH OUR APP.
- We shall reference the views like ListView and Floating action button here,from our XML Layouts.Also SwipeRefreshLayout.
- We then generate our dataset and pass it to an instance of our adapter.
- We set the adapter to our ListView.
package com.tutorials.hp.swiperefreshlistviewexample;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView lv;
CustomAdapter adapter;
SwipeRefreshLayout swipe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
lv= (ListView) findViewById(R.id.lv);
swipe= (SwipeRefreshLayout) findViewById(R.id.swiper);
final ArrayList<Movie> movies=getMovies();
adapter=new CustomAdapter(this,movies,swipe);
lv.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, String.valueOf(movies.size()), Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
private ArrayList<Movie> getMovies()
{
//COLECTION OF MOVIES
ArrayList<Movie> movies=new ArrayList<>();
Movie movie=new Movie("Game Of Thrones",R.drawable.thrones);
movies.add(movie);
movie=new Movie("BlackList",R.drawable.red);
movies.add(movie);
movie=new Movie("Breaking Bad",R.drawable.breaking);
movies.add(movie);
movie=new Movie("Shuttle Carrier",R.drawable.shuttlecarrier);
movies.add(movie);
movie=new Movie("Fruits",R.drawable.fruits);
movies.add(movie);
movie=new Movie("Crisis",R.drawable.crisis);
movies.add(movie);
movie=new Movie("Ghost Rider",R.drawable.rider);
movies.add(movie);
movie=new Movie("Star Wars",R.drawable.starwars);
movies.add(movie);
movie=new Movie("Men In Black",R.drawable.meninblack);
movies.add(movie);
return movies;
}
}
SECTION 5 : Our Layouts
ActivityMain.xml Layout.
- Inflated as our activity's view.
- Contains xml specifications for Cordinator Layout,appbar layout,toolbar as well as floating action button.All these are contained in Design Support library.
- Includes content main where we define our view hierarchy.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
android_layout_width="match_parent"
android_layout_height="match_parent"
android_fitsSystemWindows="true"
tools_context="com.tutorials.hp.swiperefreshlistviewexample.MainActivity">
<android.support.design.widget.AppBarLayout
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android_id="@+id/toolbar"
android_layout_width="match_parent"
android_layout_height="?attr/actionBarSize"
android_background="?attr/colorPrimary"
app_popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android_id="@+id/fab"
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_layout_gravity="bottom|end"
android_layout_margin="@dimen/fab_margin"
android_src="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
ContentMain.xml Layout.
- Defines our view hierarchy.
- Wraps our AdapterView with SwipeRefreshLayout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android_layout_width="match_parent"
android_layout_height="match_parent"
android_paddingBottom="@dimen/activity_vertical_margin"
android_paddingLeft="@dimen/activity_horizontal_margin"
android_paddingRight="@dimen/activity_horizontal_margin"
android_paddingTop="@dimen/activity_vertical_margin"
app_layout_behavior="@string/appbar_scrolling_view_behavior"
tools_context="com.tutorials.hp.swiperefreshlistviewexample.MainActivity"
tools_showIn="@layout/activity_main">
<android.support.v4.widget.SwipeRefreshLayout
android_id="@+id/swiper"
android_layout_width="match_parent"
android_layout_height="wrap_content">
<ListView
android_id="@+id/lv"
android_layout_width="match_parent"
android_layout_height="match_parent"
>
</ListView>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
Model.xml Layout.
- Inflated as our AdapterView's viewitems.
- How our CardViews shall look.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
android_orientation="horizontal" android_layout_width="match_parent"
android_layout_margin="10dp"
card_view_cardCornerRadius="10dp"
card_view_cardElevation="10dp"
android_layout_height="wrap_content">
<RelativeLayout
android_layout_width="match_parent"
android_layout_height="match_parent">
<ImageView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_id="@+id/movieImage"
android_padding="10dp"
android_src="@drawable/ghost" />
<TextView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_textAppearance="?android:attr/textAppearanceLarge"
android_text="Name"
android_id="@+id/nameTxt"
android_padding="10dp"
android_textColor="@color/colorAccent"
android_layout_below="@+id/movieImage"
android_layout_alignParentLeft="true"
/>
<TextView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_textAppearance="?android:attr/textAppearanceLarge"
android_text=" John Doe a former FBI Agent and now Physics teacher .is wrongly accussed of murdering an innocent child.He makes it his business to find the bad guys who did taht.He convinces hacker Aram to join him.....
"
android_id="@+id/descTxt"
android_padding="10dp"
android_layout_below="@+id/nameTxt"
android_layout_alignParentLeft="true"
/>
<TextView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_textAppearance="?android:attr/textAppearanceMedium"
android_text="TV Show"
android_id="@+id/posTxt"
android_padding="10dp"
android_layout_below="@+id/movieImage"
android_layout_alignParentRight="true" />
<CheckBox
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_id="@+id/chk"
android_layout_alignParentRight="true"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
Example 2 - Android Swipe RefreshLayout with ListView
This is an android example to swipe to refresh a custom listview ith images and text.
Swipe to Refresh or Pull to Refresh is a very popular mechanism for refeshing data. It's also more modern than say clicking a button or something.
A special layout called SwipeRefreshLayout allows this in a very easy manner.
2. Add Dependencies
Add dependencies in your app level build.gradle.
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.2.1'
compile 'com.android.support:design:23.2.1'
compile 'com.android.support:cardview-v7:23.2.1'
}
3. Create User Interface
User interfaces are typically created in android using XML layouts as opposed by direct java coding.
This is an example fo declarative programming.
Advantages of Using XML over Java
No. | Advantage |
---|---|
1. | Declarative creation of widgets and views allows us to use a declarative language XML which makes is easier. |
2. | It's easily maintanable as the user interface is decoupled from your Java logic. |
3. | It's easier to share or download code and safely test them before runtime. |
4. | You can use XML generated tools to generate XML |
Here are our layouts for this project:
(a). activity_main.xml
- This layout gets inflated to MainActivity user interface.
- It includes the content_main.xml.
Here are some of the widgets, views and viewgroups that get employed"
No. | View/ViewGroup | Package | Role |
---|---|---|---|
1. | CordinatorLayout | android.support.design.widget |
Super-powered framelayout that provides our application's top level decoration and is also specifies interactions and behavioros of all it's children. |
2. | AppBarLayout | android.support.design.widget |
A LinearLayout child that arranges its children vertically and provides material design app bar concepts like scrolling gestures. |
3. | ToolBar | <android.support.v7.widget |
A ViewGroup that can provide actionbar features yet still be used within application layouts. |
4. | FloatingActionButton | android.support.design.widget |
An circular imageview floating above the UI that we can use as buttons. |
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
android_layout_width="match_parent"
android_layout_height="match_parent"
android_fitsSystemWindows="true"
tools_context="com.tutorials.hp.swiperefreshlistviewexample.MainActivity">
<android.support.design.widget.AppBarLayout
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android_id="@+id/toolbar"
android_layout_width="match_parent"
android_layout_height="?attr/actionBarSize"
android_background="?attr/colorPrimary"
app_popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android_id="@+id/fab"
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_layout_gravity="bottom|end"
android_layout_margin="@dimen/fab_margin"
android_src="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
(b). content_main.xml
This layout gets included in your activity_main.xml.
We define a ListView inside a SwipeRefreshLayout inside here.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android_layout_width="match_parent"
android_layout_height="match_parent"
android_paddingBottom="@dimen/activity_vertical_margin"
android_paddingLeft="@dimen/activity_horizontal_margin"
android_paddingRight="@dimen/activity_horizontal_margin"
android_paddingTop="@dimen/activity_vertical_margin"
app_layout_behavior="@string/appbar_scrolling_view_behavior"
tools_context="com.tutorials.hp.swiperefreshlistviewexample.MainActivity"
tools_showIn="@layout/activity_main">
<android.support.v4.widget.SwipeRefreshLayout
android_id="@+id/swiper"
android_layout_width="match_parent"
android_layout_height="wrap_content">
<ListView
android_id="@+id/lv"
android_layout_width="match_parent"
android_layout_height="match_parent"
>
</ListView>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
(c). model.xml
Custom ListView row model:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
android_orientation="horizontal" android_layout_width="match_parent"
android_layout_margin="10dp"
card_view_cardCornerRadius="10dp"
card_view_cardElevation="10dp"
android_layout_height="wrap_content">
<RelativeLayout
android_layout_width="match_parent"
android_layout_height="match_parent">
<ImageView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_id="@+id/movieImage"
android_padding="10dp"
android_src="@drawable/ghost" />
<TextView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_textAppearance="?android:attr/textAppearanceLarge"
android_text="Name"
android_id="@+id/nameTxt"
android_padding="10dp"
android_textColor="@color/colorAccent"
android_layout_below="@+id/movieImage"
android_layout_alignParentLeft="true"
/>
<TextView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_textAppearance="?android:attr/textAppearanceLarge"
android_text=" John Doe a former FBI Agent and now Physics teacher .is wrongly accussed of murdering an innocent child.He makes it his business to find the bad guys who did taht.He convinces hacker Aram to join him.....
"
android_id="@+id/descTxt"
android_padding="10dp"
android_layout_below="@+id/nameTxt"
android_layout_alignParentLeft="true"
/>
<TextView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_textAppearance="?android:attr/textAppearanceMedium"
android_text="TV Show"
android_id="@+id/posTxt"
android_padding="10dp"
android_layout_below="@+id/movieImage"
android_layout_alignParentRight="true" />
<CheckBox
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_id="@+id/chk"
android_layout_alignParentRight="true"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
4. Java Classes
(a). Movie.java
Our data object.
package com.tutorials.hp.swiperefreshlistviewexample;
public class Movie {
private String name;
private int image;
public Movie(String name, int image) {
this.name = name;
this.image = image;
}
public String getName() {
return name;
}
public int getImage() {
return image;
}
}
(b). ItemClickListener.java
Our Item Click Listener interface.
package com.tutorials.hp.swiperefreshlistviewexample;
public interface ItemClickListener {
void onItemClick();
}
(c). MyViewHolder.java
Our ListView ViewHolder class:
package com.tutorials.hp.swiperefreshlistviewexample;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class MyViewHolder implements View.OnClickListener {
ImageView img;
TextView nameTxt;
ItemClickListener itemClickListener;
public MyViewHolder(View v) {
img= (ImageView) v.findViewById(R.id.movieImage);
nameTxt= (TextView) v.findViewById(R.id.nameTxt);
v.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener ic)
{
this.itemClickListener=ic;
}
@Override
public void onClick(View v) {
this.itemClickListener.onItemClick();
}
}
(d). CustomAdapter.java
Our BaseAdapter class.
package com.tutorials.hp.swiperefreshlistviewexample;
import android.content.Context;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
public class CustomAdapter extends BaseAdapter {
Context c;
ArrayList<Movie> movies;
SwipeRefreshLayout swipe;
LayoutInflater inflater;
public CustomAdapter(Context c, ArrayList<Movie> movies,SwipeRefreshLayout swipe) {
this.c = c;
this.movies = movies;
this.swipe=swipe;
}
@Override
public int getCount() {
return movies.size();
}
@Override
public Object getItem(int position) {
return movies.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(inflater==null)
{
inflater= (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if(convertView==null)
{
convertView=inflater.inflate(R.layout.model,parent,false);
}
MyViewHolder holder=new MyViewHolder(convertView);
holder.nameTxt.setText(movies.get(position).getName());
holder.img.setImageResource(movies.get(position).getImage());
holder.setItemClickListener(new ItemClickListener() {
@Override
public void onItemClick() {
Toast.makeText(c, movies.get(position).getName(), Toast.LENGTH_SHORT).show();
}
});
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refresh();
}
});
return convertView;
}
private void refresh()
{
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
movies.add(0,movies.get(new Random().nextInt(movies.size())));
CustomAdapter.this.notifyDataSetChanged();
swipe.setRefreshing(false);
}
},3000);
}
}
MainActivity.java
Our MainAcrivity.
package com.tutorials.hp.swiperefreshlistviewexample;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView lv;
CustomAdapter adapter;
SwipeRefreshLayout swipe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
lv= (ListView) findViewById(R.id.lv);
swipe= (SwipeRefreshLayout) findViewById(R.id.swiper);
final ArrayList<Movie> movies=getMovies();
adapter=new CustomAdapter(this,movies,swipe);
lv.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, String.valueOf(movies.size()), Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
private ArrayList<Movie> getMovies()
{
//COLECTION OF MOVIES
ArrayList<Movie> movies=new ArrayList<>();
Movie movie=new Movie("Game Of Thrones",R.drawable.thrones);
movies.add(movie);
movie=new Movie("BlackList",R.drawable.red);
movies.add(movie);
movie=new Movie("Breaking Bad",R.drawable.breaking);
movies.add(movie);
movie=new Movie("Shuttle Carrier",R.drawable.shuttlecarrier);
movies.add(movie);
movie=new Movie("Fruits",R.drawable.fruits);
movies.add(movie);
movie=new Movie("Crisis",R.drawable.crisis);
movies.add(movie);
movie=new Movie("Ghost Rider",R.drawable.rider);
movies.add(movie);
movie=new Movie("Star Wars",R.drawable.starwars);
movies.add(movie);
movie=new Movie("Men In Black",R.drawable.meninblack);
movies.add(movie);
return movies;
}
}
Example 3 - Android SQLite - RecyclerView - CRUD then Swipe To Refresh Data
Android SQLite - RecyclerView - CRUD then Swipe To Refresh Data Tutorial.
This is an android sqlite refresh tutorial with recyclerview as our adapterview.Users will swipe the recyclerview or pull it down thus refreshing data stored in sqlite database.
However first see how to perform CRUD adding data to sqlite database. Then we retrieve the data and bind to a RecyclerView.
Then when the user can show up an an input dialog and add more data. Those data don't get shown immediately.
He can then swipe down/ or pull down the RecyclerView to refresh the data.
We use the SwipeRefreshLayout to enable this swiping functionality.
In short this is what we do in this episode 10:
- INSERT data to SQLite database.
- SELECT data from our SQLite database.
- Reload/Refresh data from our SQLite database when the user swipes/pulls down our RecyclerView.
SwipeRefreshLayout was introduced in Android KitKat.
1. Create Basic Activity Project
First create an empty project in android studio.You can see how to do so here.
2. Add Dependencies
Lets add dependencies in our app level build.gradle:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:design:23.3.0'
compile 'com.android.support:cardview-v7:23.3.0'
}
3. Create User Interface
User interfaces are typically created in android using XML layouts as opposed by direct java coding.
Here are our layouts for this project:
(a). activity_main.xml
- This layout gets inflated to MainActivity user interface.
- It includes the content_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
android_layout_width="match_parent"
android_layout_height="match_parent"
android_fitsSystemWindows="true"
tools_context="com.tutorials.hp.sqliteswipetorefresh.MainActivity">
<android.support.design.widget.AppBarLayout
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android_id="@+id/toolbar"
android_layout_width="match_parent"
android_layout_height="?attr/actionBarSize"
android_background="?attr/colorPrimary"
app_popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android_id="@+id/fab"
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_layout_gravity="bottom|end"
android_layout_margin="@dimen/fab_margin"
android_src="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
(b). content_main.xml
This layout gets included in your activity_main.xml.
We wrap our RecyclerView inside a SwipeRefreshLayout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android_layout_width="match_parent"
android_layout_height="match_parent"
android_paddingBottom="@dimen/activity_vertical_margin"
android_paddingLeft="@dimen/activity_horizontal_margin"
android_paddingRight="@dimen/activity_horizontal_margin"
android_paddingTop="@dimen/activity_vertical_margin"
app_layout_behavior="@string/appbar_scrolling_view_behavior"
tools_context="com.tutorials.hp.sqliteswipetorefresh.MainActivity"
tools_showIn="@layout/activity_main">
<android.support.v4.widget.SwipeRefreshLayout
android_id="@+id/swiper"
android_layout_width="match_parent"
android_layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android_id="@+id/rv"
android_layout_width="match_parent"
android_layout_height="wrap_content"
></android.support.v7.widget.RecyclerView>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
(c). dialog_input.xml
This is the input dialog.
Users will enter data to SQLite database via this dialog.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
android_orientation="horizontal" android_layout_width="500dp"
android_layout_margin="1dp"
card_view_cardCornerRadius="10dp"
card_view_cardElevation="5dp"
android_layout_height="match_parent">
<LinearLayout
android_layout_width="match_parent"
android_orientation="vertical"
android_layout_height="match_parent">
<android.support.design.widget.TextInputLayout
android_id="@+id/nameLayout"
android_layout_width="match_parent"
android_layout_height="wrap_content">
<EditText
android_id="@+id/nameEditTxt"
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_singleLine="true"
android_hint= "Name" />
</android.support.design.widget.TextInputLayout>
<Button android_id="@+id/saveBtn"
android_layout_width="fill_parent"
android_layout_height="wrap_content"
android_text="Save"
android_clickable="true"
android_background="@color/colorAccent"
android_layout_marginTop="40dp"
android_textColor="@android:color/white"/>
<Button android_id="@+id/retrieveBtn"
android_layout_width="fill_parent"
android_layout_height="wrap_content"
android_text="Retrieve"
android_clickable="true"
android_background="@color/colorAccent"
android_layout_marginTop="40dp"
android_textColor="@android:color/white"/>
</LinearLayout>
</android.support.v7.widget.CardView>
(d). model.xml
This is our model layout.
The RecyclerView viewitems will get inflated from this template. This will happpen in our RecyclerView Adapter class.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
android_orientation="horizontal" android_layout_width="match_parent"
android_layout_margin="5dp"
card_view_cardCornerRadius="10dp"
card_view_cardElevation="5dp"
android_layout_height="wrap_content">
<RelativeLayout
android_layout_width="match_parent"
android_layout_height="match_parent">
<TextView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_textAppearance="?android:attr/textAppearanceLarge"
android_text="Name"
android_id="@+id/nameTxt"
android_padding="10dp"
android_layout_alignParentTop="true"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
4. Java Classes
Here are our Java Classes:
Our Data Object
(a) Spacecraft.java
This is our model class. It models a single spacecraft.
It's our POJO class.
package com.tutorials.hp.sqliteswipetorefresh.mDataObject;
public class SpaceCraft {
String name;
int id;
public SpaceCraft() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Our SQLite Classes
(a) Constants.java
Our database constants.
Includes sqlite database name, table name, database version, table creation statement and table dropping statements as string constants.
package com.tutorials.hp.sqliteswipetorefresh.mDataBase;
public class Constants {
//COLUMNS
static final String ROW_ID="id";
static final String NAME="name";
//DB PROPS
static final String DB_NAME="hh_DB";
static final String TB_NAME="hh_TB";
static final int DB_VERSION=1;
//CREATE_TB
static final String CREATE_TB="CREATE TABLE hh_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name TEXT NOT NULL);";
//DROP_TB
static final String DROP_TB="DROP TABLE IF EXISTS "+TB_NAME;
}
(b) DBHelper.java
Our database helper class.
Creates sqlite database table and upgrades it.
package com.tutorials.hp.sqliteswipetorefresh.mDataBase;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, Constants.DB_NAME, null, Constants.DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
try
{
db.execSQL(Constants.CREATE_TB);
}catch (SQLException e)
{
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(Constants.DROP_TB);
onCreate(db);
}
}
(c) DBAdapter.java
Our sqlite database adapter class.
Allows us perform our CRUD operations : opening database, inserting data, retrieving data, closing the database.
package com.tutorials.hp.sqliteswipetorefresh.mDataBase;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DBAdapter {
Context c;
SQLiteDatabase db;
DBHelper helper;
public DBAdapter(Context c) {
this.c = c;
helper=new DBHelper(c);
}
//OPEN DB
public void openDB()
{
try
{
db=helper.getWritableDatabase();
}catch (SQLException e)
{
e.printStackTrace();
}
}
//CLOSING
public void closeDB()
{
try
{
helper.close();
}catch (SQLException e)
{
e.printStackTrace();
}
}
//SAVE OR INSERTING
public boolean add(String name)
{
try
{
ContentValues cv=new ContentValues();
cv.put(Constants.NAME, name);
db.insert(Constants.TB_NAME, Constants.ROW_ID, cv);
return true;
}catch (SQLException e)
{
e.printStackTrace();
}
return false;
}
//SELECT OR RETRIEVE
public Cursor retrieve()
{
String[] columns={Constants.ROW_ID,Constants.NAME};
return db.query(Constants.TB_NAME,columns,null,null,null,null,null);
}
}
Our RecyclerView Classes
(a) MyHolder.java
Our RecyclerView ViewHolder class.
package com.tutorials.hp.sqliteswipetorefresh.mRecycler;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.tutorials.hp.sqliteswipetorefresh.R;
public class MyHolder extends RecyclerView.ViewHolder {
TextView nameTxt;
public MyHolder(View itemView) {
super(itemView);
this.nameTxt= (TextView) itemView.findViewById(R.id.nameTxt);
}
}
##(b) MyAdapter.java Our RecyclerView Adapter class.
package com.tutorials.hp.sqliteswipetorefresh.mRecycler;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.tutorials.hp.sqliteswipetorefresh.R;
import com.tutorials.hp.sqliteswipetorefresh.mDataBase.DBAdapter;
import com.tutorials.hp.sqliteswipetorefresh.mDataObject.SpaceCraft;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
ArrayList<SpaceCraft> spaceCrafts;
SwipeRefreshLayout swipeRefreshLayout;
public MyAdapter(Context c, ArrayList<SpaceCraft> spaceCrafts, SwipeRefreshLayout swipeRefreshLayout) {
this.c = c;
this.spaceCrafts = spaceCrafts;
this.swipeRefreshLayout = swipeRefreshLayout;
}
@Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,parent,false);
MyHolder holder=new MyHolder(v);
return holder;
}
@Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.nameTxt.setText(spaceCrafts.get(position).getName());
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
getUpdates();
}
});
}
@Override
public int getItemCount() {
return spaceCrafts.size();
}
private void getUpdates()
{
spaceCrafts.clear();
DBAdapter db=new DBAdapter(c);
db.openDB();
Cursor c=db.retrieve();
while (c.moveToNext())
{
int id=c.getInt(0);
String name=c.getString(1);
SpaceCraft s=new SpaceCraft();
s.setId(id);
s.setName(name);
spaceCrafts.add(s);
}
db.closeDB();
swipeRefreshLayout.setRefreshing(false);
this.notifyDataSetChanged();
}
}
Our Activity class
(a) MainActivity.java
Our MainActivity class. Will display our RecyclerView and show us a dialog for adding data to SQLite database.
package com.tutorials.hp.sqliteswipetorefresh;
import android.app.Dialog;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.tutorials.hp.sqliteswipetorefresh.mDataBase.DBAdapter;
import com.tutorials.hp.sqliteswipetorefresh.mDataObject.SpaceCraft;
import com.tutorials.hp.sqliteswipetorefresh.mRecycler.MyAdapter;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView rv;
MyAdapter adapter;
SwipeRefreshLayout swipeRefreshLayout;
EditText nameEditText;
Button saveBtn,retrieveBtn;
ArrayList<SpaceCraft> spaceCrafts=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
rv= (RecyclerView) findViewById(R.id.rv);
rv.setLayoutManager(new LinearLayoutManager(this));
swipeRefreshLayout= (SwipeRefreshLayout) findViewById(R.id.swiper);
adapter=new MyAdapter(this,spaceCrafts,swipeRefreshLayout);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
displayDialog();
}
});
}
private void displayDialog()
{
Dialog d=new Dialog(this);
d.setTitle("Save To Database");
d.setContentView(R.layout.dialog_layout);
nameEditText= (EditText) d.findViewById(R.id.nameEditTxt);
saveBtn= (Button) d.findViewById(R.id.saveBtn);
retrieveBtn= (Button) d.findViewById(R.id.retrieveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
save(nameEditText.getText().toString());
}
});
retrieveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getSpaceCrafts();
}
});
d.show();
}
private void save(String name)
{
DBAdapter db=new DBAdapter(this);
db.openDB();
if(db.add(name))
{
nameEditText.setText("");
}else {
Toast.makeText(this,"Unable to save",Toast.LENGTH_SHORT).show();
}
db.closeDB();
}
private void getSpaceCrafts()
{
spaceCrafts.clear();
DBAdapter db=new DBAdapter(this);
db.openDB();
Cursor c=db.retrieve();
while (c.moveToNext())
{
int id=c.getInt(0);
String name=c.getString(1);
SpaceCraft s=new SpaceCraft();
s.setId(id);
s.setName(name);
spaceCrafts.add(s);
}
db.closeDB();
rv.setAdapter(adapter);
}
}
Download
Download code below.
If you prefer more explanations or want to see the demo then the video tutorial is here.
No. | Location | Link |
---|---|---|
1. | GitHub | Direct Download) |
2. | GitHub | Browse |
3. | YouTube | Video Tutorial |
4. | YouTube | Our YouTube Channel |