Android Pull To Refresh Tutorial - TuteCentral
Android Pull To Refresh Tutorial - TuteCentral
com)
(http://www.tutecentral.com/wp-content/uploads/2014/03/pull_to_refresh_cover.png)
In this tutorial I’ll show you how to use pull to refresh feature in your android application. Pull to refresh is the
hottest android UI pattern used by developers in their applications to improve the usability. You can see this pull to
refresh feature in many android applications like Gmail,Facebook, Twitter etc… I google it to find some tutorials to
how implement this but I couldn’t find any article related to this topic. I did it my self. For a beginner it may be a
difficult task to do. So I thought to do tutorial on this topic which will help to people who is struggling to use pull
to refresh in their android application.
Demo Video
Android Pull To Refresh Demo
0:19 / 1:10
Note :
At end of this tutorial you can download the example project and you can see the video demonstration of this
tutorial which will help you to follow this tutorial step by step.
“ActionBar-PullToRefresh” library will interact with the application actionbar to refresh. This library also compatible
with ”ActionBarSherlock”. In this tutorial I’ll not use “ActionBarSherlock” library behalf I’ll use stock android
actionbar. This library default supports only for android 4.0 (ICS-API level 14) or higher sdk levels. If you need to use
this library below API-Level 14 you need use ActionBarCompact library. Check
“Android Pull To Refresh with ActionBarCompact “ article to learn how to do this.
As you can see in the demo video above “ActionBar-PullToRefresh” library is support different views. Below list will
show you compatible views.
ActionBar-PullToRefresh : (https://github.com/chrisbanes/ActionBar-PullToRefresh)
SmoothProgressBar : (https://github.com/castorflex/SmoothProgressBar)
(http://www.tutecentral.com/wp-
content/uploads/2014/01/step2_p
rojectexplore.png)
Errors in ActionBar Pull To Refresh
Library
After you Import both libraries to your workspace ActionBar Pull To Refresh Library will have some errors as you can
see in above image. In order to fix this errors you need to do some updates to both libraries.
Next you need to Drag and Drop the “fr” folder from “java” to “src” folder in “main” project. By default all the class
will be in “java” folder so you need to change it “src” folder.
(http://www.tutecentral.com/wp-content/uploads/2014/01/smoothprogress_errorfix.png)
Drag and Drop the “fr” folder to “src”
Next open the “AndroidManifest.xml” file of ActionBar pull to refresh library. Update the manifest file as below
AndroidManifest.xml
1 <?xml version="1.0"-e
ActionBar Pull
ncoding="utf To Refresh
-8"?>
2 <manifest xmlns:android="http://schemas.android.com/apk/res/android (http://schemas.an
3 package="uk.co.senab.actionbarpulltorefresh.library">
4
5 <!-- set the minimum sdk version to 11 -->
6 <uses-sdk
7 android:minSdkVersion="11"
8 android:targetSdkVersion="18" />
9
10 <application />
11 </manifest>
Now most of the errors should be fixed. But there should error in “uk.co.senab.actionbarpulltorefresh.library =>
DefaultHeaderTransformer.java” class like below which will tell you there is no width(int) method in
“SmoothProgressDrawable” class.
(http://www.tutecentral.com/wp-content/uploads/2014/01/pull_to_refresh_error_fix.png)
Error in width() method
To fix this error you need to simply change the width(strokeWidth) to strokeWidth(strokeWidth). Now all the errors
are fixed.
BaseActivity.java
1 package com.tutecentral.pulltorefreshexample;
2
3 import android.app.Activity;
4 import android.app.Fragment;
5 import android.content.Intent;
6 import android.os.Bundle;
7 import android.view.Menu;
8 import android.view.MenuItem;
9 import android.widget.Toast;
10
11 public class BaseActivity extends Activity {
12
13 @Override
14 protected void onCreate(Bundle savedInstanceState) {
15 // TODO Auto-generated method stub
16 super.onCreate(savedInstanceState);
17
18 // Add the Sample Fragment if there is one
19 Fragment sampleFragment = getSampleFragment();
20 if (sampleFragment != null) {
21 getFragmentManager().beginTransaction()
22 .replace(android.R.id.content, sampleFragment).commit();
23 }
24
25 }
26
27 @Override
28 public boolean onCreateOptionsMenu(Menu menu) {
29 // TODO Auto-generated method stub
30
31 getMenuInflater().inflate(R.menu.base_menu, menu);
32 return super.onCreateOptionsMenu(menu);
33 }
34
35 @Override
36 public boolean onOptionsItemSelected(MenuItem item) {
37
38 // This method is for menu. This menu items will appear in all
39 //activities extends this class. I have use this menus to navigate
40 //between activities. You can change this code as you wish
41 //
42
43 switch (item.getItemId()) {
44 case R.id.action_listview:
45 Toast.makeText(this, "Pull to Refresh in ListView", Toast.LENGTH_SHORT).
46 Intent i=new Intent(this,ListViewActivity.class);
47 startActivity(i);
48
49 return true;
50 case R.id.action_scrollview:
51 Toast.makeText(this, "Pull to Refresh in Scroll View", Toast.LENGTH_SHOR
52
53 Intent x=new Intent(this,ScrollViewActivity.class);
54 startActivity(x);
55
56 return true;
57 case R.id.action_webview:
58 Toast.makeText(this, "Pull to Refresh in Web View", Toast.LENGTH_SHORT).
59
60 Intent z=new Intent(this,WebViewActivity.class);
61 startActivity(z);
62
63 return true;
64 }
65
66 return super.onOptionsItemSelected(item);
67 }
68
69 //This method will override by child class. Then base class can get the fragment
70 protected Fragment getSampleFragment() {
71 return null;
72 }
73
74 }
Create an android xml file in “res =>menu” folder called “base_menu.xml“. Copy and paste the below code into the
file. This menu used in BaseActivity to share the single menu with all fragments.
base_menu.xml
1 <?xml version="1.0" encoding="utf-8"?>
2 <menu xmlns:android="http://schemas.android.com/apk/res/android (http://schemas.androi
3
4 <!--
5 You can change this as your requrement. I use this menu Item to navigate bettween
6 fragments. So I can show how ListView,WebView & ScrollView works with
7 ActionBar Pull To Refresh Library
8 -->
9
10 <item android:id="@+id/action_listview"
11 android:title="ListView"
12 android:showAsAction="ifRoom|withText" />
13
14 <item android:id="@+id/action_webview"
15 android:title="WebView"
16 android:showAsAction="ifRoom|withText" />
17
18 <item android:id="@+id/action_scrollview"
19 android:title="ScrollVIew"
20 android:showAsAction="ifRoom|withText" />
21
22 </menu>
Now BaseActivity class is completed. You will see errors in this class because I didn’t create “WebViewActivity” &
“ScrollViewActivity” activities. These two activities are used to implement pull to refresh in web view and scroll view.
If you are not using those views you can delete that code snippet from your BaseActivity.java class.
As I mention I will use this pull to refresh library in ListView,WebView and ScrollView. So I will start with ListView,
Pull To Refresh With ListView
Goto “res => layout” open the “activity_list_view.xml” copy and paste the following code to xml file
activity_list_view.xml
1 <?xml version="1.0" encoding="utf-8"?>
2 <uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout
3 xmlns:android="http://schemas.android.com/apk/res/android (http://schemas.android.
4 android:id="@+id/ptr_layout"
5 android:layout_width="match_parent"
6 android:layout_height="match_parent">
7
8 <ListView
9 android:id="@+id/ptr_listview"
10 android:layout_height="match_parent"
11 android:layout_width="match_parent" />
12
13 </uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout>
Now open the “ListViewActivity.java” class.This class will extend by BaseActivity. Update your ListViewActivity class
according to below code or copy and paste below code your class.
ListViewActivity.java
1 package com.tutecentral.pulltorefreshexample;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
7 import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
8 import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
9 import android.os.AsyncTask;
10 import android.os.Bundle;
11 import android.app.Fragment;
12 import android.app.ListFragment;
13 import android.view.View;
14 import android.view.ViewGroup;
15 import android.widget.ArrayAdapter;
16
17 public class ListViewActivity extends BaseActivity {
18
19 @Override
20 protected Fragment getSampleFragment() {
21 return new SimpleListFragment();
22 }
23
24 public static class SimpleListFragment extends ListFragment implements OnRefres
25 {
26
27 int i=0;
28
29 private PullToRefreshLayout mPullToRefreshLayout;
30
31 ArrayAdapter<String> adapter;
32
33 List<String> list;
34
35 @Override
36 public void onViewCreated(View view, Bundle savedInstanceState) {
37 // TODO Auto-generated method stub
38 super.onViewCreated(view, savedInstanceState);
39
40 list=new ArrayList<String>();
41 int no=1;
42 for(int i=0;i<5;i++)
43 {
44 list.add("Item No :"+no++);
45 }
46
47 super.onViewCreated(view,savedInstanceState);
48 ViewGroup viewGroup = (ViewGroup) view;
49
50 // As we're using a ListFragment we create a PullToRefreshLayout ma
51 mPullToRefreshLayout = new PullToRefreshLayout(viewGroup.getContext
52
53 // We can now setup the PullToRefreshLayout
54 ActionBarPullToRefresh.from(getActivity())
55 // We need to insert the PullToRefreshLayout into the Fragm
56 .insertLayoutInto(viewGroup)
57 // Here we mark just the ListView and it's Empty View as pu
58 .theseChildrenArePullable(android.R.id.list, android.R.id.e
59 .listener(this)
60 .setup(mPullToRefreshLayout);
61
62 }
63
64 @Override
65 public void onActivityCreated(Bundle savedInstanceState) {
66 // TODO Auto-generated method stub
67 super.onActivityCreated(savedInstanceState);
68
69 adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.sim
70
71 // Set the List Adapter to display the sample items
72 setListAdapter(adapter);
73 setListShownNoAnimation(true);
74 }
75
76 @Override
77 public void onRefreshStarted(View view) {
78 // TODO Auto-generated method stub
79
80 //setListShown(false); // This will hide the listview and visible a
81
82 new AsyncTask<Void, Void, Void>() {
83
84 @Override
85 protected Void doInBackground(Void... params) {
86 try {
87 Thread.sleep(5000); // 5 seconds
88 int itemNo=list.size();
89 itemNo++;
90 list.add("New Item No :"+itemNo);
91
92 } catch (InterruptedException e) {
93 e.printStackTrace();
94 }
95 return null;
96 }
97
98 @Override
99 protected void onPostExecute(Void result) {
100 super.onPostExecute(result);
101
102 adapter.notifyDataSetChanged();
103 // Notify PullToRefreshLayout that the refresh has finished
104 mPullToRefreshLayout.setRefreshComplete();
105
106 // if you set the "setListShown(false)" then you have to
107 //uncomment the below code segment
108
109 // if (getView() != null) {
110 // // Show the list again
111 // setListShown(true);
112 // }
113 }
114 }.execute();
115
116 }
117
118 }
119
120 }
Now listview class is over. Currently you are not able to run this program because there are some errors in
BaseActivity.java class to fix. Just comment below lines and run the application to check the result.
BaseActivity.java
1 ...
2 Intent x=new Intent(this,ScrollViewActivity.class); //comment this line
3 startActivity(x);//comment this line
4
5 ...
6 Intent z=new Intent(this,WebViewActivity.class);//comment this line
7 startActivity(z);//comment this line
Now goto “res=>layout” open the “activity_web_view.xml” file. This file should include a “PullToRefreshLayout” and
a “WebView“ as following code
activity_web_view.xml
1 <uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout xmlns:android="http://
2 xmlns:ptr="http://schemas.android.com/apk/res-auto (http://schemas.android.com/apk
3 android:id="@+id/ptr_layout"
4 android:layout_width="match_parent"
5 android:layout_height="match_parent" >
6
7 <WebView
8 android:id="@+id/webview"
9 android:layout_width="match_parent"
10 android:layout_height="match_parent"
11 ptr:ptrViewDelegateClass="uk.co.senab.actionbarpulltorefresh.library.viewdeleg
12
13 </uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout>
Now goto the “WebViewActivity.java” class and update the class according to below coding. This class extends
“BaseActivity” and implements “OnRefreshListener”
WebViewActivity.java
1 package com.tutecentral.pulltorefreshexample;
2
3 import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
4 import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
5 import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
6 import android.os.Bundle;
7 import android.view.View;
8 import android.webkit.WebView;
9 import android.webkit.WebViewClient;
10
11 public class WebViewActivity extends BaseActivity implements OnRefreshListener {
12
13 private PullToRefreshLayout mPullToRefreshLayout;
14
15 private WebView mWebView;
16
17 @Override
18 protected void onCreate(Bundle savedInstanceState) {
19 super.onCreate(savedInstanceState);
20 setContentView(R.layout.activity_web_view);
21
22 mWebView = (WebView) findViewById(R.id.webview);
23 mWebView.getSettings().setJavaScriptEnabled(true);
24 mWebView.setWebViewClient(new SampleWebViewClient());
25
26 // Now find the PullToRefreshLayout and set it up
27 mPullToRefreshLayout = (PullToRefreshLayout) findViewById(R.id.ptr
28 ActionBarPullToRefresh.from(this)
29 .allChildrenArePullable()
30 .listener(this)
31 .setup(mPullToRefreshLayout);
32
33 // Finally make the WebView load something...
34 mWebView.loadUrl("http://www.tutecentral.com (http://www.tutecentr
35
36 }
37
38 @Override
39 public void onRefreshStarted(View view) {
40 // TODO Auto-generated method stub
41
42 //////This method will Automatically call when
43 /////pull to refresh event occurs
44
45 mWebView.reload();
46 }
47
48 private class SampleWebViewClient extends WebViewClient {
49
50 @Override
51 public boolean shouldOverrideUrlLoading(WebView view, String url)
52 // Return false so the WebView loads the url
53 return false;
54 }
55
56 @Override
57 public void onPageFinished(WebView view, String url) {
58 super.onPageFinished(view, url);
59
60 // If the PullToRefreshAttacher is refreshing, make it as comp
61 if (mPullToRefreshLayout.isRefreshing()) {
62 mPullToRefreshLayout.setRefreshComplete();
63 }
64 }
65 }
66
67 }
We need to Internet permission to render the webview. Add following permission code to application
“AndroidManifest.xml” file
AndroidManifest.xml
1 <?xml version="1.0" encoding="utf-8"?>
2 <manifest xmlns:android="http://schemas.android.com/apk/res/android (http://schemas.and
3 package="com.tutecentral.pulltorefershexample"
4 android:versionCode="1"
5 android:versionName="1.0" >
6
7 <uses-permission android:name="android.permission.INTERNET" />
8
9 ....
I have used a “TextView” inside the ScrollView. You can use your own compatible android view with scroll view
behalf of “TextView”
activity_scroll_view
1 <uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout
2 xmlns:android="http://schemas.android.com/apk/res/android (http://schemas.android.
3 android:id="@+id/ptr_layout"
4 android:layout_width="match_parent"
5 android:layout_height="match_parent">
6
7 <ScrollView
8 android:id="@+id/scrollview"
9 android:layout_width="fill_parent"
10 android:layout_height="fill_parent"
11 android:padding="8dp"
12 android:scrollbarStyle="insideInset">
13
14 <!-- Below TextView used to update the screen. You can use any
15 android View with ScrollView. -->
16 <TextView
17 android:layout_width="fill_parent"
18 android:layout_height="wrap_content"
19 android:text="Pull Down to Add More Text"
20 android:id="@+id/scrollTextView"
21 />
22
23 </ScrollView>
24
25 </uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout>
Now you need to update the “ScrollViewActivity.java” class in your “src” folder. ScrollViewActivity extends
“BaseActivity” and implements “OnRefreshListener“. Update your class according to below coding.
ScrollViewActivity.java
1 package com.tutecentral.pulltorefreshexample;
2
3 import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
4 import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
5 import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
6 import android.os.AsyncTask;
7 import android.os.Bundle;
8 import android.view.View;
9 import android.widget.TextView;
10
11 public class ScrollViewActivity extends BaseActivity implements OnRefreshListener {
12
13 private PullToRefreshLayout mPullToRefreshLayout;
14 TextView textView;
15
16 @Override
17 protected void onCreate(Bundle savedInstanceState) {
18 super.onCreate(savedInstanceState);
19 setContentView(R.layout.activity_scroll_view);
20
21 textView=(TextView)findViewById(R.id.scrollTextView);
22
23 ///You will setup the action bar with pull to refresh layout
24 mPullToRefreshLayout = (PullToRefreshLayout) findViewById(R.id.ptr_layout)
25 ActionBarPullToRefresh.from(this)
26 .allChildrenArePullable()
27 .listener(this)
28 .setup(mPullToRefreshLayout);
29
30 }
31
32 @Override
33 public void onRefreshStarted(View view) {
34 // TODO Auto-generated method stub
35
36 /**
37 * Below AsyncTask class is used to update the view
38 * Asynchronously
39 */
40 new AsyncTask<Void, Void, Void>() {
41
42 @Override
43 protected Void doInBackground(Void... params) {
44 try {
45 Thread.sleep(5000);
46 //Here you can get the new text from DB or through a web ser
47 //Then YOu can pass it to onPostExecute() method to
48 //Update the view
49
50 } catch (InterruptedException e) {
51 e.printStackTrace();
52 }
53 return null;
54 }
55
56 @Override
57 protected void onPostExecute(Void result) {
58 super.onPostExecute(result);
59
60 //Here you can update the view
61 textView.setText(textView.getText().toString()+"--New Content Ad
62
63 // Notify PullToRefreshLayout that the refresh has finished
64 mPullToRefreshLayout.setRefreshComplete();
65 }
66 }.execute();
67 }
68
69 }
Now we can run this application in emulator or in a real android device to check. Below you can download the
sample codes for this program. See the video demonstration of this tutorial to how to follow this tutorial. I hope
this tutorial was helped you. If there is any problems or suggestions regarding this article please comment below.
Dont forget to Like our Facebook Page (https://www.facebook.com/tutecentral). Subscribe to our website, Google
Plus (https://plus.google.com/+Tutecentral/posts) and Youtube Channel (http://www.youtube.com/tutecentral) for
more tutorials. Thank you for visiting our website.
Video Demonstration
Android Pull To Refresh Tutorial
0:00 / 21:35
Downloads
Download the complete project
(http://downloads.tutecentral.com/wp-content/uploads/2014/02/PullToRefreshExample.zip)
Google
(http://www.tutecentral.com/android-pull-to-refresh/?share=google-plus-1&nb=1)
Facebook 49
(http://www.tutecentral.com/android-pull-to-refresh/?share=facebook&nb=1)
Twitter 5 More
(http://www.tutecentral.com/android-pull-to-refresh/?share=twitter&nb=1)
(https://plus.google.com/+AhamedIshak)Ahamed Ishak (https://plus.google.com/+AhamedIshak) Follow 0
(HTTP://WWW.FACEBOOK.COM/SHARER.PHP?U=HTTP%3A%2F%2FWWW.TUTECENTRAL.COM%2FANDROID-PULL-TO-
REFRESH%2F)
(HTTP://PLUS.GOOGLE.COM/SHARE?URL=HTTP://WWW.TUTECENTRAL.COM/ANDROID-PULL-TO-REFRESH/)
(HTTP://PINTEREST.COM/PIN/CREATE/BUTTON/?URL=HTTP://WWW.TUTECENTRAL.COM/ANDROID-PULL-TO-
REFRESH/&MEDIA=HTTP://WWW.TUTECENTRAL.COM/WP-CONTENT/UPLOADS/2014/03/PULL_TO_REFRESH_COVER.PNG)
Tw eet 5
Like 49
19
PREVIOUS ARTICLE
Android Swipe ListView (http://www.tutecentral.com/android-swipe-listview/)
NEXT ARTICLE
Android Custom Navigation Drawer (http://www.tutecentral.com/android-custom-navigation-drawer/)
(http://www.tutecentral.com/author/ishak-livegmail-com/)
Ahamed Ishak (http://www.tutecentral.com/author/ishak-livegmail-
com/)
I'm a self motivated person who love to learn new stuff and share them with others.
(https://plus.google.com/+AhamedIshak) (tutecentral)
SIMILAR ARTICLES
(http://www.tutecentral.com/restful-api-for-android-part-2/)
Restful API for Android using ASP.NET and SQL Server Part 2
(http://www.tutecentral.com/restful-api-for-android-part-2/)
Mar 28, 2014
(http://www.tutecentral.com/restful-api-for-android-part-1/)
Restful API for Android using ASP.NET and SQL Server Part 1
(http://www.tutecentral.com/restful-api-for-android-part-1/)
Mar 12, 2014
(http://www.tutecentral.com/android-custom-navigation-
drawer/)
Thank you for the tutorial. But I have a question. How do I implement this using a Fragment? What do
I have to do? Which java classes do I have to modify?
Please respond.
Thank you very much.
• Reply • Share ›
Restful API for Android using ASP.NET and Android Custom Navigation Drawer
SQL Server Part 1 93 comments • 2 months ago
10 comments • a month ago Ahamed Ishak — you can use Shared
Ahamed Ishak — Thank you.. Share this with Preference to store the value then retrieve from
your friends and colleagues.. Give a support.. fragment.
God Bless You...
Subscribe Add Disqus to your site
Enter your email address to subscribe to this website and receive notifications of new posts by email.
Email Address
Subscribe Us
SOCIAL
111 Fans
(https://www.facebook.com/tutecentral)
62 Subscribers
(https://plus.google.com/+Tutecentral)
12 Followers
(http://www.tutecentral.com/feed/)
90 Subscribers
(http://www.youtube.com/user/tutecentral)
Like Us (https://www.facebook.com/tutecentral)
Tute Central
Like
(http://creativecommons.org/licenses/by/4.0/deed.en_US)
TuteCentral.com by TuteCentral (http://www.tutecentral.com) is licensed under a Creative Commons Attribution
4.0 International License (http://creativecommons.org/licenses/by/4.0/deed.en_US).
(https://plus.google.com/+AhamedIshak?rel=author)