Android Pull To Refresh With Listview,WebView and ScrollView

pull to refresh android

How to use Pull to Refresh in Listview in Android ? Waiting for the Solution with source code yeah here we come up with this. Lets explore –

Here you can download the updated code with libraries.if not found please comment and give me your email address“.

Download Code

Using Pull to Refresh in Android we going to use external libraries i.e. “Android-PullToRefresh” , “ActionBar-PullToRefresh”. These libraries developed by Chrisbanes. Android-PullToRefresh is no longer maintained by  Chrisbanes so we going to use ActionBar-PullTo Refresh .

This Library is also compatible with “ActionBarSherlock” and it wants minimun API Level 14 . It is also supported with Lower API Levels and I’ll update you later.Lets move on towards tutorial –

Steps –

1). You have to Download two libraries from the given Urls and After downloading both the libraries you have to extract it and then import it to your eclipse. https://github.com/chrisbanes/ActionBar-PullToRefresh https://github.com/castorflex/SmoothProgressBar

2). After importing to your eclipse IDE it will show some errors so you have to solve it but i have already saved your time guyz you just need to download my source code which is working so good and cool .

NOTE –   SO, need not to download any libraries as above i mentioned ,you just need to download my source code and import it .

Here in my project i’have use four java files lets start with –

BaseActivity.java , This class will support all other Views like ListView,ScrollView,WebView. This Class will extend Activity Class and paste the below code in your Java File. BaseActivity.java

package androidarena.pulltorefreshexample;

import androidarena.pulltorefreshexample.R;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class BaseActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		

        // Add the Sample Fragment if there is one
        Fragment sampleFragment = getSampleFragment();
        if (sampleFragment != null) {
            getFragmentManager().beginTransaction()
                    .replace(android.R.id.content, sampleFragment).commit();
        }
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		
		  getMenuInflater().inflate(R.menu.base_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	
		// This method is for menu. This menu items will appear in all
		//activities extends this class. I have use this menus to navigate 
		//between activities. You can change this code as you wish 
		// 
		
		
		  switch (item.getItemId()) {
          case R.id.action_listview:
              Toast.makeText(this, "Pull to Refresh in ListView", Toast.LENGTH_SHORT).show();
              Intent i=new Intent(this,ListViewActivity.class);
              startActivity(i);
              
              return true;
          case R.id.action_scrollview:
              Toast.makeText(this, "Pull to Refresh in Scroll View", Toast.LENGTH_SHORT).show();
             
              Intent x=new Intent(this,ScrollViewActivity.class);
              startActivity(x);
              
              return true;
          case R.id.action_webview:
              Toast.makeText(this, "Pull to Refresh in Web View", Toast.LENGTH_SHORT).show();
              
              Intent z=new Intent(this,WebViewActivity.class);
              startActivity(z);
              
              return true;    
      }
		
		return super.onOptionsItemSelected(item);
	}

	
	//This method will override by child class. Then base class can get the fragment
	protected Fragment getSampleFragment() {
        return null;
    }
	
	
}

Now goto menu folder and create base_menu.xml . It is helpful for showing and hiding the views according to space .

if you are not having a knowledge of Android Menus go through with my Tutorial http://androidarena.co.in/working-on-android-menus-hidden-field/ .

base_menu.xml 

<?xml version="1.0" encoding="utf-8"?>


<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <!--
    You can change this as your requrement. I use this menu Item to navigate bettween 
    fragments. So I can show how ListView,WebView & ScrollView works with
    ActionBar Pull To Refresh Library  
      -->
    
    <item android:id="@+id/action_listview"
          android:title="ListView"
          android:showAsAction="ifRoom|withText" />

    <item android:id="@+id/action_webview"
          android:title="WebView"
          android:showAsAction="ifRoom|withText" />
    
        <item android:id="@+id/action_scrollview"
          android:title="ScrollVIew"
          android:showAsAction="ifRoom|withText" />

</menu>

activity_list_view.xml , paste below code in your main xml file i.e Listview . This file shows when your project launches and this is your first activity.

<?xml version="1.0" encoding="utf-8"?>

<uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ptr_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/ptr_listview"
        android:layout_height="match_parent"
        android:layout_width="match_parent" />

 

</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

package androidarena.pulltorefreshexample;

import java.util.ArrayList;
import java.util.List;

import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Fragment;
import android.app.ListFragment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

public class ListViewActivity extends BaseActivity {


	@Override
	 protected Fragment getSampleFragment() {
	        return new SimpleListFragment();
	    }
	
	
	public static class SimpleListFragment extends ListFragment implements OnRefreshListener
	{

		int i=0;
		
	private	PullToRefreshLayout mPullToRefreshLayout;
		
	
	ArrayAdapter<String> adapter;
	

	List<String> list;

    

		@Override
		public void onViewCreated(View view, Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			super.onViewCreated(view, savedInstanceState);
			
			list=new ArrayList<String>();
			int no=1;
			for(int i=0;i<5;i++)
			{
				list.add("Android Arena :"+no++);
			}
			
			  super.onViewCreated(view,savedInstanceState);
	            ViewGroup viewGroup = (ViewGroup) view;

	            // As we're using a ListFragment we create a PullToRefreshLayout manually
	            mPullToRefreshLayout = new PullToRefreshLayout(viewGroup.getContext());

	            // We can now setup the PullToRefreshLayout
	            ActionBarPullToRefresh.from(getActivity())
	                    // We need to insert the PullToRefreshLayout into the Fragment's ViewGroup
	                    .insertLayoutInto(viewGroup)
	                    // Here we mark just the ListView and it's Empty View as pullable
	                    .theseChildrenArePullable(android.R.id.list, android.R.id.empty)
	                    .listener(this)
	                    .setup(mPullToRefreshLayout);
			
		}

		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			super.onActivityCreated(savedInstanceState);
		
			adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, list);
			
		    // Set the List Adapter to display the sample items
            setListAdapter(adapter);
            setListShownNoAnimation(true);
		}
		
		
		@Override
		public void onRefreshStarted(View view) {
			// TODO Auto-generated method stub
			
			
			//setListShown(false); // This will hide the listview and visible a round progress bar 
			
			
			 new AsyncTask<Void, Void, Void>() {

	                @Override
	                protected Void doInBackground(Void... params) {
	                    try {
	                        Thread.sleep(5000); // 5 seconds 
	                        int itemNo=list.size();
	                        itemNo++;
	                     list.add("New Android Arena :"+itemNo);
		                	
	                       
	                        
	                    } catch (InterruptedException e) {
	                        e.printStackTrace();
	                    }
	                    return null;
	                }

	                @Override
	                protected void onPostExecute(Void result) {
	                    super.onPostExecute(result);
	              
                        
	                    adapter.notifyDataSetChanged();
	                    // Notify PullToRefreshLayout that the refresh has finished
	                    mPullToRefreshLayout.setRefreshComplete();

	            // if you set the "setListShown(false)" then you have to 
	            //uncomment the below code segment
	                    
//	                    if (getView() != null) {
//	                        // Show the list again
//	                        setListShown(true);
//	                    }
	                }
	            }.execute();
			
			
		}
		
		
		
	}
	


}
    

Now you have to create two xml files more i.e. activity_scroll_view.xml and activity_web_view.xml . Paste below code consecutively .

<uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ptr_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:id="@+id/scrollview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="8dp"
        android:scrollbarStyle="insideInset">

        
        <!-- Below TextView used to update the screen. You can use any
             android View with ScrollView.    -->
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Pull Down to Add More Text"
            android:id="@+id/scrollTextView"
            />

    </ScrollView>

</uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout>

 

<uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ptr="http://schemas.android.com/apk/res-auto"
    android:id="@+id/ptr_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        ptr:ptrViewDelegateClass="uk.co.senab.actionbarpulltorefresh.library.viewdelegates.WebViewDelegate" />

</uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout>

goto the “WebViewActivity.java” class and update your class according to below coding. This class should extends “BaseActivity”  and it should implements “OnRefreshListener”  WebViewActivity.java .

package androidarena.pulltorefreshexample;

