• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Very Simple "Add to Cart/View Cart" Functionality

XDA Developers,

First I would like to admit my current Android Developer Status. I have began programming in this field about 2 weeks ago, and my knowledge is lilting. I plan to stick around these forums with intent to increase my knowledge, and not just use what you have to offer but actually learn!

Anyway, here is my dilemma...

I have already established an android application that includes product listings and an "Add to Cart" button. My intention is to add some intent to the "Add to Cart" button that will:

1.) Pop up, "This item has been added to your cart"
2.) Actually add the item to the cart

Of course then I am interested in how to develop a "View Cart" page to see the added items

I have already searched through online tutorials and developed something very similar. But it is such a rough copy, as opposed to sharing the messy code I've put together, I figured I would just ask on a clean slate

I appreciate any assistance,
- Deployments


Further Breakdown:
Right now I have a product list page. When you click on a product there are two buttons: "Add to Cart" and "View Cart". However, neither of these buttons do anything.

I need some help adding an intent/function to the button, that when clicked it can pass text/price/image data to the "View Cart" page for each product
 
If you want to pop up a dialog that shows a message, you can use a Dialog. There's some information on how to do that here

https://developer.android.com/guide/topics/ui/dialogs

Creating an Activity with an Intent is a standard Android app procedure. Some information about that here:

https://developer.android.com/training/basics/firstapp/starting-activity

If you would like to post any code you already have, and get some advice on that, then please do so.


Here is an example of a sunglass1.xml file

Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:background="#e5fff7"
    tools:context=".sunglass1"
    tools:layout_editor_absoluteY="81dp">

    <TextView
        android:id="@+id/textView6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="165dp"
        android:layout_marginStart="40dp"
        android:layout_marginTop="18dp"
        android:gravity="center"
        android:text="Sleek and Simple Glasses"
        android:textColor="#0015ff"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/textView11"
        app:layout_constraintStart_toStartOf="@+id/imageView10"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="Sleek and Simple Glasses" />

    <Button
        android:id="@+id/viewcart"
        android:layout_width="0dp"
        android:layout_height="59dp"
        android:layout_marginEnd="42dp"
        android:text="View Cart"
        app:layout_constraintBaseline_toBaselineOf="@+id/addcart3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/addcart3"
        tools:text="View Cart" />

    <Button
        android:id="@+id/addcart3"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="53dp"
        android:layout_marginEnd="26dp"
        android:layout_marginStart="26dp"
        android:text="Add to Cart"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/viewcart"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView10"
        tools:text="Add to Cart" />

    <TextView
        android:id="@+id/textView7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="28dp"
        android:layout_marginStart="96dp"
        android:text="$45"
        android:textSize="50sp"
        app:layout_constraintBottom_toTopOf="@+id/addcart3"
        app:layout_constraintStart_toStartOf="@+id/textView11"
        app:layout_constraintTop_toBottomOf="@+id/textView11"
        tools:text="$45" />

    <TextView
        android:id="@+id/textView11"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="40dp"
        android:layout_marginEnd="42dp"
        android:layout_marginStart="42dp"
        android:gravity="center"
        android:text="These glasses are sharp, sleek, and simple. Not to mention; highly affordable as well!"
        app:layout_constraintBottom_toTopOf="@+id/textView7"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView6"
        tools:text="These glasses are sharp, sleek, and simple. Not to mention; highly affordable as well!" />

    <ImageView
        android:id="@+id/imageView10"
        android:layout_width="0dp"
        android:layout_height="200dp"
        android:layout_marginBottom="155dp"
        android:layout_marginEnd="26dp"
        android:layout_marginStart="26dp"
        android:layout_marginTop="44dp"
        app:layout_constraintBottom_toTopOf="@+id/addcart3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/sunglass3" />

</android.support.constraint.ConstraintLayout>

It is very simple, please see the attached screenshot.

I need some help so that when the user presses "Add to Cart", it will send the text and price data to "View Cart" page

Thanks,
- Deployment
 

Attachments

  • Screen Shot 2018-05-09 at 11.56.49 AM.png
    Screen Shot 2018-05-09 at 11.56.49 AM.png
    80.4 KB · Views: 2,673
First thing you need to do is add an OnClickListener to your Button. Like this

Code:
final Button button = findViewById(R.id.button_id);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Code here executes on main thread after user presses button
            }
        });

https://developer.android.com/reference/android/widget/Button

The code in the onClick() method will create an Intent, and start the child Activity. I'll let you read up on how to do that, rather than supply code, because it's an important thing for you to learn.
 
First thing you need to do is add an OnClickListener to your Button. Like this

Code:
final Button button = findViewById(R.id.button_id);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Code here executes on main thread after user presses button
            }
        });

https://developer.android.com/reference/android/widget/Button

The code in the onClick() method will create an Intent, and start the child Activity. I'll let you read up on how to do that, rather than supply code, because it's an important thing for you to learn.

OnClick Listened is added on all pages, ID's associated as well

Looks like all that is left is the executable code to push the text and value, and then the recipient code to display it within the cart page

- Deployment

