Friday, April 4, 2014

Send data to the Server like image(captured photo from camera), name, email




import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.LoginButton;

public class CameraActivity extends Activity {

private static final int PICK_IMAGE = 1;
private static final int PICK_Camera_IMAGE = 2;
private ImageView imgView;
private Button upload, skip, btnCameraOn, btnTerm, btnPolicy;
private Bitmap bitmap;
private ProgressDialog dialog;
Uri imageUri;
Session mySession;
int imageFrom;
private UiLifecycleHelper uiHelper;
LoginButton authButton;
MediaPlayer mp = new MediaPlayer();
private String storeDataUrl;
String fb_id, stringBitmap, jsonResponse;
String filePath;
File file;
DefaultHttpClient mHttpClient;
HttpResponse response;
EditText etinternet;
private String internetMessage;
Typeface type_optima_bold;


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

imgView = (ImageView) findViewById(R.id.ImageView);
upload = (Button) findViewById(R.id.imguploadbtn);
btnCameraOn = (Button) findViewById(R.id.btnCameraOn);

etinternet = (EditText)findViewById(R.id.etinternet);
type_optima_bold = Typeface.createFromAsset(getAssets(),
"fonts/Optima Demi Bold.ttf");
etinternet.setTypeface(type_optima_bold);

imageFrom = Global.viaemail;
try {
Bundle b = new Bundle();
b = getIntent().getExtras();
// fb_id = b.getString("facebook_id");
fb_id = Global.fbid;
System.out.println("from camera activity===" + fb_id);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, callback,
savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
}

// ///////////
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
authButton = (LoginButton) findViewById(R.id.authButton);

/*
* authButton.setReadPermissions(Arrays.asList("email", "user_birthday",
* "basic_info"));
*
* authButton.clearPermissions();
*/

/*
* authButton.setPublishPermissions("publish_actions", "email",
* "user_birthday", "basic_info");
*/

btnCameraOn.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
String fileName = "new-photo-name.jpg";
// create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image captured by camera");
// imageUri is the current activity attribute, define and save
// it for
// later usage (also in onSaveInstanceState)
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
// create new Intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, PICK_Camera_IMAGE);
}
});
upload.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
if (bitmap == null) {
/*Toast toast1=Toast.makeText(getApplicationContext(),
"Please select image", Toast.LENGTH_SHORT);
toast1.setGravity(Gravity.TOP | Gravity.CENTER, 0, 400);
toast1.show();*/
internetMessage = etinternet.getText().toString();
myAlertBox(internetMessage);
} else {

new ImageGalleryTask().execute();
}
}
});





}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri selectedImageUri = null;
uiHelper.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {

case PICK_Camera_IMAGE:
if (resultCode == RESULT_OK) {
// use imageUri here to access the image
selectedImageUri = imageUri;

} else if (resultCode == RESULT_CANCELED) {
Toast toast2=Toast.makeText(this, "Picture was not taken",
Toast.LENGTH_SHORT);
toast2.setGravity(Gravity.TOP | Gravity.CENTER, 0, 400);
toast2.show();
} else {
Toast toast3=Toast.makeText(this, "Picture was not taken",
Toast.LENGTH_SHORT);
toast3.setGravity(Gravity.TOP | Gravity.CENTER, 0, 400);
toast3.show();
}
break;
}

if (selectedImageUri != null) {
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();

// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);

if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast toast4=Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG);
toast4.setGravity(Gravity.TOP | Gravity.CENTER, 0, 400);
toast4.show();

Log.e("Bitmap", "Unknown path");
}

if (filePath != null) {
file = new File(filePath);
decodeFile(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast toast5=Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG);
toast5.setGravity(Gravity.TOP | Gravity.CENTER, 0, 400);
toast5.show();

Log.e(e.getClass().getName(), e.getMessage(), e);
}
}

}

private Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state,
Exception exception) {
mySession = session;
System.out.println("statusCallBack Called");
onSessionStateChange(session, state, exception);

}
};

private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
authButton.setVisibility(View.GONE);
} else if (state.isClosed()) {
authButton.setVisibility(View.VISIBLE);
}
}

@Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}

@Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}

@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}

class ImageGalleryTask extends AsyncTask<Void, Void, String> {

@Override
protected void onPreExecute() {
dialog = ProgressDialog.show(CameraActivity.this, "Uploading",
"Please wait...", true);
super.onPreExecute();
}

@Override
protected String doInBackground(Void... unsued) {

if (imageFrom == 1) {
// put the uploading of image,name and email like else part
try {
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
mHttpClient = new DefaultHttpClient();
File file = new File(filePath);
HttpPost httppost = new HttpPost("paste server url");
MultipartEntity entity = new MultipartEntity();
entity.addPart("name", new StringBody(Global.name));
entity.addPart("email", new StringBody(Global.email));
entity.addPart("file", new FileBody(file));
httppost.setEntity(entity);
response = mHttpClient.execute(httppost);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {

try {
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
mHttpClient = new DefaultHttpClient();
File file = new File(filePath);
HttpPost httppost = new HttpPost("paste server url");
MultipartEntity entity = new MultipartEntity();
entity.addPart("fb_id", new StringBody(fb_id));
entity.addPart("file", new FileBody(file));
httppost.setEntity(entity);
response = mHttpClient.execute(httppost);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

return null;

}

@Override
protected void onProgressUpdate(Void... unsued) {

}

@Override
protected void onPostExecute(String sResponse) {
try {
if(imageFrom==1){
System.out.println("Global.name========"+Global.name);
System.out.println("Global.email==="+Global.email);
}else{
System.out.println("imageFrom="+imageFrom);
}
System.out.println("filepath is===" + filePath);
HttpEntity r_entity = response.getEntity();
String responseString = EntityUtils.toString(r_entity);
Log.i("UPLOAD==", responseString);
System.out.println("respose from camera multipart==="
+ responseString);
if (dialog.isShowing())
dialog.dismiss();
Intent in = new Intent(getApplicationContext(),
ThankYouActivity.class);
in.putExtra("session", mySession);
startActivity(in);
} catch (Exception e) {
Toast toast6=Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG);
toast6.setGravity(Gravity.TOP | Gravity.CENTER, 0, 400);
toast6.show();

Log.e(e.getClass().getName(), e.getMessage(), e);
}
}

}

public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}



public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);

// The new size we want to scale to
final int REQUIRED_SIZE = 1024;

// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}

// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);

System.out.println("what is bitmap==" + bitmap);
stringBitmap = BitMapToString(bitmap);
System.out.println("String bitmap is==" + stringBitmap);
imgView.setImageBitmap(bitmap);

}

// convert bitmap to string
public String BitMapToString(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String strBitMap = Base64.encodeToString(b, Base64.DEFAULT);
return strBitMap;
}
public void myAlertBox(String msg) {
final Dialog dialog1 = new Dialog(CameraActivity.this);
dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog1.setContentView(R.layout.my_custom_popup_alert);

Button ok = (Button) dialog1.findViewById(R.id.button1);
TextView tv = (TextView) dialog1.findViewById(R.id.tv1);
tv.setTypeface(type_optima_bold);
tv.setText(msg);
ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog1.dismiss();
//startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
//finish();
}
});
dialog1.show();
}

}

Friday, February 21, 2014

Android Coding: Pass data from Service to Activity

Android Coding: Pass data from Service to Activity: original

manifestfile

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.techblogon.serviceexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.techblogon.serviceexample.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:enabled="true" android:name=".MyService" />
    </application>

</manifest>
MyService.java

package com.techblogon.serviceexample;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service{

private static final String TAG = "MyService";

@Override
public IBinder onBind(Intent arg0) {
return null;
}

@Override
public void onCreate() {

Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}

@Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}

