1

Actually, I was trying to implement a shopping cart using Android Studio. There is a custom list view in the main page included an "Add to Cart" button. So, whenever I click on the button the item must be added in the cart. But, I have no idea. Please guys, help me out. I'm a newbie.

Here is the Product Adapter

package com.example.raswap.octomatic;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

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

/**
 * Created by aurora on 22/03/16.
 */
public class Pro_Adapter extends ArrayAdapter {
    List list = new ArrayList();

    public Pro_Adapter(Context context, int resource) {
        super(context, resource);
    }

    static class DataHandler{
        ImageView img;
        TextView p_name;
        TextView b_name;
        TextView price;
        Button b_atc;
    }

    @Override
    public void add(Object object) {
        list.add(object);
    }

    @Override
    public int getCount() {
        return this.list.size();
    }

    @Override
    public Object getItem(int position) {
        return this.list.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row;
        row = convertView;
        DataHandler handler;

        if(convertView == null){
            LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.e_layout, parent, false);
            handler = new DataHandler();
            handler.img = (ImageView)row.findViewById(R.id.pro_image);
            handler.p_name = (TextView)row.findViewById(R.id.pro_name);
            handler.b_name = (TextView)row.findViewById(R.id.brand);
            handler.price = (TextView)row.findViewById(R.id.pricing);
            handler.b_atc = (Button)row.findViewById(R.id.atc);
            row.setTag(handler);
        }else{
            handler = (DataHandler)row.getTag();
        }

        Product_data_provider dataProvider;
        dataProvider = (Product_data_provider)this.getItem(position);

        handler.img.setImageResource(dataProvider.getPro_img_resource());
        handler.p_name.setText(dataProvider.getPro_name());
        handler.b_name.setText(dataProvider.getBr_name());
        handler.price.setText(dataProvider.getPricing());


        return row;
    }
}

Here is the Main Activity class:

package com.example.raswap.octomatic;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class E_shop extends Activity {

    ListView listView;
    int[] emage = {R.drawable.gb32, R.drawable.tb1, R.drawable.dvd};
    String[] pro_name;
    String[] br_name;
    String[] price;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.activity_e_shop);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_titlebar);
        View z = findViewById(R.id.oct_logo);
        z.setClickable(true);
        z.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(E_shop.this, MainActivity.class));
            }
        });
        View x = findViewById(R.id.for_user_info);
        x.setClickable(true);
        x.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(E_shop.this, UserInformation.class));
            }
        });
        Pro_Adapter adapter = new Pro_Adapter(getApplicationContext(),R.layout.e_layout);
        ListView listView = (ListView)findViewById(R.id.e_list);
        listView.setAdapter(adapter);
        pro_name = getResources().getStringArray(R.array.nameOfProduct);
        br_name = getResources().getStringArray(R.array.branding);
        price = getResources().getStringArray(R.array.pricing);

        int i = 0;

        for(String pro: pro_name){
            Product_data_provider dataProvider = new Product_data_provider(emage[i],pro, br_name[i], price[i]);
            adapter.add(dataProvider);
            i++;
        }

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch(position){
                    case 0:
                        Intent newActivity = new Intent(E_shop.this, Product_Desc.class);
                        newActivity.putExtra("pro_emage",R.drawable.gb32);
                        newActivity.putExtra("title","Kingston 32Gigs Pen Drive");
                        newActivity.putExtra("desc", "Store a huge collection of data in a generous 32GB space of this Kingston pen drive and carry it along. It has a sleek design with a smooth finish, and a pretty-looking charm bearing the Kingston logo dangles from this pen drive. Featured in a size of 3 x 1.2 x 0.5 cm, this Kingston 32GB pen drive weighs only 5g. You can easily tuck it away in the pocket of your laptop bag, purse or your shirt pocket with its compact and light weight.");
                        startActivity(newActivity);
                        break;
                    case 1:
                        Intent Activity1 = new Intent(E_shop.this, Product_Desc.class);
                        Activity1.putExtra("pro_emage",R.drawable.tb1);
                        Activity1.putExtra("title","Samsung 1TB Portable Hard Disk");
                        Activity1.putExtra("desc", "From college to school students, all deal with transferring files, software and applications from various systems that are large in size. With the advancements in media technology on the rise, we require a large amount of space to store our data. Even most of the growing companies require a secure means of storing data for analyses. All of this embarks on the need for a reliable hard disk. The top quality brand of Samsung brings you this sleek and portable hard drive ideally designed for continuous usage. Now you can store 2TB of diverse data easily. This, sleek hard disk comes with 36 months warranty. The body of this drive has a smart construction. The Samsung external hard disk comes in a sturdy design.");
                        startActivity(Activity1);
                        break;
                    case 2:
                        Intent Activity2 = new Intent(E_shop.this, Product_Desc.class);
                        Activity2.putExtra("pro_emage", R.drawable.dvd);
                        Activity2.putExtra("title", "A pack of 50 DVD's");
                        Activity2.putExtra("desc", "Create and store digital video, audio and multimedia files, Stores up to 4.7GB or more than 2 hours of MPEG2 video, Has 7 times the storage capacity of a CDR, Sony branded 16X DVD-R in a 100 pack Spindle, AccuCORE Technology");
                        startActivity(Activity2);
                        break;
                }
            }
            @SuppressWarnings("unused")
            public void onClick(View v){

            }
        });


    }
}

