Android material design Programming Blog

Pull down to fetch fresh data from PHP or JSON file into RecyclerView using Android Swipe Refresh Layout and AsyncTask.

When you swipe down to the screen, you likely to see a rounded button with refresh icon spinning indicating data is loading on the background. In Android, it’s easy to implement that android pull to refresh layout. Let’s see how to do that.

How to add swipe/pull to refresh layout?

Adding pull to refresh layout involves following files.

activity_main.xml

The SwipeRefreshLayout widget is supported in android support version 4, the code for adding widget is highlighted below and make sure that your RecyclerView widget is inside SwipeRefreshLayout widget.

MainActivity.java

Define the variable for SwipeRefreshLayout view on top of the class.

SwipeRefreshLayout mSwipeRefreshLayout;

Copy the below-highlighted code into your oncreate() method of MainActivity.java class. Here we are getting the reference to SwipeRefreshLayout widget and setting listener to listen for swipe down refresh and when the user swipes down to a screen, call AsyncTask to fetch fresh data.

We have made Swipe layout visible when the user swipes the screen. It continues to visible even after data loaded so we need to hide the layout after our data loaded from the server. At the end of your onPostExecute(String result) method add below code to hide SwipeRefreshLayout.

mSwipeRefreshLayout.setRefreshing(false);

Finally, to test your application remove some rows from JSON file or add some rows to it. Now, in your phone, swipe vertically down to see updated data.

Hi Guru thank you for the source code and tutorial. I manage to run the app. but i am wondering about the image. fish image which I would like to replace with my own images from my server. I want to pass my image as an url please help me achieve with thank you.

In our JSON file you like to see image name as 1.jpg, 2.jpg and so on..., they are actually image from URL, rather than repeating URL again like http://www.example.com/images/1.jpg, http://www.example.com/images/2.jpg and so on..., i specified only image name and folder path is attached while retrieving image. The sample code is shown below which i used in AdapterFish.java and for your reference image folder path is highlighted.

What I found glide supports fetching, decoding, and displaying video stills, images, and animated GIFs. But how could I change it to display picture from mysql? This code use to find picture from file test/images right? Im still looking forward tutorial fetch picture from mysql to search example.. 🙂