How to used Recycler View with Swipe Refresh in AndroidX

Hiii developer in this AndroidX Example, I am Share how to use How to used Recycler View with Swipe Refresh in AndroidX. In this Android Example, I am using all google design material library with API Level 29.

Also, you can read in this article show Rest API data in recycler view and using swipe refresh. first, off we can use a network library to forget the response from the server with a JSONArray. TO parses JSON data to a list with Recycler View in AndroidX.

The topic of this Article:-

  1. JSON Parsing with Rest API for Server.
  2. How TO Parsing JSONArrary list Response for Server API.
  3. Recycler View List in AndroidX.
  4. How to used Swipe refresh list Data in AndroidX.
  5. JSON Volley with Array List.
  6. How to used Recycler View with Swipe Refresh in AndroidX.

Let’s Start on the Solution:- create a new AndroidX project and add these dependencies in your App base build.gradle.

Add Android Dependency : 

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation "androidx.drawerlayout:drawerlayout:1.0.0"
    implementation 'com.google.android.material:material:1.1.0'
    implementation "androidx.coordinatorlayout:coordinatorlayout:1.1.0"
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.android.volley:volley:1.1.0'
    implementation 'de.hdodenhof:circleimageview:2.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'

Step 2: Add Recycler view list and swipe refresh in XML Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".Activitys.Event_Activity">


    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/refresh_Events"
        android:layout_height="match_parent"
        android:layout_width="match_parent">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/Event_RecyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" />

    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

</LinearLayout>

Step 3: Create A CardView Layout.

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/Event_CardView"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    card_view:cardCornerRadius="3dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RelativeLayout
            android:id="@+id/widget30"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

        <ImageView
            android:id="@+id/EventList_Image"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:src="@drawable/baseline_style_24"
            android:background="@color/White"
            android:contentDescription="@null" />

            <LinearLayout
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:background="@color/White"
                android:layout_margin="10dp"
                android:padding="5dp"
                android:gravity="center"
                android:layout_alignParentRight="true"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/EventDate"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:text=""
                    android:textAppearance="@style/body" />

                <TextView
                    android:id="@+id/EventMonth"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:singleLine="true"
                    android:gravity="center"
                    android:padding="2dp"
                    android:text=""
                    android:textAppearance="@style/small_indic" />


            </LinearLayout>



        </RelativeLayout>


            <TextView
                android:id="@+id/EventId"
                android:textColor="@color/Black"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone"
                />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="5dp">

            <TextView
                android:id="@+id/EventCategory"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAppearance="@style/small_indic"
                android:gravity="top"
                android:singleLine="true"
                android:padding="2dp"
                android:text="" />

            <TextView
                android:id="@+id/EventName"
                android:textColor="@color/Black"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAppearance="@style/name"
                android:textStyle="bold"
                android:gravity="top"
                android:singleLine="true"
                android:padding="2dp"
                android:text=" Testing " />

            <TextView
                android:id="@+id/EventDescription"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAppearance="@style/small_body"
                android:gravity="top"
                android:padding="2dp"
                android:text=" "/>


        </LinearLayout>
    </LinearLayout>
</androidx.cardview.widget.CardView>

Step 4: Open Your Main java file Implement Rest API Data.

 