@Override
public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
}

For services started

MainActivity.java

package com.techblogon.serviceexample;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {

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

//start the service
public void onClickStartServie(View V)
{
//start the service from here //MyService is your service class name
startService(new Intent(this, MyService.class));
}
//Stop the started service
public void onClickStopService(View V)
{
//Stop the running service from here//MyService is your service class name
//Service will only stop if it is already running.
stopService(new Intent(this, MyService.class));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}

Test

DBHelper
=================
package com.kitchen.dbhelper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

import com.kitchen.ItemPojo;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.os.Environment;
import android.util.Log;

public class DataBaseHelper extends SQLiteOpenHelper {
private static String DB_NAME = "mykitchen.sqlite";
public static final int MYDATABASE_VERSION = 1;
private static String packageName = "com.kitchen";
private SQLiteDatabase myDataBase;
private final Context myContext;
public static final String KITCHEN_ORDER = "kitchen";
public static final String WAITER_ORDER = "waiterOrder";
public static final String TB_SETTINGS = "settings";
public static final String TB_USER_LIST = "userList";
public static final String TB_ITEMS = "items";
public static final String TB_ORDER_LIST = "order_list";

private static final String CREATE_KITCHEN_ORDER = "CREATE TABLE IF NOT EXISTS  "
+ KITCHEN_ORDER
+ "(order_id varchar(20),"
+ "waiter_id varchar(10),"
+ "item_name varchar(30),"
+ "quantity varchar(20),"
+ "availability varchar(30),"
+ "done varchar(20),"
+ "time_taken varchar(15));";

private static final String CREATE_WAITER_REQUEST = "CREATE TABLE IF NOT EXISTS  "
+ WAITER_ORDER
+ "(waiter_id varchar(10) primary key,"
+ "request_id varchar(10),"
+ "request varchar(30),"
+ "status varchar(5));";

private static final String CREATE_SETTINGS = "CREATE TABLE IF NOT EXISTS  "
+ TB_SETTINGS
+ "(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name character varying(255) NOT NULL,"
+ "value character varying(255) NOT NULL,"
+ "updated_time timestamp without time zone);";

private static final String CREATE_USER_LIST = "CREATE TABLE IF NOT EXISTS  "
+ TB_USER_LIST
+ "(id long NOT NULL,"
+ "name character varying(255) NOT NULL,"
+ "password character varying(255) NOT NULL,"
+ "role character varying(255) NOT NULL);";

private static final String CREATE_ITEMS = "CREATE TABLE IF NOT EXISTS  "
+ TB_ITEMS + "(id long NOT NULL,"
+ "classification character varying(255) NOT NULL,"
+ "name character varying(255) NOT NULL,"
+ "price double precision NOT NULL,"
+ "CONSTRAINT items_pkey PRIMARY KEY (id),"
+ "CONSTRAINT items_name_key UNIQUE (name));";
private static final String CREATE_ORDER_LIST = "CREATE TABLE IF NOT EXISTS  "
+ TB_ORDER_LIST
+ "(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "discount_amount double precision NOT NULL,"
+ "service_tax double precision NOT NULL,"
+ "total_value double precision NOT NULL,"
+ "waiter_assigned_orderid long NOT NULL,"
+ "waiter_id long);";

private static final String TAG = "DataBaseHelper";


public DataBaseHelper(Context context) {

super(context, DB_NAME, null, 1);
myContext = context;
try {
myDataBase = myContext.openOrCreateDatabase(DB_NAME, 1, null);

} catch (Exception e) {
e.printStackTrace();
}

try {
System.out.println("Database settings start.");
myDataBase.execSQL(CREATE_KITCHEN_ORDER);
myDataBase.execSQL(CREATE_WAITER_REQUEST);
myDataBase.execSQL(CREATE_SETTINGS);
myDataBase.execSQL(CREATE_USER_LIST);
myDataBase.execSQL(CREATE_ITEMS);
myDataBase.execSQL(CREATE_ORDER_LIST);

System.out.println("Database settings done.");

} catch (SQLException e) {
e.printStackTrace();
}

}

@Override
public void onCreate(SQLiteDatabase db) {

try {

} catch (Exception e) {

e.printStackTrace();
}

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

Log.w("DATABASE UPGRADE", "Upgrading database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS kitchen_table");
onCreate(db);

}
public int deleteAll() {

int f = 1;

myDataBase.delete(TB_USER_LIST, null, null);

return f;
}
public Cursor getOrder() {
try {
//storeDataToSDCard();
//importDB();
String selectQuery = "SELECT * FROM " + KITCHEN_ORDER + ";";

Cursor c = myDataBase.rawQuery(selectQuery, null);
if (c != null)
return c;
else
return null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

public boolean addKitchenOrder(String oid, String wid,
String iName, String qty, String avi, String done,
String time_taken) {

try {
myDataBase
.execSQL("INSERT INTO "
+ KITCHEN_ORDER
+ " (order_id,item_name,quantity,availability,done,waiter_id,time_taken) Values"
+ "('" + oid + "','" + iName + "','" + qty
+ "','" + avi + "','" + done + "','" + wid + "','" + time_taken + "') ");
return true;

} catch (SQLException e) {
e.printStackTrace();
return false;
}

}
public void storeDataToSDCard() {
try {
File sd = Environment.getExternalStorageDirectory();
String sd1 = Environment.getExternalStorageState();
File data = Environment.getDataDirectory();
Log.i(TAG, "Environment.MEDIA_MOUNTED.equals(sd1)="
+ Environment.MEDIA_MOUNTED.equals(sd1));
// if (Environment.MEDIA_MOUNTED.equals(sd1)) {
if (sd.canWrite()) {
String currentDBPath = "//data//" + packageName
+ "//databases//" + DB_NAME;
String backupDBPath = DB_NAME;
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
Log.i(TAG, "currentDB=" + currentDB);
Log.i(TAG, "backupDB=" + backupDB);

FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();

}
} catch (Exception e) {

}
}
private void importDB() {
         // TODO Auto-generated method stub

         try {
             File sd = Environment.getExternalStorageDirectory();
             File data  = Environment.getDataDirectory();
             Log.i(TAG, "importDB data="+data);
             Log.i(TAG, "importDB sd="+sd);
             if (sd.canWrite()) {
                 String  currentDBPath= "//data//" + packageName
                         + "//databases//" + "mykitchen.sqlite";
                 Log.i(TAG, "importDB currentDBPath="+currentDBPath);
                 String backupDBPath  = "/mykitchen.sqlite";
                 File  backupDB= new File(data, currentDBPath);
                 File currentDB  = new File(sd, backupDBPath);
                 Log.i(TAG, "importDB backupDB="+backupDB);
                 Log.i(TAG, "importDB currentDB="+currentDB);

                 FileChannel src = new FileInputStream(currentDB).getChannel();
                 FileChannel dst = new FileOutputStream(backupDB).getChannel();
                 dst.transferFrom(src, 0, src.size());
                 src.close();
                 dst.close();

             }
         } catch (Exception e) {

         }
     }
public void updateCategory(int vcid, String name, String date,
String place, String nextDate) {
try {
System.out.println("UPDATE " + TB_CATEGORY + " SET VCNAME='" + name
+ "',PLACE='" + place + "',NEXT_DUE_DATE='" + nextDate
+ "',VACCINATION_DATE='" + date + "' where VCID='" + vcid
+ "';");
myDataBase.execSQL("UPDATE " + TB_CATEGORY + " SET VCNAME='" + name
+ "',PLACE='" + place + "',NEXT_DUE_DATE='" + nextDate
+ "',VACCINATION_DATE='" + date + "' where VCID='" + vcid
+ "';");
storeDataToSDCard();
} catch (Exception e) {
e.printStackTrace();
}

}
public String getSettings() {
// TODO Auto-generated method stub
String value = "192.168.0.103";
Cursor c = myDataBase.rawQuery("SELECT value FROM settings", null);
Log.e("Testing", "c.getColumnCount()=" + c.getColumnCount());
Log.e("Testing", "c.getCount()=" + c.getCount());
try {
if (c != null) {
if (c.moveToFirst()) {
do {

value = c.getString(c.getColumnIndex("value"));

} while (c.moveToNext());
}

c.close();
return value;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;

}

public void saveSettings(String name, String ip,
String upTime) {
// TODO Auto-generated method stub
try {

SQLiteStatement stmt = myDataBase
.compileStatement("INSERT INTO  settings(name,value,updated_time) Values (?,?,?)");
stmt.bindString(1, name);
stmt.bindString(2, ip);
stmt.bindString(3, upTime);
stmt.execute();

} catch (Exception e) {
e.printStackTrace();
}
}
public void putUserData(long useridlong, String name,
String pwd, String role) {
// TODO Auto-generated method stub
try {
SQLiteStatement stmt = myDataBase
.compileStatement("INSERT INTO  userList(id,name,password,role) Values (?,?,?,?)");
stmt.bindLong(1, useridlong);
stmt.bindString(2, name);
stmt.bindString(3, pwd);
stmt.bindString(4, role);
stmt.execute();

} catch (Exception e) {
e.printStackTrace();
}
}

public boolean getvalidUser(String uid, String pwd) {
// TODO Auto-generated method stub
Cursor c = myDataBase.rawQuery("SELECT * FROM userList where id= '"+uid+"' and password= '"+pwd+"'", null);
Log.e("Testing", "c.getColumnCount()=" + c.getColumnCount());
Log.e("Testing", "c.getCount()=" + c.getCount());
if(c.getCount()==0){
return false;
}else{
return true;
}
}

public void insertItemData(long item_id, String name,
String classification, double item_price) {
try {
SQLiteStatement stmt = myDataBase
.compileStatement("INSERT INTO  items(id,name,classification,price) Values (?,?,?,?)");
stmt.bindLong(1, item_id);
stmt.bindString(2, name);
stmt.bindString(3, classification);
stmt.bindDouble(4, item_price);
stmt.execute();
} catch (Exception e) {
e.printStackTrace();
}

}
public List<ItemPojo> getItemData() {
// TODO Auto-generated method stub
List<ItemPojo> itemdata = new ArrayList<ItemPojo>();
Cursor c = myDataBase.rawQuery("SELECT * FROM items", null);
Log.e("Testing", "c.getColumnCount()=" + c.getColumnCount());
Log.e("Testing", "c.getCount()=" + c.getCount());
try {
if (c != null) {
if (c.moveToFirst()) {
do {
ItemPojo cat = new ItemPojo();

cat.setItem_id(c.getLong(c.getColumnIndex("id")));
cat.setClassification(c.getString(c.getColumnIndex("classification")));
cat.setName(c.getString(c.getColumnIndex("name")));
cat.setItem_price(c.getDouble(c.getColumnIndex("price")));
itemdata.add(cat);

} while (c.moveToNext());
}

c.close();
return itemdata;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;

}

public void insertOrderList(long waiter_assign_order_id, double total,
double serviceTax, long waiter_id, double disAmount) {
// TODO Auto-generated method stub
try {

SQLiteStatement stmt = myDataBase
.compileStatement("INSERT INTO  order_list(waiter_assigned_orderid,total_value,service_tax,waiter_id,discount_amount) Values (?,?,?,?,?)");
stmt.bindLong(1, waiter_assign_order_id);
stmt.bindDouble(2, total);
stmt.bindDouble(3, serviceTax);
stmt.bindLong(4, waiter_id);
stmt.bindDouble(5, disAmount);
stmt.execute();
} catch (Exception e) {
e.printStackTrace();
}

}
}
MyOrder.java
================
package com.kitchen;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.kitchen.dbhelper.DataBaseHelper;

public class MainOrderActivity extends ListActivity {
private static final String TAG = "MainActivity";
public final ArrayList<HashMap<String, Object>> kitchenlist = new ArrayList<HashMap<String, Object>>();
DataBaseHelper db;
Cursor cursor;
DataBaseHelper database;
LazyAdapter adapter1;
ListView list;
SimpleAdapter adapter;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order_details);
TextView tvMenu=(TextView) findViewById(R.id.tvMenu);
//database = new DataBaseHelper(this);
try {
//cursor = database.getOrder();
//Log.i(TAG, "cursor=" + cursor);
//new MYAsyncTask().execute("");
//cursor.close();
//database.close();
} catch (Exception e) {
e.printStackTrace();
}
tvMenu.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent in = new Intent(MainOrderActivity.this, WaiterLogin.class);
startActivity(in);
}
});
}

class MYAsyncTask extends AsyncTask<String, Void, Integer> {

private ProgressDialog dialog1;

@Override
protected void onPreExecute() {
dialog1 = ProgressDialog.show(MainOrderActivity.this, "", "Loading...");
super.onPreExecute();
}

@Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
adapter = new SimpleAdapter(getApplicationContext(), kitchenlist,
R.layout.new_kitchen_order_adapter, new String[] { "order_id",
"item_name", "quantity", "availability" }, new int[] { R.id.tvOrderNo,
R.id.tvMenuItems1, R.id.tvQty, R.id.tvState });
setListAdapter(adapter);
dialog1.dismiss();
super.onPostExecute(result);
}

@Override
protected Integer doInBackground(String... params) {
// TODO Auto-generated method stub
try {
if (cursor != null) {

if (cursor.moveToFirst()) {
do {
String order_id = cursor.getString(cursor
.getColumnIndex("order_id"));
String waiter_id = cursor.getString(cursor
.getColumnIndex("waiter_id"));
String item_name = cursor.getString(cursor
.getColumnIndex("item_name"));
String quantity = cursor.getString(cursor
.getColumnIndex("quantity"));
String availability = cursor.getString(cursor
.getColumnIndex("availability"));
String done = cursor.getString(cursor
.getColumnIndex("done"));
String time_taken = cursor.getString(cursor
.getColumnIndex("time_taken"));

Log.i(TAG, "order_id=" + order_id);
Log.i(TAG, "waiter_id=" + waiter_id);
Log.i(TAG, "item_name=" + item_name);
Log.i(TAG, "quantity=" + quantity);
Log.i(TAG, "availability=" + availability);
Log.i(TAG, "done=" + done);
Log.i(TAG, "time_taken=" + time_taken);

HashMap<String, Object> map = new HashMap<String, Object>();

map.put("order_id", order_id);
map.put("waiter_id", waiter_id);
map.put("item_name", item_name);
map.put("quantity", quantity);
map.put("availability", availability);
if (done.equalsIgnoreCase("yes"))
map.put("done=", true);
else
map.put("done", false);

map.put("time_taken", time_taken);

kitchenlist.add(map);

} while (cursor.moveToNext());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

}
Login
================
package com.restaurant;

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

import android.R.anim;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.restaurant.database.RestaurantDbHelper;

public class LoginActivity extends Activity {

private static final String TAG = "LoginActivity";
private RestaurantDbHelper mySQLiteAdapter;
Button btnSubmit;
String urlCat, catClass,selName;
Spinner spnWaiterName, spnOrderNumber;
List<String> waiter_list = new ArrayList<String>();
List<String> order_list = new ArrayList<String>();
List<String> temp_list = new ArrayList<String>();
ArrayAdapter<String> a1, a2;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
urlCat = "http://" + (GlobalData.localhost).trim()
+ ":8080/turnr-server/category/all";

//mySQLiteAdapter = new RestaurantDbHelper(LoginActivity.this);

btnSubmit = (Button) findViewById(R.id.btnSubmit);
spnWaiterName = (Spinner) findViewById(R.id.spnWaiterName);
spnOrderNumber = (Spinner) findViewById(R.id.spnOrderNumber);
mySQLiteAdapter = new RestaurantDbHelper(LoginActivity.this);
mySQLiteAdapter.delAll();
mySQLiteAdapter.waiterTableData("Faiz", 1);
mySQLiteAdapter.waiterTableData("Faiz", 2);
mySQLiteAdapter.waiterTableData("Faiz", 3);
mySQLiteAdapter.waiterTableData("Faiz", 4);
mySQLiteAdapter.waiterTableData("Faiz", 5);
mySQLiteAdapter.waiterTableData("Mahesh", 6);
mySQLiteAdapter.waiterTableData("Mahesh", 7);
mySQLiteAdapter.waiterTableData("Mahesh", 8);
mySQLiteAdapter.waiterTableData("Mahesh", 9);
mySQLiteAdapter.waiterTableData("Mahesh", 10);
mySQLiteAdapter.waiterTableData("Arun", 11);
mySQLiteAdapter.waiterTableData("Arun", 12);
mySQLiteAdapter.waiterTableData("Arun", 13);
mySQLiteAdapter.waiterTableData("Arun", 14);
mySQLiteAdapter.waiterTableData("Arun", 15);
mySQLiteAdapter.waiterTableData("Manoj", 16);
mySQLiteAdapter.waiterTableData("Manoj", 17);
mySQLiteAdapter.waiterTableData("Manoj", 18);
mySQLiteAdapter.waiterTableData("Manoj", 19);
mySQLiteAdapter.waiterTableData("Manoj", 20);
waiter_list=mySQLiteAdapter.getWaiterName();
/*waiter_list.add("Faiz");
waiter_list.add("Mahesh");
waiter_list.add("Arun");
waiter_list.add("Manoj");
order_list.add("1");
order_list.add("2");
order_list.add("3");
order_list.add("4");*/
order_list=mySQLiteAdapter.getWaiterTableNo(waiter_list.get(0));

Log.i(TAG, "XXXXXXXX="+order_list.size());
a1 = new ArrayAdapter<String>(this, R.drawable.spn_text_color,
waiter_list);
a1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spnWaiterName.setAdapter(a1);

a2 = new ArrayAdapter<String>(this, R.drawable.spn_text_color,
order_list);
a2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spnOrderNumber.setAdapter(a2);

btnSubmit.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
mySQLiteAdapter.deleteOrders();
dialog_func();

}
});
spnWaiterName.setOnItemSelectedListener(new OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
selName=spnWaiterName.getSelectedItem().toString();
temp_list.clear();
temp_list=mySQLiteAdapter.getWaiterTableNo(selName);
Log.i(TAG, "TTTTTTTTTTT="+temp_list.size());
order_list.clear();
order_list.addAll(temp_list);
a2.notifyDataSetChanged();
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}

public void dialog_func() {

final Dialog dialog1 = new Dialog(this);
dialog1.setCanceledOnTouchOutside(false);
dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog1.setContentView(R.layout.custom_alert);

Button cancel = (Button) dialog1.findViewById(R.id.btnCancel);
Button grouping = (Button) dialog1.findViewById(R.id.btnGrouping);
Button newgroup = (Button) dialog1.findViewById(R.id.btnNew);
TextView tv = (TextView) dialog1.findViewById(R.id.tvPleaseConfirm);
ImageView  imgClose=(ImageView) dialog1.findViewById(R.id.imgClose);
tv.setText("Please confirm the grouping.");
imgClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog1.dismiss();
}

});
newgroup.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog1.dismiss();
Intent intent = new Intent(getApplicationContext(),
HomeActivity.class);
startActivity(intent);
finish();
}

});
grouping.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog1.dismiss();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog1.dismiss();

}
});
dialog1.show();

}
}
IPConfig.java
=================
package com.kitchen;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.kitchen.dbhelper.DataBaseHelper;
import com.kitchen.validate.IPAddressValidator;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class IPCofigActivity extends Activity implements OnClickListener {

// json data
private static final String TAG_USERLIST = "userList";
private static final String TAG_USERID = "id";
private static final String TAG_PASSWORD = "password";
private static final String TAG_NAME = "name";
private static final String TAG_ROLE = "role";
String chk;
Button btnSave;
EditText etIp;
String ip, name = "IP Address", upTime, url;
private DataBaseHelper mySQLiteAdapter;
SimpleDateFormat sdf;
JSONArray userList = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ip_address);
btnSave = (Button) findViewById(R.id.btnSave);
etIp = (EditText) findViewById(R.id.etIp);
btnSave.setOnClickListener(this);
mySQLiteAdapter = new DataBaseHelper(this);
String oldIP = mySQLiteAdapter.getSettings();
etIp.setText("" + oldIP);
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnSave:
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
upTime = sdf.format(new Date());
Log.e("Testing Time", "upTime=" + upTime);
ip = etIp.getText().toString();
IPAddressValidator ipval = new IPAddressValidator();
boolean validateIP = ipval.validate(ip);

if (!ip.equalsIgnoreCase("")) {
if (validateIP) {
GlobalData.localhost=ip;
url = "http://" + (GlobalData.localhost).trim()
+ ":8080/turnr-server/user/all";
System.out.println("url====" + url);
mySQLiteAdapter.saveSettings(name, ip, upTime);
mySQLiteAdapter.close();
GlobalData.localhost = ip;
Toast.makeText(IPCofigActivity.this,
"IP Address Configured successfully",
Toast.LENGTH_LONG).show();
new AsyncGetCatData().execute(url);

} else {
alertbox("IP Configuration",
"Please enter Valid IP Address.");
}
} else {
alertbox("IP Configuration", "Please enter IP Address.");
}
break;
}
}

public void alertbox(String title, String mymessage) {
new android.app.AlertDialog.Builder(this)
.setMessage(mymessage)
.setTitle(title)
.setCancelable(true)
.setNegativeButton(android.R.string.ok,
new android.content.DialogInterface.OnClickListener() {
public void onClick(
android.content.DialogInterface dialog,
int whichButton) {
}
}).show();

}

class AsyncGetCatData extends AsyncTask<String, Void, Integer> {

private ProgressDialog dialog1;

@Override
protected Integer doInBackground(String... params) {

try {
JSONParser jParser1 = new JSONParser();
// getting JSON string from URL
JSONObject json1 = jParser1.getJSONFromUrl(url);
// Getting Array of Contacts
System.out.println("json1.toString()====" + json1.toString());
if (json1.toString() != null) {
userList = json1.getJSONArray(TAG_USERLIST);

// looping through All Contacts
for (int i = 0; i < userList.length(); i++) {
JSONObject c = userList.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_USERID);
String name = c.getString(TAG_NAME);
String pwd = c.getString(TAG_PASSWORD);
String role = c.getString(TAG_ROLE);

long useridlong = Long.parseLong(id);
System.out.println("useridlong====" + useridlong);
System.out.println("name====" + name);
System.out.println("pwd====" + pwd);
if (role.equalsIgnoreCase("Waiter")) {
mySQLiteAdapter.putUserData(useridlong, name,
pwd, role);
}

}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog1 = ProgressDialog.show(IPCofigActivity.this, "",
"Loading...");

super.onPreExecute();
}

@Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
dialog1.dismiss();
Intent intent1 = new Intent(getApplicationContext(),
WaiterLogin.class);
startActivity(intent1);
finish();
super.onPostExecute(result);
}

}
}