This Page has two parts which are as follows.
A. Part I : Description and flow of Programs.
B. Part II: Coding.
A. Part I
Description of Main Page. Showing the Screen Layouts.
Main Page: This is the first Page that appear on screen.
This page have four sections.
1. In first section :The images are flipped one by one. These images are advertisement images.
2. In second section : The Images are scrolled. These are the Items Images scrolled from Left to right.
3. In Third section : The data is taken from MySql and PHP File. This is the data for bank offers etc,
4. Top Section Have Icon as follows.
4.1 Help Icon : To Take Photo from camera and send as Email.
4.2 Login Icon : To accept user and validate.
4.3 Cart Icon : This will show the Items listed in Cart and waiting for Confirmation.
4.4 Tracking Icon: This will list the Items status on shipment.
4.5 Once the user is logged in. User name is displayed . User mobile no is saved at application level.
5. Animation on Icon: The animation is controlled with a flag.
5.1 Help Icon : The Icon will Zoom In and Zoom Out.
5.2 Login Icon : Will Blink , if the user is not logged in.
5.3 Cart Icon : Will tilt from –20 to 20 degree , if there is item in Cart.
Two Dialogs are shown before main page appear.
User Dialog page : User is prompted to enter the Login Details, if not entered.
Login Page : This page is displayed on press of Login Icon.It will accept Login details.
This has two options
1. User Validation: Enter user name and password. User is validated and data like user name, mobile no and address is saved at application level.
2. Register User: Enter user details and save in MySql.
List All Items. : This page will display all the Items to purchase. Items are added to Cart on select.
Cart Page & SMS Page : This page will show all Items in cart. Send SMS once confirmed to purchase. On Press of Pay Button SMS will be send.
Help Page & Email Page : Send Email in case of Complaint. Take photo and send as Email with inline images along with text/complaint.
B. Part II
Three PHP files are used:
1. gettabledata.php file. This will accept a query as string and return the data from MySql.
2. myconnection.php. This file is called from gettabledata.php to establish connection to MySql.
3. insertdata.php : This file will insert data to MySql. This will accept insert query to save data in MySql.
Following files are created.
myconnection.php
gettabledata.php
MainActivity.java
backgroundTaskOffers.java
activity_main.xml
PHP File Name: myconnection.php
PHP File Name:gettabledata.php
File Name: MainActivity.java
public class MainActivity extends ActionBarActivity {
<?php
//establish connection
$user="root";
$password="";
$host="localhost";
$database="cart";
//connection to database
$handle = mysql_connect($host,$user,$password)
or die("Unable to connect");
//echo "Connected to MySql";
$selected = mysql_select_db($database,$handle)
or die("Could not select database");
?>
PHP File Name:gettabledata.php
<?php
//Establish Connection
require 'myconnection.php';
//Get Parameter
$query=$_POST['query'];
//Execute the sql query and return result;
$result= mysql_query($query);
//if (mysql_num_rows($result) == 0 ) {die(mysql_error());}
if(mysql_num_rows($result) ==0 ) { $output["data"][]=array("id"=>-1);}
//Loop to get data from table
while ($row = mysql_fetch_array($result))
{
$output["data"][]=$row;
}
print(json_encode($output));
//Close connection
mysql_close($handle);
?>
File Name: MainActivity.java
package com.example.cart;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.app.ActionBarActivity;import android.support.v7.appcompat.R.id;
import android.text.method.ScrollingMovementMethod;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private static final OnClickListener OnClickListener = null;
ImageView imageview;
ListView listview;
TextView username;
TextView scrolltxt1;
int image_id = R.drawable.sale;
String adds_title = "S A L E";
String adds_message = "Bargain Sale Starts at \n 12:30PM Today";
LocationManager mLocationManager;
float LOCATION_REFRESH_DISTANCE = 1;
long LOCATION_REFRESH_TIME = 100;
HorizontalScrollView hsv;
LinearLayout ll;
@Override
fnflip(); // This method will flip images. These are advertisements. These are drawable images as image1,image2,image3
@Override
int[] ArrayImage = { R.drawable.image1, R.drawable.image2,
R.drawable.image3, R.drawable.image_large };
int[] ArrayImage2 = { R.drawable.pen, R.drawable.pens, R.drawable.laptop };
String[] items = { "Ax Bank| 10% off on all Items", "Hd Bank | 5% off" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageview = (ImageView) findViewById(R.id.Image1);
listview = (ListView) findViewById(R.id.ListView1);
username = (TextView) findViewById(R.id.username);
scrolltxt1 = (TextView) findViewById(R.id.scrolltxt);
hsv = (HorizontalScrollView) findViewById(R.id.hscroll);
ll = (LinearLayout) findViewById(R.id.LayoutImage2);
fnflip(); // This method will flip images. These are advertisements. These are drawable images as image1,image2,image3
fnscroll(); // This method will scroll images from left to right.
fnview(); // This method will show data from Mysql and PHP database.
fnanim(0); // This method will animate all the images initially like Help,Login,Cart &Tracking.
fndialog(); // This method will show a splash screen with advertisement which will disappear after some time.
username.setText(((GlobalVariable) this.getApplicationContext()).getUserName());
}
@Override
public void onResume() { // After a pause OR at startup
super.onResume();
// These statements will scroll the text from left to right. The data is received from MySql and PHP.
// The behaviour is same as marquee.
// The data is saved in TextView and the text should be long to scroll.
// This is specified in OnResume event so that when the screen is revised these statements will executed again.
username.setText(((GlobalVariable) this.getApplicationContext())
.getUserName());
String txt = getdata().toString();
String repeated = new String(new char[100 - txt.length()]).replace(
"\0", " ");
scrolltxt1.setText(txt + repeated);
scrolltxt1.setSelected(true); // important to use to text to scroll
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// This method will flip images. These are advertisements. These are drawable images as image1,image2,image3
// These images will flip after every 500.
public void fnflip() {
final Handler handler = new Handler();
Runnable runable = new Runnable() {
int i = 0;
@Override
public void run() {
imageview.setImageResource(ArrayImage[i++]);
hsv.smoothScrollBy(200, 0);
if (i > ArrayImage.length - 1)
i = 0;
handler.postDelayed(this, 500);
}
};
handler.postDelayed(runable, 1000);
}
// This method will scroll images from left to right.
public void fnscroll() {
LinearLayout llayout = (LinearLayout) findViewById(R.id.LayoutImage2);
int x = 0;
for (int i = 0; i < 10; i++) {
ImageView imageview = new ImageView(getBaseContext());
imageview.setId(i);
imageview.setPadding(2, 2, 2, 2);
if (x >= 3)
x = 0;
imageview.setImageResource(ArrayImage2[x++]);
llayout.addView(imageview);
}
}
// This method will show data from MySql and PHP database.
// The data is received from MySql and PHP with the help of getdata() method.
public void fnview() {
@SuppressWarnings("unchecked")
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(), R.layout.custom_layout, getdata());
listview.setAdapter(adapter);
}
//The getdata method will accept query as select statement and link to PHP file gettabledata.php.
@SuppressWarnings("rawtypes")
public ArrayList getdata() {
ArrayList arrstr = null;
try {
BackgroundTaskOffers bto = new BackgroundTaskOffers();
// String host="10.0.2.2"; //host for mobile emulator other wise
// server host name
String host = ((GlobalVariable) getApplicationContext()).getHost();
// host for mobile emulator other wise server hostname
String query = "Select * from catg_details";
String link = "http://" + host + "/php/gettabledata.php";
String[] fields = { "discounts_provider_name", "discounts_details" };
String str = bto.execute(query, link).get();
arrstr = bto.getOfferdetails(str, fields);
} catch (Exception e) {
e.printStackTrace();
Log.v("system error", "**");
}
return arrstr;
}
// With this method will start the ListActivity Intent - To list of Items to purchase in ListView.
public void fnnextpage(View v) {
Intent intent = new Intent(getApplicationContext(), ListActivity.class);
new SmsReceiver();
startActivity(intent);
}
//This method will start the ComplaintActivity Intent. - To Capture Photo from Camera and send as Email.
public void fnhelp(View v) {
Intent intent = new Intent(getApplicationContext(), ComplaintActivity.class);
startActivity(intent);
}
//This method will start the CartActivity Intent. - To Show the Items in cart in ListView.
public void fncart(View v) {
Intent intent = new Intent(getApplicationContext(), CartActivity.class);
startActivity(intent);
}
//This method will start the LoginActivity Intent. - This is User Login Page.
public void fnlogin(View v) {
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
// This method will animate all the images initially like Help,Login,Cart &Tracking.
// Login Icon will animate as Blink.
// Cart Icon will animate as Rotate from -20 to 20 degree.
// Tracking Icon will animate as Move from Left to Right and back.
// Help Icon will Zoom In and Zoom Out.
public void fnanim(int flag) {
Animation animation1 = null, animation2 = null, animation3 = null, animation4 = null;
ImageView imagev_b = (ImageView) findViewById(R.id.Login);
ImageView imagev_r = (ImageView) findViewById(R.id.Cart);
ImageView imagev_m = (ImageView) findViewById(R.id.Tracking);
ImageView imagev_h = (ImageView) findViewById(R.id.help);
if (flag == 1 || flag == 0) {
animation1 = new AnimationUtils().loadAnimation(getApplicationContext(), R.anim.blink);
imagev_b.setAnimation(animation1);
}
if (flag == 2 || flag == 0) {
animation2 = new AnimationUtils().loadAnimation(getApplicationContext(), R.anim.rotate);
imagev_r.setAnimation(animation2);
}
if (flag == 3 || flag == 0) {
animation3 = new AnimationUtils().loadAnimation(getApplicationContext(), R.anim.moveleft);
imagev_m.setAnimation(animation3);
}
if (flag == 4 || flag == 0) {animation4 = new AnimationUtils().loadAnimation(getApplicationContext(), R.anim.smallmax);
imagev_h.setAnimation(animation4);
}
}
// Creates a dialog for user to enter username else give a message that user is not logged in.
public void fndialog() {
String username = ((GlobalVariable) this.getApplicationContext())
.getUserName();
String dialog_title = "";
String dialog_message = "";
if (username == "Not LoggedIn") {
dialog_title = "User Not LoggedIn";
dialog_message = "Enter user name and Password \n on Pressing above Key Icon \n\n and Once Validated Items can be added to Your Cart";
} else {
dialog_title = "Your are Logged in as User:" + username;
dialog_message = "To Change User please \n Enter user name and Password \n on Pressing above Key Icon \n\n and Once Validated Items can be added to Your Cart";
}
AlertDialog.Builder alertdialog = new AlertDialog.Builder(this);
alertdialog.setTitle(dialog_title);
alertdialog.setMessage(dialog_message);
alertdialog.setIcon(resize(getResources().getDrawable(R.drawable.login), 100));
alertdialog.setPositiveButton("Continue",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{ fnadds(); } });
alertdialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish(); // close the application and exit;
}
});
AlertDialog alertd = alertdialog.create();
alertd.show();
}
// This is a method to resize an Image to a small Image , so as to take less memory and avoid memory overflow errors.
private Drawable resize(Drawable image, int size)
{
Bitmap b = ((BitmapDrawable) image).getBitmap();
Bitmap bitmapresize = Bitmap.createScaledBitmap(b, size, size, false);
return new BitmapDrawable(getResources(), bitmapresize);
}
// This will show an advertisements . It will appear as splash Image and will disappear after some time.
public void fnadds() {
ImageView image = new ImageView(getBaseContext());
image.setMaxHeight(100);
image.setMaxWidth(100);
image.setBackgroundColor(Color.RED);
image.setImageResource(image_id);
final AlertDialog alertdialog = new AlertDialog.Builder(this).create();
alertdialog.setTitle(adds_title);
alertdialog.setMessage(adds_message);
alertdialog.setIcon(resize(image.getDrawable(), 500));
final Handler handler = new Handler();
Runnable runable = new Runnable() {
int ii = 0;
@Override
public void run() {
// TODO Auto-generated method stub
handler.postDelayed(this, 500);
ii++;
if (ii > 10)
alertdialog.dismiss();
}
};
handler.postDelayed(runable, 1500);
alertdialog.show();
}
}
File Name: BackgroundTaskOffers.java
package com.example.cart;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
public class BackgroundTaskOffers extends AsyncTask<String, Void, String> {
String Result;
StringBuilder sb = new StringBuilder();
@Override
protected String doInBackground(String... arg0) {
String query = (String) arg0[0];
String link = (String) arg0[1];
Result = link(query, link);
return Result;
}
// This method is used to establish a connection to PHP file.
// SQL query and link to PHP file is passed as parameter.
public String link(String query, String link) {
try {
String data = URLEncoder.encode("query", "UTF-8") + "="
+ URLEncoder.encode(query, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(data);
wr.flush();
String line = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
// Get the data in array format for adapter. Json data is passed with database fields.
// This method is for offers details adapter and show data in ListView.
public ArrayList<String> getOfferdetails(String jsondata, String[] data) {
ArrayList<String> arrstr = new ArrayList<String>();
try {
JSONObject jobject = new JSONObject(jsondata);
JSONArray jmain = jobject.optJSONArray("data");
String[] rdata = new String[2];
for (int i = 0; i < jmain.length(); i++) {
JSONObject jchild = jmain.getJSONObject(i);
rdata[0] = jchild.optString(data[0]);
rdata[1] = jchild.optString(data[1]);
arrstr.add(rdata[0] + " | " + rdata[1]);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return arrstr;
}
// Get the data in List<Items> format for adapter. Json data is passed with database fields.
// This method is for Items details adapter and show data in ListView.
public List<Items> getItems(String jsondata, String[] data) {
List<Items> allitems = new LinkedList<Items>();
try {
JSONObject jobject = new JSONObject(jsondata);
JSONArray jmain = jobject.optJSONArray("data");
for (int i = 0; i < jmain.length(); i++) {
JSONObject jchild = jmain.getJSONObject(i);
Items items = new Items();
items.setId(Integer.parseInt(jchild.optString(data[0])));
items.setItem_code(jchild.optString(data[1]));
items.setItem_short_desc(jchild.optString(data[2]));
items.setItem_color(jchild.optString(data[3]));
items.setItem_size(jchild.optString(data[4]));
items.setItem_value(Double.parseDouble(jchild
.optString(data[5])));
allitems.add(items);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return allitems;
}
// Get the data in List<schedule> format for adapter. Json data is passed with database fields.
// This method is for Cart details adapter and show data in ListView.
public List<schedule> getCart(String jsondata, String[] data) {
List<schedule> allitems = new LinkedList<schedule>();
try {
JSONObject jobject = new JSONObject(jsondata);
JSONArray jmain = jobject.optJSONArray("data");
for (int i = 0; i < jmain.length(); i++) {
JSONObject jchild = jmain.getJSONObject(i);
schedule items = new schedule();
items.setUsercode(jchild.optString(data[0]));
items.setItem_code(jchild.optString(data[1]));
items.setSchedule_type(jchild.optString(data[2]));
items.setSchedule_date(jchild.optString(data[3]));
String order = "0";
if (jchild.optString(data[4]) != "")
order = jchild.optString(data[4]);
items.setSchedule_order(Integer.parseInt(order));
allitems.add(items);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return allitems;
}
}
File: activity_main.xml
<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.cart.MainActivity" >
<LinearLayout
android:id="@+id/Main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/LayoutMenuBar"
style="@style/menubar"
android:layout_width="wrap_content"
android:layout_height="30sp"
android:orientation="horizontal" >
<ImageView
android:id="@+id/ModuleName"
android:layout_width="100sp"
android:layout_height="30sp"
android:src="@drawable/modulename" />
<TextView
android:id="@+id/username"
style="@style/white"
android:layout_width="90sp"
android:layout_height="wrap_content"
android:text="Not LoggedIn"
android:textSize="10sp" />
<ImageView
android:id="@+id/help"
android:layout_width="30sp"
android:layout_height="wrap_content"
android:onClick="fnhelp"
android:src="@drawable/help" />
<ImageView
android:id="@+id/Login"
android:layout_width="30sp"
android:layout_height="wrap_content"
android:onClick="fnlogin"
android:src="@drawable/login" />
<ImageView
android:id="@+id/Cart"
android:layout_width="40sp"
android:layout_height="wrap_content"
android:onClick="fncart"
android:src="@drawable/cart" />
<ImageView
android:id="@+id/Tracking"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/delivery" />
</LinearLayout>
<LinearLayout
android:id="@+id/LayoutImage1"
android:layout_width="match_parent"
android:layout_height="150sp"
android:layout_marginTop="2sp"
android:background="@drawable/greenstyle"
android:orientation="horizontal"
android:padding="7sp" >
<ImageView
android:id="@+id/Image1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:scaleType="fitXY"
android:src="@drawable/image1" />
</LinearLayout>
<HorizontalScrollView
android:id="@+id/hscroll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/greenstyle"
android:padding="7sp" >
<LinearLayout
android:id="@+id/LayoutImage2"
android:layout_width="wrap_content"
android:layout_height="130sp"
android:layout_marginTop="2sp"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
<LinearLayout
android:id="@+id/LayoutView"
android:layout_width="wrap_content"
android:layout_height="130sp"
android:layout_marginTop="2sp"
android:background="@drawable/greenstyle"
android:orientation="vertical" >
<ListView
android:id="@+id/ListView1"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:padding="10sp" >
</ListView>
<TextView
android:id="@+id/scrolltxt"
style="@style/whitebold"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/redstyle"
android:ellipsize="marquee"
android:singleLine="true"
android:textSize="16dp" />
</LinearLayout>
</LinearLayout>
<Button
android:id="@+id/prevpage"
style="@style/whitebold"
android:layout_width="100sp"
android:layout_height="30sp"
android:layout_alignBottom="@+id/scroll1"
android:layout_alignParentBottom="true"
android:layout_marginLeft="100sp"
android:background="@drawable/redstyle"
android:onClick="fnnextpage"
android:text="Next Page"
android:textSize="12sp" />
</RelativeLayout>