Android tutorial

Android Recycler view list with Swipe Refresh and Search bar in recycler list

Android Recycler view list with Swipe Refresh and Search bar in recycler list

In this article, I am sharing how to used recycler view in android and Swipe Refresh list to refresh the recycler view list with a search bar to search any item in the recycler list easy. It’s very easy to implement these just follow the simple step t implement the recycler view list with card view to attractive design. And I am getting data with the API  and implement the using volley network library to hit the API  for Information.

 

Step 1: First one to  Start Android Studio

Step 2 :  Seconds step to Create a New Project Project ClickOn  ==> File  ==> NEW ==> New Project

Step 3: After create on your project open your java file and XML file and you can just cope with the code and paste on your file and run your project.

Step 4: Add Library In build.gradle

compile 'com.android.support:appcompat-v7:27.0.2'
compile 'com.android.support:design:27.0.2'
compile 'com.android.support:support-v4:27.0.2'
compile 'de.hdodenhof:circleimageview:2.1.0'
compile 'com.android.support:cardview-v7:27.0.2'
compile 'com.android.support:recyclerview-v7:27.0.2'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.android.volley:volley:1.0.0'
testCompile 'junit:junit:4.12'

Step 5:  Open Your XML file and add the code to your XML file.

activity_home.xml

<?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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
   >
    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/Customer_refreshList"
        android:layout_height="match_parent"
        android:layout_width="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/Customer_recycler_LeadsList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="vertical" />
    </android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>

Step 6:  Open Your Java File and Implement these

In java class implements recycler view and get and set data throw to API and show on this list using Adapter and set data to card view.

Home.Java

public class Home extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener,SearchView.OnQueryTextListener {

    public static final String KEY_Mobile = "mobile";

    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private CustomerAdupter rAdapter;
    public static String EMAIL;
   

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

    SessionManagement sessionManagement =new SessionManagement();
    Boolean checkLogin = sessionManagement.getLogin(this);
    EMAIL = sessionManagement.getSavedEmail(this);
    if (!checkLogin){
        Intent intent = new Intent(this,LogIn.class);
        startActivity(intent);
    }
    if (AppStatus.getInstance(this).isOnline()) {
        CustomerList();
    } else {
        ContextThemeWrapper ctw = new ContextThemeWrapper( Home.this, R.style.Theme_AlertDialog);
        final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
        alertDialogBuilder.setTitle("No internet connection");
        alertDialogBuilder.setMessage("Check your  internet connection or try again");
        alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {

            }
        });
        alertDialogBuilder.show();
    }
   
    swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.Customer_refreshList);
    swipeRefreshLayout.setOnRefreshListener(this);
}

