Android recyclerview with cardview android example e-Commerce

Hi, everyone in this Article I am sharing how to create an e-commerce App. And how to show there product in  App with a Good UI Design. Android recycler view with card view android example-e-Commerce. I am Using Android RecyclerView with CardView for Show List of product in your App. Let’s start to create your App easy way.

In this example, I am Using Recycler View List to show data in a List with Adapter. and Using CardView For Creating A Good UI for these.

Android recycler view with card view android example E-Commerce

 Step 1:- Create a Product List Activity In your Project

In your project create an activity and name with Product List. and used these code.

Step 2:-  Open your activity_product_List.XML 

in this XML file, I am adding layout for Recyclerview.

<?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="codeplayon.com.Package_List">

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

        <android.support.v7.widget.RecyclerView
            android:id="@+id/Product_Recycler"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"/>

    </android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>

 

Step 3: Open your Product java file and adding these code.

In your you java file you can use an API for product data. I am using #Volley Libary for getting data in JSONArrey Form  

public class Package_List extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{
    public static final String KEY_joint="joint";
    private RecyclerView firstRecyclerView;
    private ProductAdapter rAdapter;
    public static String EMAIL;
    private SwipeRefreshLayout swipeRefreshLayout;
    String joint="",Appoi_id="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_package__list);
        joint=getIntent().getStringExtra("Joint");
        Appoi_id=getIntent().getStringExtra("appoi_id");
        SessionManagement sessionManagement =new SessionManagement();
        Boolean checkLogin = sessionManagement.getLogin(this);
        EMAIL = sessionManagement.getSavedEmail(this);
        if (!checkLogin){
            Intent intent = new Intent(this,LoginActivity.class);
            startActivity(intent);
        }
        if (AppStatus.getInstance(this).isOnline()) {
            MyProductLIst();

        } else {
            ContextThemeWrapper ctw = new ContextThemeWrapper(Package_List.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.refreshMainCat);
        swipeRefreshLayout.setOnRefreshListener(this);
      
    }

    private void MyProductLIst() {
        // progress Dialog
        final ProgressDialog loading = new ProgressDialog(Package_List.this);
        loading.setMessage("Please Wait...");
        loading.show();
        loading.setCanceledOnTouchOutside(false);
// json response code
        StringRequest stringRequest = new StringRequest(Request.Method.POST, ConfiURL.Packges_List,
                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("status");
                            if (error_status.equals("0")) {
                                String error_msg = jsonObject.getString("message");
//                                Toast.makeText(LogIn.this, error_msg, Toast.LENGTH_SHORT).show();
                                ContextThemeWrapper ctw = new ContextThemeWrapper(Package_List.this, R.style.Theme_AlertDialog);
                                final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(ctw);
                                alertDialogBuilder.setTitle("Message");
                                alertDialogBuilder.setCancelable(false);
                                alertDialogBuilder.setMessage(error_msg);
                                alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {

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

                                JSONArray jArray = jsonObject.getJSONArray("allData");
                                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(Package_List.this, R.style.Theme_AlertDialog);
                                    final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(ctw);
                                    alertDialogBuilder.setTitle("Message");
                                    alertDialogBuilder.setCancelable(false);
                                    alertDialogBuilder.setMessage("No any history data please used Ro care india service");
                                    alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {

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

                                }

                            }

                        } catch (Exception e) {
                            Log.d("Tag", e.getMessage());

                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        loading.dismiss();
                        swipeRefreshLayout.setRefreshing(false);
                        ContextThemeWrapper ctw = new ContextThemeWrapper(Package_List.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();

                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(KEY_joint, joint);
                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("id");
                report.mText2 = json_data.getString("name");
                report.mText3 = json_data.getString("package_amount");
                report.mText4 = json_data.getString("validity");
                report.mText5 = json_data.getString("days");
                report.mText6 = json_data.getString("joints");
                report.mText7 =Appoi_id;
                data.add(report);
            }
            // Setup and Handover data to recyclerview
            firstRecyclerView = (RecyclerView) findViewById(R.id.Product_Recycler);
            rAdapter = new ProductAdapter(Package_List.this, data);
            firstRecyclerView.setAdapter(rAdapter);
            GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(),2);
            firstRecyclerView.setLayoutManager(gridLayoutManager);
//            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//                @Override
//                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                    if(dy > 0){
//                        fab.hide();
//                    } else{
//                        fab.show();
//                    }
//
//                    super.onScrolled(recyclerView, dx, dy);
//                }
//            });

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

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

}

Step 4: Create A  DataObject java Class.

in this java class, you can create a getter and Setter method for getting and setting your value.

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 getImage() {
        return Image;
    }

    public void setImage(String image) {
        Image = 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;
    }

Step 5: Create A  ProductAdapter java Class.

in your Adapter java class I a  getting value with API and set the Layout View holder.

public class ProductAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Context context;
    private LayoutInflater inflater;
    List<DataObject> data = Collections.emptyList();
    private ArrayList<DataObject> arraylist;
    // Report current;
    // int currentPos = 0;
    String Leads_id;
    private int lastPosition = -2;
    public ProductAdapter(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.product_card, parent, false);
        ProductAdapter.MyHolder holder = new ProductAdapter.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
        ProductAdapter.MyHolder myHolder = (ProductAdapter.MyHolder) holder;
        DataObject current = data.get(position);
        myHolder.ProductId.setText(current.getmText1());
        myHolder.ProductName.setText(current.getmText2());
        myHolder.package_amount.setText(current.getmText3());
        myHolder.validity.setText(current.getmText4());
        myHolder.days.setText(current.getmText5());
        myHolder.joints.setText(current.getmText6());
        Leads_id=current.getmText7();

//        String userImage = current.getImage();
//        if (userImage.isEmpty()) {
//            Toast.makeText(context, "no image for user", Toast.LENGTH_LONG).show();
//        } else {
//            Picasso.with(context)
//                    .load(userImage)
//                    .placeholder(R.drawable.ic_logo)
//                    .resize(120, 100)
//                    .into(((MyHolder) holder).Productimage);
//        }
        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 ProductName;
        TextView ProductId;
        ImageView Productimage;
        TextView joints,package_amount,validity,days;
        Button ViewProduct;
        CardView CV;

        // create constructor to get widget reference
        public MyHolder(View itemView) {
            super(itemView);
            CV = (CardView) itemView.findViewById(R.id.CardView);
            ProductName = (TextView) itemView.findViewById(R.id.CatgriName);
            ProductId = (TextView) itemView.findViewById(R.id.CatagriId);
            joints = (TextView) itemView.findViewById(R.id.joints);
            Productimage = (ImageView) itemView.findViewById(R.id.Catagriimage);
            package_amount = (TextView) itemView.findViewById(R.id.package_amount);
            validity = (TextView) itemView.findViewById(R.id.validity);
            ViewProduct=(Button)itemView.findViewById(R.id.ViewProduct);
            days = (TextView) itemView.findViewById(R.id.days);


            ViewProduct.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(context,Buys_Package.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK| Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);

                }
            });
        }
    }
}

 