public class Event_Activity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private EventAdupter rAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_);
        swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.refresh_Events);
        swipeRefreshLayout.setOnRefreshListener(this);

            EventList();

        androidx.appcompat.app.ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("RecylerView List");
    }

    // Get Request For JSONObject
    public void EventList(){
        final ProgressDialog loading = new ProgressDialog(Event_Activity.this);
        loading.setMessage("Please Wait...");
        loading.setCanceledOnTouchOutside(false);
        loading.show();

        JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, ConfiURL.Event_List_URL, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.d("Response", response.toString());

                    try {
                        Log.d("JSON", String.valueOf(response));
                        loading.dismiss();
                        swipeRefreshLayout.setRefreshing(false);
                        String Error = response.getString("httpStatus");
                        if(Error.equals("OK")){
                            JSONArray jArray = response.getJSONArray("body");
                            if (jArray.length() == 0) {
                                /*of array length is 0 then show alert dialog if
                                 * array is not 0 then go else*/
                                ContextThemeWrapper ctw = new ContextThemeWrapper( Event_Activity.this, R.style.Theme_AlertDialog);
                                final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(ctw);
                                alertDialogBuilder.setTitle("Message");
                                alertDialogBuilder.setMessage(" No data found please try after sometime ");
                                alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {

                                    }
                                });
                                alertDialogBuilder.show();
                            } else {
                                onPostExecute(jArray);

                            }


                        }else if(Error.equals("")||Error.equals(null)){

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        loading.dismiss();
                        swipeRefreshLayout.setRefreshing(false);
                    }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                loading.dismiss();
                swipeRefreshLayout.setRefreshing(false);
                VolleyLog.d("Error", "Error: " + error.getMessage());
                Toast.makeText(Event_Activity.this, "" + error.getMessage(), Toast.LENGTH_SHORT).show();

            }
        })
        {
            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Authorization", Token);
                return headers;
            }
        };
        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        queue.add(req);
    }


    protected void onPostExecute(JSONArray result) {

        //this method will be running on UI thread
        List<DataObject> data = new ArrayList<>();
        data.equals(null);
        try {
            // Extract data from json and store into ArrayList as class objects
            for (int i = 0; i < result.length(); i++) {
                JSONObject json_data = result.getJSONObject(i);
                DataObject report = new DataObject();
                report.mText1 = json_data.getString("id");
                report.mText2 = json_data.getString("title");
                report.mText3 = json_data.getString("desciption");
                report.mText4 = json_data.getString("eventDate");
                report.mText5 = json_data.getString("createdByName");
                report.mText6 = json_data.getString("categoryName");
                report.mText7 = json_data.getString("city");
                report.mText8 = json_data.getString("state");
                report.mText9 = json_data.getString("pincode");
                report.Image = json_data.getString("thumbnailImageUrl");
                data.add(report);
            }
            // Setup and Handover data to recyclerview
            recyclerView = (RecyclerView) findViewById(R.id.Event_RecyclerView);
            rAdapter = new EventAdupter(Event_Activity.this, data);
            recyclerView.setAdapter(rAdapter);
            GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(),2);
            recyclerView.setLayoutManager(gridLayoutManager);
//            recyclerView.setLayoutManager(new LinearLayoutManager(Event_Activity.this));
            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

                    super.onScrolled(recyclerView, dx, dy);
                }
            });


        } catch (JSONException e) {
            Toast.makeText(Event_Activity.this, e.toString(), Toast.LENGTH_LONG).show();
        }
    }


    @Override
    public void onRefresh() {
        EventList();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                //Write your logic here
                Intent intent=new Intent(Event_Activity.this, Home_Activity.class);
                startActivity(intent);
                finish();
            default:
                return super.onOptionsItemSelected(item);
        }
    }


    public void onBackPressed(){
        Intent intent=new Intent(Event_Activity.this, Home_Activity.class);
        startActivity(intent);
        finish();
    }
}

Step 5: Create A RecyclerView Setter Getter java Class.

public class DataObject {
    public String mText1;
    public String mText2;
    public String mText3;
    public String mText4;
    public String mText5;
    public String mText6;
    public String mText7;
    public String mText8;
    public  String mText9;
    public String Image;
    public String Image1;
    private boolean isSelected;

    public String getImage() {
        return Image;
    }

    public void setImage(String image) {
        Image = image;
    }

    public String getImage1() {
        return Image1;
    }

    public void setImage1(String image) {
        Image1 = image;
    }

    public String getmText1() {
        return mText1;
    }

    public void setmText1(String mText1) {
        this.mText1 = mText1;
    }

    public String getmText2() {
        return mText2;
    }

    public void setmText2(String mText2) {
        this.mText2 = mText2;
    }

    public String getmText3() {
        return mText3;
    }

    public void setmText3(String mText3) {
        this.mText3 = mText3;
    }

    public String getmText4() {
        return mText4;
    }

    public void setmText4(String mText4) {
        this.mText4 = mText4;
    }

    public String getmText5() {
        return mText5;
    }

    public void setmText5(String mText5) {
        this.mText5 = mText5;
    }
    public String getmText6() {
        return mText6;
    }

