NoobsPlanet

Register a free account today to become a member! Once signed in, you'll be able to participate on this site by adding your own topics, posts and unlimited download to our resources, as well as connect with other members through your own private inbox!

Android RecyclerView Swipe Down To Refresh

noobsplanet

Active member
Staff member
Administrator
Moderator
882
883
884


In Android while fetching data from the server, we sometimes need to use Swipe to refresh to change the data on RecyclerView. If you haven't seen the previous guide then please look previous guide, Fetching Data and SearchView in RecyclerView .For example when you lost the network connection and fails to load the data. Then the user needs to close the app and reopen it to make the network connection since we've used a network connection call in onCreateView() method right? But by using SwipeRefreshLayout users, no longer need to close the app instead he/she can just tap down and volley will ask for response which is used on real time app like Viber, messenger, Whats app, etc.

The first scenario would be replacing the RecyclerView parent with SwipeRefreshLayout in activity_main.xml that will look like below:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/swipeRefreshLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

   <android.support.v7.widget.RecyclerView
       android:id="@+id/recyclerView"
       android:layout_width="wrap_content"
       android:layout_height="match_parent">
   </android.support.v7.widget.RecyclerView>

</android.support.v4.widget.SwipeRefreshLayout>
Now, on your MainActivity.java, call SwipeRefreshLayout by swipeRefreshLayout=findViewById(R.id.swipeRefreshLayout); and set the progress color, I added the following four colors, you may change as you like.
Changing Progress Color:
swipeRefreshLayout.setColorSchemeColors(getResources().getColor(android.R.color.holo_blue_bright),
        getResources().getColor(android.R.color.holo_green_light),
        getResources().getColor(android.R.color.holo_orange_light),
        getResources().getColor(android.R.color.holo_red_light));
Then make post() function and inside that call MakeVolleyConnection(); method instead of calling it directly because calling it from SwipeRefreshLayout.post(), displays progress bar until data is received.
MainActivity.java:
swipeRefreshLayout.post(new Runnable() {
    @Override
    public void run() {
        swipeRefreshLayout.setRefreshing(true);
        MakeVolleyConnection();
    }
});
Now, Implement onRefreshListener() which will be called when users swipe down RecyclerView
Calls on swipe down:
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
    @Override
    public void onRefresh() {
        swipeRefreshLayout.setRefreshing(true);
        MakeVolleyConnection();
    }
});
That's all. The final MainActivity.java class will look like below :
MainActivity.java:
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

public class MainActivity extends AppCompatActivity {
    List<RecyclerViewData> recyclerViewDataList;
    RecyclerView recyclerView;
    private static final String TAG = "apple";
    private SearchView searchView;
    private RVAdapter rvAdapter;
    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setTitle("Employee List");


        recyclerView = findViewById(R.id.recyclerView);
        swipeRefreshLayout=findViewById(R.id.swipeRefreshLayout);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);

        swipeRefreshLayout.setColorSchemeColors(getResources().getColor(android.R.color.holo_blue_bright),
                getResources().getColor(android.R.color.holo_green_light),
                getResources().getColor(android.R.color.holo_orange_light),
                getResources().getColor(android.R.color.holo_red_light));

        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
                MakeVolleyConnection();
            }
        });

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipeRefreshLayout.setRefreshing(true);
                MakeVolleyConnection();
            }
        });
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.search_menu, menu);

        MenuItem menuItem=menu.findItem(R.id.search_menu);
        searchView= (SearchView) menuItem.getActionView();
        searchView.setQueryHint("Search By First Name");
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
               return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                newText = newText.toUpperCase();
                List<RecyclerViewData> newList = new ArrayList<>();
                for (RecyclerViewData PItem : recyclerViewDataList) {
                    String name = PItem.getFirstname().toUpperCase();
                    if (name.contains(newText))
                        newList.add(PItem);
                }
                if (rvAdapter != null) {
                    rvAdapter.setFilter(newList);
                }
                return true;
            }
        });
        return true;
    }



    private void MakeVolleyConnection() {
        recyclerViewDataList = new ArrayList<>();
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                "https://reqres.in/api/users?page=1", null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (swipeRefreshLayout.isRefreshing()){
                        swipeRefreshLayout.setRefreshing(false);
                    }
                    JSONArray dataArray = response.getJSONArray("data");
                    for (int i = 0; i < dataArray.length(); i++) {
                        JSONObject userData = dataArray.getJSONObject(i);
                        RecyclerViewData recyclerViewData = new RecyclerViewData();
                        recyclerViewData.setId(userData.getInt("id"));
                        recyclerViewData.setFirstname(userData.getString("first_name"));
                        recyclerViewData.setLastname(userData.getString("last_name"));
                        recyclerViewData.setAvatar(userData.getString("avatar"));
                        recyclerViewDataList.add(recyclerViewData);

                    }
                    rvAdapter = new RVAdapter(recyclerViewDataList, MainActivity.this);
                    recyclerView.setAdapter(rvAdapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (swipeRefreshLayout.isRefreshing()){
                    swipeRefreshLayout.setRefreshing(false);
                }
                Toast.makeText(MainActivity.this, ""+error.networkResponse,Toast.LENGTH_SHORT).show();
            }
        });

        MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
    }
}
881
 
Last edited:
Top