import androidarena.pulltorefreshexample.R;

import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebViewActivity extends BaseActivity implements OnRefreshListener {

	 private PullToRefreshLayout mPullToRefreshLayout;

	    private WebView mWebView;
		
		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_web_view);
			
			 mWebView = (WebView) findViewById(R.id.webview);
		        mWebView.getSettings().setJavaScriptEnabled(true);
		        mWebView.setWebViewClient(new SampleWebViewClient());

		        // Now find the PullToRefreshLayout and set it up
		        mPullToRefreshLayout = (PullToRefreshLayout) findViewById(R.id.ptr_layout);
		        ActionBarPullToRefresh.from(this)
		                .allChildrenArePullable()
		                .listener(this)
		                .setup(mPullToRefreshLayout);

		        // Finally make the WebView load something...
		        mWebView.loadUrl("http://www.androidarena.co.in");
			
		}

		

		@Override
		public void onRefreshStarted(View view) {
			// TODO Auto-generated method stub
			
			//////This method will Automatically call when 
			/////pull to refresh event occurs 
			
			  mWebView.reload();
		}
		
		  private class SampleWebViewClient extends WebViewClient {

		        @Override
		        public boolean shouldOverrideUrlLoading(WebView view, String url) {
		            // Return false so the WebView loads the url
		            return false;
		        }

		        @Override
		        public void onPageFinished(WebView view, String url) {
		            super.onPageFinished(view, url);

		            // If the PullToRefreshAttacher is refreshing, make it as complete
		            if (mPullToRefreshLayout.isRefreshing()) {
		                mPullToRefreshLayout.setRefreshComplete();
		            }
		        }
		    }
		


}

Now create ScrollViewActivity.java and ScrollViewActivity extends “BaseActivity” and implements “OnRefreshListener“. Update your class according to below coding.

package androidarena.pulltorefreshexample;

import androidarena.pulltorefreshexample.R;

import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class ScrollViewActivity extends BaseActivity implements OnRefreshListener {

	 private PullToRefreshLayout mPullToRefreshLayout;
	   TextView textView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_scroll_view);
	   
		textView=(TextView)findViewById(R.id.scrollTextView);
		
		///You will setup the action bar with pull to refresh layout 
		mPullToRefreshLayout = (PullToRefreshLayout) findViewById(R.id.ptr_layout);
		ActionBarPullToRefresh.from(this)
              .allChildrenArePullable()
              .listener(this)
              .setup(mPullToRefreshLayout);
		
	}


	@Override
	public void onRefreshStarted(View view) {
		// TODO Auto-generated method stub
	
		/**
		 * Below  AsyncTask class is used to update the view 
		 * Asynchronously 
		 */
		new AsyncTask<Void, Void, Void>() {

	            @Override
	            protected Void doInBackground(Void... params) {
	                try {
	                    Thread.sleep(5000);
	                    //Here you can get the new text from DB or through a web service
	                    //Then YOu can pass it to onPostExecute() method to
	                    //Update the view 
	                    
	        
	                    
	                } catch (InterruptedException e) {
	                    e.printStackTrace();
	                }
	                return null;
	            }

	            @Override
	            protected void onPostExecute(Void result) {
	                super.onPostExecute(result);

	                //Here you can update the view 
	                textView.setText(textView.getText().toString()+"--New Content Added");
	              
	                // Notify PullToRefreshLayout that the refresh has finished
	                mPullToRefreshLayout.setRefreshComplete();
	            }
	        }.execute();
	}


}

Now AndroidManifest.xml file , we need to give INTERNET permission only and make sure you write minimum SDK 14 .

OutPut –

Pull to Refresh Listview     WebView

Webview

ScrollView

Now Run your project and scroll it and you will see the loading bar . any suggestions , errors do comment here . enjoy and Happy coding 😛    

10 thoughts on “Android Pull To Refresh With Listview,WebView and ScrollView

  1. nkssrikanth

    Thanks for the tutorial. I have followed everything but on executing “Unfortunately your app has closed” this android runtime error is popping. How to fix this?

    Thanks.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *