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);
}

}
}


CRUD operation in Android

MainActivity.java 
============

package com.crudoperation;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

EditText etName, etRollno, etClass, etRowID;
Button btnAdd, btnView, btnDelete, btnUpdate, btnViewById;

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

etName = (EditText) findViewById(R.id.etName);
etRollno = (EditText) findViewById(R.id.etRollno);
etClass = (EditText) findViewById(R.id.etClass);
etRowID = (EditText) findViewById(R.id.etRowId);

btnAdd = (Button) findViewById(R.id.btnAdd);
btnView = (Button) findViewById(R.id.btnView);
btnDelete = (Button) findViewById(R.id.btnDelete);
btnUpdate = (Button) findViewById(R.id.btnUpdate);
btnViewById = (Button) findViewById(R.id.btnViewById);

btnAdd.setOnClickListener(this);
btnView.setOnClickListener(this);
btnDelete.setOnClickListener(this);
btnUpdate.setOnClickListener(this);
btnViewById.setOnClickListener(this);

}

public void onClick(View v) {
switch (v.getId()) {
case R.id.btnAdd:

boolean didItWork = true;
try {
String name = etName.getText().toString();
String rollno = etRollno.getText().toString();
String sclass = etClass.getText().toString();

MySQLiteDatabase entry = new MySQLiteDatabase(MainActivity.this);
entry.open();
entry.createEntry(name, rollno, sclass);
entry.close();

etName.setText("");
etRollno.setText("");
etClass.setText("");

} catch (Exception e) {
didItWork = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Dang it!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
} finally {
if (didItWork) {
Dialog d = new Dialog(this);
d.setTitle("Adding!");
TextView tv = new TextView(this);
tv.setText("Success");
d.setContentView(tv);
d.show();
}
}

break;
case R.id.btnView:
Intent i = new Intent(getApplicationContext(),SQLiteView.class);
startActivity(i);
break;
case R.id.btnViewById:
try {
String s = etRowID.getText().toString();
long l = Long.parseLong(s);
MySQLiteDatabase hon = new MySQLiteDatabase(this);
hon.open();
String returnedName = hon.getName(l);
String returnedRollno = hon.getRollno(l);
String returnedClass = hon.getClasss(l);
hon.close();

etName.setText(returnedName);
etRollno.setText(returnedRollno);
etClass.setText(returnedClass);
} catch (Exception e) {

String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Oh Sit!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
break;

case R.id.btnUpdate:
try {
String mName = etName.getText().toString();
String mRollno = etRollno.getText().toString();
String mClass = etClass.getText().toString();

String sRow = etRowID.getText().toString();
long lRow = Long.parseLong(sRow);

MySQLiteDatabase ex = new MySQLiteDatabase(this);
ex.open();
ex.updateEntry(lRow, mName, mRollno, mClass);
ex.close();

etName.setText("");
etRollno.setText("");
etClass.setText("");

Toast.makeText(getApplicationContext(), "Row Updated Successfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {

String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Oh Sit!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
break;
case R.id.btnDelete:
try {
String sRow1 = etRowID.getText().toString();
long lRow1 = Long.parseLong(sRow1);
MySQLiteDatabase ex1 = new MySQLiteDatabase(this);
ex1.open();
ex1.deleteEntry(lRow1);
ex1.close();
Toast.makeText(getApplicationContext(), "Row Deleted Successfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {

String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Oh Sit!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
break;
}
}

}
SQLiteView
=============
package com.crudoperation;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class SQLiteView extends Activity{

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

TextView info=(TextView)findViewById(R.id.tvSQLinfo);

MySQLiteDatabase myDb=new MySQLiteDatabase(this);

myDb.open();
String data=myDb.getData();
myDb.close();
info.setText(data);


}

}

MySQLiteDatabase 
==================
package com.crudoperation;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MySQLiteDatabase {

public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_ROLLNO = "rollno";
public static final String KEY_CLASS = "class";

private static final String DATABASE_NAME = "studentdatabase";
private static final String DATABASE_TABLE = "student";
private static final int DATABASE_VERSION = 1;

private MyDbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;

private static class MyDbHelper extends SQLiteOpenHelper {

public MyDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME
+ " TEXT NOT NULL, " + KEY_ROLLNO + " TEXT NOT NULL, "
+ KEY_CLASS + " TEXT NOT NULL);"
);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + DATABASE_TABLE);
onCreate(db);
}

}

public MySQLiteDatabase(Context c) {
ourContext = c;
}

public MySQLiteDatabase open() throws SQLException {

ourHelper = new MyDbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();

return this;
}

public void close() {
ourDatabase.close();
}

public long createEntry(String name, String rollno, String sClass) {
ContentValues cv = new ContentValues();

cv.put(KEY_NAME, name);
cv.put(KEY_ROLLNO, rollno);
cv.put(KEY_CLASS, sClass);

return ourDatabase.insert(DATABASE_TABLE, null, cv);
}

public String getData() {
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_ROLLNO,
KEY_CLASS };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
null, null);
String result = "";