private void CustomerList() {
        // progress Dialog
       final ProgressDialog loading = new ProgressDialog(Home.this);
        loading.setMessage("Please Wait...");
        loading.show();
// json response code
       StringRequest stringRequest = new StringRequest(Request.Method.POST, ConfiURL.Customer_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            Log.d("JSON", response);
                            loading.dismiss();
                            swipeRefreshLayout.setRefreshing(false);
                            JSONObject jsonObject = new JSONObject(response);
                            String error_status = jsonObject.getString("error");
                            if (error_status.equals("true")) {
                                String error_msg = jsonObject.getString("msg");
//                                Toast.makeText(LogIn.this, error_msg, Toast.LENGTH_SHORT).show();
                               ContextThemeWrapper ctw = new ContextThemeWrapper( Home.this, R.style.Theme_AlertDialog);
                                final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(ctw);
                                alertDialogBuilder.setTitle("Message");
                                alertDialogBuilder.setMessage(error_msg);
                                alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {

                                    }
                                });
                                alertDialogBuilder.show();
                            } else {
                                JSONArray jArray = jsonObject.getJSONArray("Customers");
                                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( Home.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 ");
                                    alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {

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

                                }

                            }

                        } catch (Exception e) {
                            loading.dismiss();
                            swipeRefreshLayout.setRefreshing(false);
                            Log.d("Tag", e.getMessage());

                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        loading.dismiss();
                        swipeRefreshLayout.setRefreshing(false);
                        if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                            ContextThemeWrapper ctw = new ContextThemeWrapper( Home.this, R.style.Theme_AlertDialog);
                            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
                            alertDialogBuilder.setTitle("No connection");
                            alertDialogBuilder.setMessage(" Network Timeout  error please try again ");
                            alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                            alertDialogBuilder.show();
                        } else if (error instanceof AuthFailureError) {
                            ContextThemeWrapper ctw = new ContextThemeWrapper( Home.this, R.style.Theme_AlertDialog);
                            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
                            alertDialogBuilder.setTitle("Connection Error");
                            alertDialogBuilder.setMessage(" Connection authentication failure  error please try again");
                            alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                            alertDialogBuilder.show();
                            //TODO
                       } else if (error instanceof ServerError) {
                            ContextThemeWrapper ctw = new ContextThemeWrapper( Home.this, R.style.Theme_AlertDialog);
                            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
                            alertDialogBuilder.setTitle("Connection Error");
                            alertDialogBuilder.setMessage("Connection error please try again");
                            alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                            alertDialogBuilder.show();
                            //TODO
                       } else if (error instanceof NetworkError) {
                            ContextThemeWrapper ctw = new ContextThemeWrapper( Home.this, R.style.Theme_AlertDialog);
                            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
                            alertDialogBuilder.setTitle("Connection Error");
                            alertDialogBuilder.setMessage("Network connection error please try again");
                            alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                            alertDialogBuilder.show();
                            //TODO
                        } else if (error instanceof ParseError) {
                            ContextThemeWrapper ctw = new ContextThemeWrapper( Home.this, R.style.Theme_AlertDialog);
                            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
                            alertDialogBuilder.setTitle("Error");
                            alertDialogBuilder.setMessage("Parse error");
                            alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                            alertDialogBuilder.show();
                        }
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(KEY_Mobile,EMAIL);
                return map;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
    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("cstmr_id");
                report.mText2 = json_data.getString("name");
                report.mText3 = json_data.getString("address");
                report.mText4 = json_data.getString("mobile");
                report.mText5=json_data.getString("last_delivery_time");
                report.mText6=json_data.getString("last_delivery_timing");
                data.add(report);
            }
            // Setup and Handover data to recyclerview
           recyclerView = (RecyclerView) findViewById(R.id.Customer_recycler_LeadsList);
            rAdapter = new CustomerAdupter(Home.this, data);
            recyclerView.setAdapter(rAdapter);
            recyclerView.setLayoutManager(new LinearLayoutManager(Home.this));

        } catch (JSONException e) {
            Toast.makeText(Home.this, e.toString(), Toast.LENGTH_LONG).show();
        }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
   getMenuInflater().inflate(R.menu.home, menu);
    // Retrieve the SearchView and plug it into SearchManager
   final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
    SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setOnQueryTextListener(this);

    return true;
}
@Override
public void onRefresh() {
    CustomerList();
}
@Override
public boolean onQueryTextSubmit(String query) {
    return false;
}
@Override
public boolean onQueryTextChange(String newText) {
    if(rAdapter==null){
    }else {
        String text = newText;
        rAdapter.filter(text);
    }
    return false;
}
}

Step 7:  Create a Menu file home for the Search bar.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_search"
        android:icon="@drawable/search"
        android:title="search"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="ifRoom|collapseActionView" />
</menu>

Step 8: Create Adapter  CustomerAdupter