Thanks so far for the help!
 
First thing you need to do is add an OnClickListener to your Button. Like this

Code:
final Button button = findViewById(R.id.button_id);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Code here executes on main thread after user presses button
            }
        });

https://developer.android.com/reference/android/widget/Button

The code in the onClick() method will create an Intent, and start the child Activity. I'll let you read up on how to do that, rather than supply code, because it's an important thing for you to learn.
I have also established the "View Cart" button already by using

@override
public void onClick(View v) {
openCart();
}

and then opening the page within the function call



(Just wanted to provide this so you know Im actually reading, not just begging for answers)
 
What's in your openCart() method?

Here is the entire code from my sunglass1.java file (Product 1) for convenience.

Right now it displays the "Add to Cart" button, waiting for a function
It also will open "View Cart" on the click.

* Of course "View Cart" currently has nothing there other than a textview

Code:
public class sunglass1 extends AppCompatActivity {

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

        Button button = (Button) findViewById(R.id.addcart);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Code here executes on main thread after user presses button
            }
        });

        button = (Button) findViewById(R.id.viewcart);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                openCart();
            }
        });
    }
    public void openCart() {
        Intent intent = new Intent(this, cart.class);
        startActivity(intent);
    }
}
 
So going back to your original design spec, the next thing to think about is how you model the "Cart" object, and also how to pass that to the child Activity.
I'll give you a clue here - read up on the Parcelable class. This allows you to pass complex data structures between Activities.

https://developer.android.com/reference/android/os/Parcelable

So you could define a class to represent the Cart, something like this

Code:
public class Cart implements Parcelable {
  ...
}

And this class would have methods to add and remove items from the Cart.

Of course another approach you could consider, to share data between Activities is using the SQLite database. Although this would be more suitable for persistent data.
 
So going back to your original design spec, the next thing to think about is how you model the "Cart" object, and also how to pass that to the child Activity.
I'll give you a clue here - read up on the Parcelable class. This allows you to pass complex data structures between Activities.

https://developer.android.com/reference/android/os/Parcelable

So you could define a class to represent the Cart, something like this

Code:
public class Cart implements Parcelable {
  ...
}

And this class would have methods to add and remove items from the Cart.

Of course another approach you could consider, to share data between Activities is using the SQLite database. Although this would be more suitable for persistent data.


SQLite is an implementation I believe we are focusing on later. Right now we are focusing on the action of passing information from one activity and displaying it in another through use of a button click.

I am currently starting a drive to work, however will give this a read tonight and comment back my thoughts/progress

Hopefully you will be available then

Thanks so far,
- Deployment
 
Yeah sure, feel free to come back.

Im definitely getting somewhere, but at this point as opposed to you revising my jumblation of code, it might just be easier to help me in the right direction so that I can study it.

Anyways, here is my current sunglass1.java file:

Code:
package edu.phoenix.mbl402.week2apptt2163;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class sunglass1 extends AppCompatActivity {

    public static final String EXTRA_TEXT = "sunglass1.EXTRA_TEXT";

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

        Button button = (Button) findViewById(R.id.addcart);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {


                TextView textView7 = (TextView) findViewById(R.id.textView7);
                String text = textView7.getText().toString();

                Intent myintent = new Intent(v.getContext(), cart.class);
                myintent.putExtra(EXTRA_TEXT, text);
                startActivity(myintent);

            }
        });

        button = (Button) findViewById(R.id.viewcart);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                openCart();
            }
        });
    }
    public void openCart() {

        Intent intent = new Intent(this, cart.class);
        startActivity(intent);

    }
}

Here is my cart.java file:
Code:
package edu.phoenix.mbl402.week2apptt2163;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class cart extends AppCompatActivity {

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

        Intent intent = getIntent();
        String text = intent.getStringExtra(sunglass1.EXTRA_TEXT);

        TextView textview12 = (TextView) findViewById(R.id.textView12);

        textview12.setText(text);

    }


}

As you can tell, I am attempting to just replace text within the cart when "Add to Cart" is pressed, and it does in fact work! Downside is that the Cart is automatically opened when "Add to Cart" is pressed, and that a bunch of useless text must be visible in order to replace.

Please give me a better way to go about this

- Deployment
 
You need to understand this concept of a Parcelable object. It's Android's flavour of the standard Java Serializable concept.
I did find this useful website that can convert your class into a Parcelable.

http://www.parcelabler.com/

But first you must decide on the structure of your Parcelable class. For a shopping cart, a basic design would be

Code:
public class Cart {
  private ArrayList<String> items;
};

Using the above website, gives me the following Parcelable class:

Code:
class Cart implements Parcelable {
private ArrayList<String> items;

   protected Cart(Parcel in) {
       if (in.readByte() == 0x01) {
           items = new ArrayList<String>();
           in.readList(items, String.class.getClassLoader());
       } else {
           items = null;
       }
   }

   @Override
   public int describeContents() {
       return 0;
   }

   @Override
   public void writeToParcel(Parcel dest, int flags) {
       if (items == null) {
           dest.writeByte((byte) (0x00));
       } else {
           dest.writeByte((byte) (0x01));
           dest.writeList(items);
       }
   }