int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iRollno = c.getColumnIndex(KEY_ROLLNO);
int iClass = c.getColumnIndex(KEY_CLASS);

for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " " + c.getString(iName)
+ " " + c.getString(iRollno) + " " + c.getString(iClass)
+ "\n";
}

return result;
}

public String getName(long l) throws SQLException {
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_ROLLNO,
KEY_CLASS };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
+ l, null, null, null, null);
if (c != null) {
c.moveToFirst();
String name = c.getString(1);
return name;
}
return null;
}

public String getRollno(long l) throws SQLException {
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_ROLLNO,
KEY_CLASS };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
+ l, null, null, null, null);
if (c != null) {
c.moveToFirst();
String rollno = c.getString(2);
return rollno;
}
return null;
}

public String getClasss(long l) throws SQLException {
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_ROLLNO,
KEY_CLASS };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
+ l, null, null, null, null);
if (c != null) {
c.moveToFirst();
String sclass = c.getString(3);
return sclass;
}
return null;
}

public void updateEntry(long lRow, String mName, String mRollno,
String mClass) throws SQLException {
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_NAME, mName);
cvUpdate.put(KEY_ROLLNO, mRollno);
cvUpdate.put(KEY_CLASS, mClass);
ourDatabase.update(DATABASE_TABLE, cvUpdate, KEY_ROWID + "=" + lRow,
null);
}

public void deleteEntry(long lRow1) throws SQLException {
ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + lRow1, null);
}

}

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:paddingLeft="@dimen/activity_horizontal_margin"
    tools:context=".MainActivity" >

    <LinearLayout
        android:id="@+id/linName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tvName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name:" />

        <EditText
            android:id="@+id/etName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10" >

            
        </EditText>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linRollNo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/linName"
        android:layout_below="@+id/linName"
        android:layout_marginTop="16dp"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tvRollNo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Roll No:" />

        <EditText
            android:id="@+id/etRollno"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="number" >
        </EditText>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linClass"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linRollNo"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="26dp"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tvClass"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Class:" />

        <EditText
            android:id="@+id/etClass"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linAddView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/linClass"
        android:layout_marginTop="36dp"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btnAdd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add" />

        <Button
            android:id="@+id/btnView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:text="View" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linRowId"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/linAddView"
        android:layout_marginTop="24dp"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tvRowId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Row ID:" />

        <EditText
            android:id="@+id/etRowId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linUpdate"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/linRowId"
        android:layout_marginTop="26dp"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btnViewById"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ViewById" />

        <Button
            android:id="@+id/btnDelete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Delete" />

        <Button
            android:id="@+id/btnUpdate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Update" />
    </LinearLayout>

</RelativeLayout>

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

    <TableLayout
        android:id="@+id/tableLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TableRow>

            <TextView
                android:id="@+id/tvID"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Student ID" />

            <TextView
                android:id="@+id/tvName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="Name:" />

            <TextView
                android:id="@+id/tvRollno"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="Roll No:" />

            <TextView
                android:id="@+id/tvClass"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="Class" />
        </TableRow>
    </TableLayout>

    <TextView
        android:id="@+id/tvSQLinfo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="get info from db" >
    </TextView>

</LinearLayout>

AndroidManifest.xml
=====================

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.crudoperation.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>
        <activity android:name=".SQLiteView" >
            <intent-filter>
                <action android:name="com.crudoperation.SQLVIEW" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>