Here is the Product Data Provider Class:

package com.example.raswap.octomatic;

/**
 * Created by aurora on 22/03/16.
 */
public class Product_data_provider {
    private int pro_img_resource;
    private String pro_name;
    private String  br_name;
    private String pricing;

    public int getPro_img_resource() {
        return pro_img_resource;
    }

    public Product_data_provider(int pro_img_resource, String pro_name, String br_name, String pricing){
        this.setPro_img_resource(pro_img_resource);
        this.setPro_name(pro_name);
        this.setBr_name(br_name);
        this.setPricing(pricing);
    }

    public void setPro_img_resource(int pro_img_resource) {
        this.pro_img_resource = pro_img_resource;
    }

    public String getPro_name() {
        return pro_name;
    }

    public void setPro_name(String pro_name) {
        this.pro_name = pro_name;
    }

    public String getBr_name() {
        return br_name;
    }

    public void setBr_name(String br_name) {
        this.br_name = br_name;
    }

    public String getPricing() {
        return pricing;
    }

    public void setPricing(String pricing) {
        this.pricing = pricing;
    }
}

Now, Custom ListView XML file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:descendantFocusability="blocksDescendants">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/oneL"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:orientation="horizontal">
            <ImageView
                android:id="@+id/pro_image"
                android:src="@drawable/gb32"
                android:layout_width="160dp"
                android:layout_height="match_parent" />
            <LinearLayout
                android:background="#afeeee"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent">


                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:text="Product Name"
                    android:id="@+id/pro_name"
                    android:textColor="#000"
                    android:layout_marginTop="10dp"
                    android:layout_marginLeft="10dp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:text="Branding"
                    android:id="@+id/brand"
                    android:textColor="#000"
                    android:layout_marginTop="10dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginBottom="10dp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:text="Price"
                    android:textColor="#000"
                    android:id="@+id/pricing"
                    android:layout_marginLeft="10dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginBottom="10dp" />

                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Add to Cart"
                    android:id="@+id/atc" />
            </LinearLayout>


        </LinearLayout>
        <View
            android:layout_below="@+id/oneL"
            android:layout_width="match_parent"
            android:layout_height="5dp"
            android:background="#000"/>
    </RelativeLayout>
</RelativeLayout>

and finally the main layout XML file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.raswap.octomatic.E_shop">

    <ListView
        android:id="@+id/e_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</RelativeLayout>
Swapnil Rai
  • 577
  • 6
  • 14
  • I have a doubt, you have a add to cart button in main activity but, does this button come in each row, along with the item? and if not then how do you get to know which item is being added. – Rishabh Lashkari Mar 28 '16 at 11:49
  • @RishabhLashkari Yes, the add to cart button come in each row but not in the main activity. – Swapnil Rai Mar 28 '16 at 11:58
  • What I would suggest you to do is. 1. Create a method in MainActivity which when called by your adapteractivity will add the data to an arraylist, which contains all the items being added to the cart. 2. In adapterActivity have a onclickListner on button. – Rishabh Lashkari Mar 28 '16 at 12:06

5 Answers5

2

Add your button's OnClick event in the Pro_Adapter's getView() methond as you do normally in your activities' onCreate() method.

Dhrumil Shah - dhuma1981
  • 15,166
  • 6
  • 31
  • 39
0

Implement OnClickListener in your adapter class and get the Button click first and do the other task when you get the event. If you need the call back to your main activity class implement your own listener.follow the link enter link description here

Community
  • 1
  • 1
0

Add the onClickListener to your Button in getView() of your ListAdapter.

A_rmas
  • 784
  • 2
  • 10
  • 26
0

If you want handle event click button in row, i'm think you should answer set button onclick event for every row of listview

Community
  • 1
  • 1
Iris Louis
  • 297
  • 6
  • 19
0

you can try this. Change in custom Listview xml file.

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add to Cart"
    android:onClick="AddCart"
    android:id="@+id/atc" />

In MainActivity

    public void AddCart(View v) 
    {

        LinearLayout vwParentRow = (LinearLayout)v.getParent();

        TextView child = (TextView)vwParentRow.getChildAt(0);

        child.setText("I've been clicked!");
        vwParentRow.refreshDrawableState();      
    }
Rishabh Lashkari
  • 638
  • 1
  • 8
  • 22