Step 6:  Create a Card View for show product detail used in Adapter.

create an XML file for show list data in a card view. CardView is used in your adapter class to show the value in the layout.

 

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.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/CardView"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    card_view:cardBackgroundColor="@color/white"
    card_view:cardCornerRadius="8dp">

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

        <ImageView
            android:id="@+id/Catagriimage"
            android:layout_width="match_parent"
            android:layout_height="120dp"
            android:padding="10dp"
            android:background="@drawable/product"
            android:contentDescription="@null" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:padding="5dp"
            android:orientation="vertical">
            <TextView
                android:id="@+id/CatgriName"
                android:textColor="@color/colorPrimary"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAppearance="?android:textAppearanceSmall"
                android:textStyle="bold"
                android:inputType="textMultiLine"
                android:layout_weight="1"
                android:padding="2dp"
                android:text="" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="@color/colorPrimaryDark"
                    android:textAppearance="?android:textAppearanceSmall"
                    android:padding="2dp"
                    android:textStyle="bold"
                    android:text="Joint:  " />
                <TextView
                    android:id="@+id/joints"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:textColor="@color/colorPrimaryDark"
                    android:textAppearance="?android:textAppearanceSmall"
                    android:padding="2dp"
                    android:text="" />
            </LinearLayout>


            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="@color/green"
                    android:textAppearance="?android:textAppearanceSmall"
                    android:padding="2dp"
                    android:textStyle="bold"
                    android:text="Amount:  " />
            <TextView
                android:id="@+id/package_amount"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:textColor="@color/green"
                android:textAppearance="?android:textAppearanceSmall"
                android:padding="2dp"
                android:text="" />
                </LinearLayout>


            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="@color/red"
                    android:textAppearance="?android:textAppearanceSmall"
                    android:padding="2dp"
                    android:textStyle="bold"
                    android:text="Validity:  " />

            <TextView
                android:id="@+id/validity"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textColor="@color/red"
                android:gravity="center"
                android:textAppearance="?android:textAppearanceSmall"
                android:padding="2dp"
                android:text="" />
                </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="@color/black"
                    android:textAppearance="?android:textAppearanceSmall"
                    android:padding="2dp"
                    android:textStyle="bold"
                    android:text="Days:  " />

            <TextView
                android:id="@+id/days"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textColor="@color/black"
                android:gravity="center"
                android:textAppearance="?android:textAppearanceSmall"
                android:padding="2dp"
                android:text="" />
                </LinearLayout>

            <TextView
                android:id="@+id/CatagriId"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:visibility="gone"
                android:text=""/>
        </LinearLayout>

        <Button
            android:id="@+id/ViewProduct"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/white"
            android:textStyle="bold"
            android:background="@drawable/button_left"
            android:text="View"/>

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

 

 

You may also like...