public class CustomerAdupter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Context context;
    private LayoutInflater inflater;
    List<DataObject> data = Collections.emptyList();
    private ArrayList<DataObject> arraylist;
    private int lastPosition = -1;
    public CustomerAdupter(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.customer_card_view, parent, false);
        CustomerAdupter.MyHolder holder = new CustomerAdupter.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
       CustomerAdupter.MyHolder myHolder = (CustomerAdupter.MyHolder) holder;
        DataObject current = data.get(position);
        myHolder.IDLeads.setText(current.getmText1());
        myHolder.customer_name.setText(current.getmText2());
        myHolder.customer_address.setText("Address:  "+current.getmText3());
        myHolder.coustomer_mobile.setText(current.getmText4());
        myHolder.diliverDate.setText("Date  "+current.getmText5());
        myHolder.diliverTime.setText("Time  "+current.getmText6());
        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;
        }
    }
    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 customer_name;
        TextView coustomer_mobile;
        TextView customer_address;
        TextView diliverTime;
        TextView diliverDate;
        TextView IDLeads;
        CardView CV;
        // create constructor to get widget reference
       public MyHolder(View itemView) {
            super(itemView);
            CV=(CardView)itemView.findViewById(R.id.card_view1);
            IDLeads=(TextView)itemView.findViewById(R.id.cstmr_id);
            customer_name = (TextView) itemView.findViewById(R.id.customer_name);
            coustomer_mobile = (TextView) itemView.findViewById(R.id.coustomer_mobile);
            customer_address = (TextView) itemView.findViewById(R.id.customer_address);
            diliverTime=(TextView)itemView.findViewById(R.id.Customer_timing);
            diliverDate=(TextView)itemView.findViewById(R.id.Customer_Date);
            CV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String ProId=IDLeads.getText().toString().trim();
                    Intent intent=new Intent(context,Delivery_Form.class);
                    intent.putExtra("ProId",ProId);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK| Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                }
            });
        }
    }
}

 

Step 9: Create A Java Class for get and set value object 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 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;
    }  
}
Step 10: Create CardView for design XML.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/card_view1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardBackgroundColor="@color/colorAccent"
    card_view:cardCornerRadius="0dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">
        <de.hdodenhof.circleimageview.CircleImageView
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/ProfileImage"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_gravity="center"
            android:src="@drawable/ic_perm_identity_white_24dp"
            app:civ_border_width="8dp"
            app:civ_fill_color="@color/colorPrimaryDark"
            app:civ_border_color="@color/colorPrimaryDark"/>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:padding="2dp"
            android:orientation="vertical">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

            <TextView
                android:id="@+id/customer_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:padding="0dp"
                android:layout_weight="1"
                android:singleLine="true"
                android:textAppearance="?android:textAppearanceMedium"
                android:textColor="@color/white"
                android:text=" "/>


            <TextView
                android:id="@+id/coustomer_mobile"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="0dp"
                android:layout_weight="1"
                android:gravity="center"
                android:textAppearance="?android:textAppearanceSmall"
                android:singleLine="true"
                android:textColor="@color/white"
                android:text=""/>
            </LinearLayout>
            <TextView
                android:id="@+id/customer_address"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="0dp"
                android:textAppearance="?android:textAppearanceSmall"
                android:textColor="@color/white"
                android:text=""/>

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

                <TextView
                    android:id="@+id/Customer_timing"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:padding="0dp"
                    android:singleLine="true"
                    android:layout_weight="1"
                    android:textAppearance="?android:textAppearanceSmall"
                    android:textColor="@color/colorPrimaryDark"
                    android:text=" "/>


                <TextView
                    android:id="@+id/Customer_Date"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:padding="0dp"
                    android:textAppearance="?android:textAppearanceSmall"
                    android:layout_weight="1"
                    android:singleLine="true"
                    android:textColor="@color/colorPrimaryDark"
                    android:text=""/>
            </LinearLayout>

            <TextView
                android:id="@+id/cstmr_id"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:visibility="gone"
                android:textColor="@color/colorAccent"
                android:textAppearance="?android:textAppearanceSmall"
                android:text=""/>

        </LinearLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>

 

 

1 Comment

  1. This is very fascinating, You’re an excessively skilled blogger. I’ve joined your rss feed and sit up for searching for extra of your fantastic post. Additionally, I have shared your site in my social networks|

Comments are closed.