In this example showing use of MVC Pattern to create a very basic Shopping cart. Creating very basic Controller Class and defined in application context and you can use this Controller Class as a Global class. If any View(Activity) required values then view should call controller and then controller will call appropriate Model and provide value to view.
Models can also communicate with each others to exchange values.
Please firstly read these examples.
Global Variable Or Application Context Variable - Android Example
Dynamically Create View Elements - Android Example
Model Class to store products details.
package com.androidexample.mvc; public class ModelProducts { private String productName; private String productDesc; private int productPrice; public ModelProducts(String productName,String productDesc,int productPrice) { this.productName = productName; this.productDesc = productDesc; this.productPrice = productPrice; } public String getProductName() { return productName; } public String getProductDesc() { return productDesc; } public int getProductPrice() { return productPrice; } }
Model Class to store products in cart.
Create a ModelProducts type Arraylist to store ModelProducts instances.
package com.androidexample.mvc; import java.util.ArrayList; public class ModelCart{ private ArrayList<ModelProducts> cartProducts = new ArrayList<ModelProducts>(); public ModelProducts getProducts(int pPosition) { return cartProducts.get(pPosition); } public void setProducts(ModelProducts Products) { cartProducts.add(Products); } public int getCartSize() { return cartProducts.size(); } public boolean checkProductInCart(ModelProducts aProduct) { return cartProducts.contains(aProduct); } }
Controller class extends with android.app.Application and defined in the application tag in your AndroidManifest.xml file. Android will create an instance of Controller class and make it available for your entire application context. You can get object of your class on any activity / broadcast receiver / service in application context(environment) by Context.getApplicationContext() method.
Controller class to intract with models and provide values to views.
Create a ModelProducts type Arraylist to store ModelProducts instances.
Create a ModelCart type refference to store ModelCart instance to intract with ModelCart.
package com.androidexample.mvc; import java.util.ArrayList; import android.app.Application; public class Controller extends Application{ private ArrayList<ModelProducts> myProducts = new ArrayList<ModelProducts>(); private ModelCart myCart = new ModelCart(); public ModelProducts getProducts(int pPosition) { return myProducts.get(pPosition); } public void setProducts(ModelProducts Products) { myProducts.add(Products); } public ModelCart getCart() { return myCart; } public int getProductsArraylistSize() { return myProducts.size(); } }
Assign Controller.java in application tag, see this line in application tag android:name="com.androidexample.mvc.Controller"
After assign you can get Controller.java instance on any activity in application context.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidexample.mvc" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="9" /> <application android:name="com.androidexample.mvc.Controller" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.androidexample.mvc.FirstScreen" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.androidexample.mvc.SecondScreen" ></activity> <activity android:name="com.androidexample.mvc.ThirdScreen" ></activity> </application> </manifest>
getApplicationContext() method of Context will give Controller.java object, use this object to store product details and then store object in Arraylist.
Creating view elements dynamically to show product details and add to cart buttons.
After click add to cart button product object will store in Arraylist defined in ModelCart class.
package com.androidexample.mvc; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import android.app.ActionBar.LayoutParams; import android.app.Activity; import android.content.Intent; public class FirstScreen extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.firstscreen); final LinearLayout lm = (LinearLayout) findViewById(R.id.linearMain); final Button secondBtn = (Button) findViewById(R.id.second); //Get Global Controller Class object (see application tag in AndroidManifest.xml) final Controller aController = (Controller) getApplicationContext(); /****************** Create Dummy Products Data ***********/ ModelProducts productObject = null; for(int i=1;i<=4;i++) { int price = 10+i; // Create product model class object productObject = new ModelProducts("Product "+i,"Description "+i,price); //store product object to arraylist in controller aController.setProducts(productObject); } /****************** Products Data Creation End ***********/ /******* Create view elements dynamically and show on activity ******/ //Product arraylist size int ProductsSize = aController.getProductsArraylistSize(); // create the layout params that will be used to define how your // button will be displayed LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); /******** Dynamically create view elements - Start **********/ for(int j=0;j< ProductsSize;j++) { // Get probuct data from product data arraylist String pName = aController.getProducts(j).getProductName(); int pPrice = aController.getProducts(j).getProductPrice(); // Create LinearLayout to view elemnts LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.HORIZONTAL); TextView product = new TextView(this); product.setText(" "+pName+" "); //Add textView to LinearLayout ll.addView(product); TextView price = new TextView(this); price.setText(" $"+pPrice+" "); //Add textView to LinearLayout ll.addView(price); final Button btn = new Button(this); btn.setId(j+1); btn.setText("Add To Cart"); // set the layoutParams on the button btn.setLayoutParams(params); final int index = j; //Create click listener for dynamically created button btn.setOnClickListener(new OnClickListener() { public void onClick(View v) { //Clicked button index Log.i("TAG", "index :" + index); // Get product instance for index ModelProducts tempProductObject = aController.getProducts(index); //Check Product already exist in Cart or Not if(!aController.getCart().checkProductInCart(tempProductObject)) { btn.setText("Added"); // Product not Exist in cart so add product to // Cart product arraylist aController.getCart().setProducts(tempProductObject); Toast.makeText(getApplicationContext(), "Now Cart size: "+aController.getCart().getCartSize(), Toast.LENGTH_LONG).show(); } else { // Cart product arraylist contains Product Toast.makeText(getApplicationContext(), "Product "+(index+1)+" already added in cart.", Toast.LENGTH_LONG).show(); } } }); //Add button to LinearLayout ll.addView(btn); //Add LinearLayout to XML layout lm.addView(ll); } /******** Dynamically create view elements - End **********/ secondBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent(getBaseContext(), SecondScreen.class); startActivity(i); } }); } }
Showing ModelProduct objects details on screen that stored in ModelCart Arraylist.
package com.androidexample.mvc; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class SecondScreen extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.secondscreen); TextView showCartContent = (TextView) findViewById(R.id.showCart); final Button thirdBtn = (Button) findViewById(R.id.third); //Get Global Controller Class object (see application tag in AndroidManifest.xml) final Controller aController = (Controller) getApplicationContext(); // Get Cart Size final int cartSize = aController.getCart().getCartSize(); String showString = ""; /******** Show Cart Products on screen - Start ********/ if(cartSize >0) { for(int i=0;i<cartSize;i++) { //Get product details String pName = aController.getCart().getProducts(i).getProductName(); int pPrice = aController.getCart().getProducts(i).getProductPrice(); String pDisc = aController.getCart().getProducts(i).getProductDesc(); showString += " Product Name : "+pName+" "+ "Price : "+pPrice+" "+ "Discription : "+pDisc+""+ " -----------------------------------"; } } else showString = " Shopping cart is empty. "; showCartContent.setText(showString); /******** Show Cart Products on screen - End ********/ thirdBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { if(cartSize >0) { Intent i = new Intent(getBaseContext(), ThirdScreen.class); startActivity(i); } else Toast.makeText(getApplicationContext(), "Shopping cart is empty.", Toast.LENGTH_LONG).show(); } }); } @Override protected void onDestroy() { super.onDestroy(); } }
Showing ModelProduct objects details on screen that stored in ModelCart Arraylist.
package com.androidexample.mvc; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class ThirdScreen extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.thirdscreen); TextView showCartContent = (TextView) findViewById(R.id.showCart); //Get Global Controller Class object (see application tag in AndroidManifest.xml) final Controller aController = (Controller) getApplicationContext(); int cartSize = aController.getCart().getCartSize(); String showString = ""; /******** Show Cart Products on screen - Start ********/ for(int i=0;i<cartSize;i++) { //Get product details String pName = aController.getCart().getProducts(i).getProductName(); int pPrice = aController.getCart().getProducts(i).getProductPrice(); String pDisc = aController.getCart().getProducts(i).getProductDesc(); showString += " Product Name : "+pName+" "+ "Price : "+pPrice+" "+ "Discription : "+pDisc+""+ " -----------------------------------"; } showCartContent.setText(showString); /******** Show Cart Products on screen - End ********/ } }