    public void setmText6(String mText6) {
        this.mText6 = mText6;
    }

    public String getmText7() {
        return mText7;
    }

    public void setmText7(String mText7) {
        this.mText7 = mText7;
    }
    public String getmText8() {
        return mText8;
    }

    public void setmText8(String mText8) {
        this.mText8 = mText8;
    }

    public String getmText9() {
        return mText9;
    }

    public void setmText9(String mText9) {
        this.mText9 = mText9;
    }
    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean isSelected) {
        this.isSelected = isSelected;
    }

}

Step 6: Create a RecylerViewAdapter java class.

 

public class EventAdupter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private LayoutInflater inflater;
    List<DataObject> data = Collections.emptyList();
    private ArrayList<DataObject> arraylist;
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");


    private int lastPosition = -2;
    public EventAdupter(Context context, List<DataObject> data) {
        this.context = context;
        // inflater = LayoutInflater.from(context);
        this.data = data;
        this.arraylist = new ArrayList<DataObject>();
        this.arraylist.addAll(data);
    }

    // Inflate the layout when viewholder created
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.from(parent.getContext()).
                inflate(R.layout.event_card, parent, false);
        EventAdupter.MyHolder holder = new EventAdupter.MyHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        // Get current position of item in recyclerview to bind data and assign values from list
        EventAdupter.MyHolder myHolder = (EventAdupter.MyHolder) holder;
        DataObject current = data.get(position);
        myHolder.EventId.setText(current.getmText1());
        myHolder.EventName.setText(current.getmText2());
        myHolder.EventDescription.setText(current.getmText7()+", "+current.getmText8()+" "+current.getmText9());
        myHolder.EventCategory.setText(current.getmText6());
        String date=current.getmText4();
        try {
            Date d = dateFormat.parse(date);
            DateFormat Date = new SimpleDateFormat("dd");
            DateFormat Date1 = new SimpleDateFormat("MMM");
            myHolder.EventDate.setText(String.valueOf(Date.format(d)));
            myHolder.EventMonth.setText(String.valueOf(Date1.format(d)));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        String userImage = current.getImage();
            if (userImage.isEmpty()||userImage.equals(null)||userImage.equals("")) {

            } else {
                Picasso.with(context)
                        .load(userImage)
                        .placeholder(R.drawable.ic_calander_24dp)
                        .fit()
                        .into( myHolder.EventList_Image);
            }
        setAnimation(myHolder.itemView, position);

    }

    private void setAnimation(View viewToAnimate, int position)
    {
        // If the bound view wasn't previously displayed on screen, it's animated
        if (position > lastPosition)
        {
            Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
            viewToAnimate.startAnimation(animation);
            lastPosition = position;
        }
    }

    // Filter Class
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        data.clear();
        if (charText.length() == 0) {
            data.addAll(arraylist);
        } else {
            for (DataObject wp : arraylist) {
                if (wp.getmText2().toLowerCase(Locale.getDefault()).contains(charText)) {
                    data.add(wp);
                }
            }
        }
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return data.size();
    }


    class MyHolder extends RecyclerView.ViewHolder {

        TextView EventName;
        TextView EventId;
        TextView EventDescription;
        ImageView EventList_Image;
        TextView EventCategory;
        TextView EventDate;
        TextView EventMonth;
        CardView CV;

        // create constructor to get widget reference
        public MyHolder(View itemView) {
            super(itemView);
            CV = (CardView) itemView.findViewById(R.id.Event_CardView);
            EventName = (TextView) itemView.findViewById(R.id.EventName);
            EventId = (TextView) itemView.findViewById(R.id.EventId);
            EventList_Image = (ImageView) itemView.findViewById(R.id.EventList_Image);
            EventDescription = (TextView)itemView.findViewById(R.id.EventDescription);
            EventCategory = (TextView)itemView.findViewById(R.id.EventCategory);
            EventDate = (TextView)itemView.findViewById(R.id.EventDate);
            EventMonth = (TextView)itemView.findViewById(R.id.EventMonth);

            CV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
        }
    }
}

After complete these steps run your project and Test output…..

 

You may also like...