   @SuppressWarnings("unused")
   public static final Parcelable.Creator<Cart> CREATOR = new Parcelable.Creator<Cart>() {
       @Override
       public Cart createFromParcel(Parcel in) {
           return new Cart(in);
       }

       @Override
       public Cart[] newArray(int size) {
           return new Cart[size];
       }
   };
}

You would pass the Parcelable object to a child Activity in the Intent.
 
You need to understand this concept of a Parcelable object. It's Android's flavour of the standard Java Serializable concept.
I did find this useful website that can convert your class into a Parcelable.

http://www.parcelabler.com/

But first you must decide on the structure of your Parcelable class. For a shopping cart, a basic design would be

Code:
public class Cart {
  private ArrayList<String> items;
};

Using the above website, gives me the following Parcelable class:

Code:
class Cart implements Parcelable {
private ArrayList<String> items;

   protected Cart(Parcel in) {
       if (in.readByte() == 0x01) {
           items = new ArrayList<String>();
           in.readList(items, String.class.getClassLoader());
       } else {
           items = null;
       }
   }

   @Override
   public int describeContents() {
       return 0;
   }

   @Override
   public void writeToParcel(Parcel dest, int flags) {
       if (items == null) {
           dest.writeByte((byte) (0x00));
       } else {
           dest.writeByte((byte) (0x01));
           dest.writeList(items);
       }
   }

   @SuppressWarnings("unused")
   public static final Parcelable.Creator<Cart> CREATOR = new Parcelable.Creator<Cart>() {
       @Override
       public Cart createFromParcel(Parcel in) {
           return new Cart(in);
       }

       @Override
       public Cart[] newArray(int size) {
           return new Cart[size];
       }
   };
}

You would pass the Parcelable object to a child Activity in the Intent.

I understand the basics of Parcelable, I have been reading about it all day. However still lack the knowledge to actually implement it into my instance here.

I still have this as my sunglass1.java file, after undoing all my attempts today:
Code:
public class sunglass1 extends AppCompatActivity {

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

        Button button = (Button) findViewById(R.id.addcart);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //How to pass information here
            }
        });

        button = (Button) findViewById(R.id.viewcart);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                openCart();
            }
        });
    }
    public void openCart() {

        Intent intent = new Intent(this, cart.class);
        startActivity(intent);
    }
}

Just very lost how to implement this so that textview6 and textview7 will be passed and received by the cart.java file.... then stored there for further additions. Of course a simple intent could be used, but that only passes data on the single instance, and it is not permanently stored

Any further help is appreciated

- Deployed
 
You shouldn't store the selected items in the Cart (child) Activity. Because when it finishes, it's destroyed.
Instead you should maintain a data structure in the Sunglass Activity to contain the selected items. So every time you create a new Cart Activity, you pass the items to it in the Intent.
 
You shouldn't store the selected items in the Cart (child) Activity. Because when it finishes, it's destroyed.
Instead you should maintain a data structure in the Sunglass Activity to contain the selected items. So every time you create a new Cart Activity, you pass the items to it in the Intent.

Can you please assist me in setting that up, Ive been reading all day but am loosing so much hope as this is only my first week of Android Development and such a concept is hard to grasp with no present example.

I mean I assure you that even if you walk me through this Ill continue my research
 
I will try to help you, but believe me, you'll learn next to nothing by just copy/pasting code. I won't be doing you any favours in terms of improving your understanding, by giving you a code complete answer.

To start with, let me ask you these questions:-

1. How would you store all the selected String items in your Sunglass Activity? What data structure would you use?

2. How would you transmit that data to your child Activity, based on your knowledge of Intents?

If you can't answer question 1, then you're in no position to continue app development, because you lack basic knowledge of the Java programming language. Going forward from here would be like building on sand. You really have to learn to walk, before you can run.
 
1. What about an ArrayList?
ArrayList<String> list = new ArrayList<String>();
list.add("Sunglass Type 1");
list.add("$70");

My Intent Format:
2. Intent intent = new Intent(sunglass1.this, cart.class);
intent.putExtra( // Somehow need to push the entire array here on the click of a button);
startActivity(intent);

then receive the intent in the cart.class
String s = getIntent().getStringExtra("//somehow receive that entire array");


But the biggest question, even if I do figure out how to send the entire array there. Is how to permanently pass the data... Because even with this method (Which I had figured out earlier and erased), the data was only there when opening the new activity, and disappeared when I exited

- Deployed
 
But the biggest question, even if I do figure out how to send the entire array there. Is how to permanently pass the data... Because even with this method (Which I had figured out earlier and erased), the data was only there when opening the new activity, and disappeared when I exited

As I said before, you build up your data in the Sunglass Activity, and each time the user clicks View Cart, you send all the data to the child Activity.
 
Hi,
my idea was using shared preferences and then pass the data to the intent. but its difficult for me to pass an Arraylist values to shared preferences. please share me if u found solutions for this
 
Back
Top Bottom