Android Pull to Refresh RecyclerView with JSON PHP

Android Pull to Refresh RecyclerView with JSON PHP
Rate this post

Android Pull to Refresh RecyclerView with JSON PHP

در این آموزش نحوه swipe کردن RecyclerView با استفاده از اطلاعات json رو مرور میکنیم.

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 screen, you likely to see rounded button with refresh icon spinning indicating data is loading on background. In android it’s easy to implement that android pull to refresh layout. Let’s see how to do that.

از اینجا میتونین قطعه کد این آموزش رو دانلود کنین

Android Pull to Refresh RecyclerView with JSON PHP

activity_main.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">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swifeRefresh"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/fishPriceList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        />
    </android.support.v4.widget.SwipeRefreshLayout>

</LinearLayout>

 

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 reference to SwipeRefreshLayout widget and setting listener to listen for swipe down refresh and when user swipe down to screen, call AsyncTask to fetch fresh data.

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Swipe Refresh Layout
        mSwipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swifeRefresh);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new AsyncFetch().execute();
            }
        });
        //Make call to AsyncTask
        new AsyncFetch().execute();
    }

We have made Swipe layout visible when user swipes the screen. It continues to visible even after data loaded so we need to hide the layout after our data loaded from 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 it. Now, in your phone, swipe vertically down to see updated data.

 

Android Pull to Refresh RecyclerView with JSON PHP

Share