Friday, 16 August 2013
Thursday, 15 August 2013
Database for Android
1)DBAdapter
package com.BabyName.DB;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBAdapter {
private final String DATABASE_NAME = "weed.sqlite";
private final int DATABASE_VERSION = 1;
private Context context;
private DatabaseHelper DBHelper;
//private static SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
public class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
// db.execSQL(DATABASE_CREATE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//onCreate(db);
}
}
// ---opens the database---
@SuppressWarnings("unused")
public DBAdapter open() throws SQLException {
SQLiteDatabase db = DBHelper.getWritableDatabase();
return this;
}
// ---closes the database---
public void close() {
DBHelper.close();
}
}
package com.BabyName.DB;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBAdapter {
private final String DATABASE_NAME = "weed.sqlite";
private final int DATABASE_VERSION = 1;
private Context context;
private DatabaseHelper DBHelper;
//private static SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
public class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
// db.execSQL(DATABASE_CREATE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//onCreate(db);
}
}
// ---opens the database---
@SuppressWarnings("unused")
public DBAdapter open() throws SQLException {
SQLiteDatabase db = DBHelper.getWritableDatabase();
return this;
}
// ---closes the database---
public void close() {
DBHelper.close();
}
}
2) Define String
package com.BabyName.DB;
public class in {
public String babyid="";
public String babygender="";
public String babyname="";
public String meaning="";
public String descr="";
public String castid="";
public String religionid="";
public String languageid="";
public String rashiid="";
public int isfav=0;
}
3)databasehelper
package com.BabyName.DB;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class databasehelper extends SQLiteOpenHelper {
private static String DATABASE_NAME = "BabyNamesDataBase.sqlite";
private SQLiteDatabase myDataBase;
private Context myContext;
@SuppressWarnings("unused")
private String TAG = this.getClass().getSimpleName();
private String path = "/data/data/com.BabyName/databases/";
public databasehelper(Context context) {
super(context, DATABASE_NAME, null, 1);
this.myContext = context;
}
// ---Create the database---
public void createDataBase() throws IOException {
// ---Check whether database is already created or not---
boolean dbExist = checkDataBase();
if (!dbExist) {
this.getReadableDatabase();
try {
// ---If not created then copy the database---
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
this.close();
}
}
// --- Check whether database already created or not---
private boolean checkDataBase() {
try {
String myPath = path + DATABASE_NAME;
File f = new File(myPath);
if (f.exists())
return true;
else
return false;
} catch (SQLiteException e) {
e.printStackTrace();
return false;
}
}
// --- Copy the database to the output stream---
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
String outFileName = path + DATABASE_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
// --- Open the database---
String myPath = path + DATABASE_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
myDataBase.setLockingEnabled(false);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase arg0) {
//arg0.execSQL("CREATE TABLE Msg (id text,title text,body text,date1 text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void update_delete_insertquery(String s) {
myDataBase.execSQL(s);
}
public Cursor selectquery(String s) {
return myDataBase.rawQuery(s, null);
}
public ArrayList<BabyNameDB> getAllBabynames() {
ArrayList<BabyNameDB> loc_infos = new ArrayList<BabyNameDB>();
openDataBase();
Cursor c = myDataBase
.rawQuery(
"SELECT * FROM babynamestable", null);
if (c != null) {
if (c.moveToFirst()) {
do {
BabyNameDB loc = new BabyNameDB();
loc.babyid = c.getString(0).trim();
loc.babygender = c.getString(1).trim();
loc.babyname = c.getString(2).trim();
loc.meaning = c.getString(3).trim();
loc.descr = c.getString(4).trim();
loc.castid = c.getString(5).trim();
loc.religionid = c.getString(6).trim();
loc.languageid = c.getString(7).trim();
loc.rashiid = c.getString(8).trim();
loc.isfav = c.getInt(9);
loc_infos.add(loc);
} while (c.moveToNext());
}
}
c.close();
myDataBase.close();
SQLiteDatabase.releaseMemory();
return loc_infos;
}
public ArrayList<BabyNameDB> getBabynames(String Where) {
ArrayList<BabyNameDB> loc_infos = new ArrayList<BabyNameDB>();
openDataBase();
Cursor c = myDataBase
.rawQuery(
"SELECT * FROM babynamestable WHERE "+Where+" ORDER BY lower(babyname) ASC", null);
if (c != null) {
if (c.moveToFirst()) {
do {
BabyNameDB loc = new BabyNameDB();
loc.babyid = c.getString(0).trim();
loc.babygender = c.getString(1).trim();
loc.babyname = c.getString(2).trim();
loc.meaning = c.getString(3).trim();
loc.descr = c.getString(4).trim();
loc.castid = c.getString(5).trim();
loc.religionid = c.getString(6).trim();
loc.languageid = c.getString(7).trim();
loc.rashiid = c.getString(8);
loc.isfav = c.getInt(9);
loc_infos.add(loc);
} while (c.moveToNext());
}
}
c.close();
myDataBase.close();
SQLiteDatabase.releaseMemory();
return loc_infos;
}
public ArrayList<BabyNameDB> getAllnamesBabynames(String Where) {
ArrayList<BabyNameDB> loc_infos = new ArrayList<BabyNameDB>();
openDataBase();
Cursor c = myDataBase
.rawQuery(
"SELECT * FROM babynamestable WHERE "+Where, null);
if (c != null) {
if (c.moveToFirst()) {
do {
BabyNameDB loc = new BabyNameDB();
loc.babyid = c.getString(0).trim();
loc.babygender = c.getString(1).trim();
loc.babyname = c.getString(2).trim();
loc.meaning = c.getString(3).trim();
loc.descr = c.getString(4).trim();
loc.castid = c.getString(5).trim();
loc.religionid = c.getString(6).trim();
loc.languageid = c.getString(7).trim();
loc.rashiid = c.getString(8);
loc.isfav = c.getInt(9);
loc_infos.add(loc);
} while (c.moveToNext());
}
}
c.close();
myDataBase.close();
SQLiteDatabase.releaseMemory();
return loc_infos;
}
public String GetRashiNames(int id) {
String name="";
openDataBase();
Cursor c = myDataBase
.rawQuery(
"SELECT * FROM Rashitable WHERE id="+id, null);
if (c != null) {
if (c.moveToFirst()) {
name=c.getString(1).trim();
}
}
c.close();
myDataBase.close();
SQLiteDatabase.releaseMemory();
return name;
}
public void UpdateFav(int a, String babyid) {
openDataBase();
myDataBase
.execSQL("UPDATE babynamestable set isfav='"+a +"' WHERE babyid IN ("+babyid+")");
myDataBase.close();
SQLiteDatabase.releaseMemory();
}
public ArrayList<String> getPopularnames() {
ArrayList<String> pop_nameList = new ArrayList<String>();
openDataBase();
Cursor c = myDataBase
.rawQuery(
"SELECT * FROM PopularCategory", null);
if (c != null) {
if (c.moveToFirst()) {
do {
pop_nameList.add(c.getString(1).trim());
} while (c.moveToNext());
c.close();
myDataBase.close();
SQLiteDatabase.releaseMemory();
return pop_nameList;
}
}
c.close();
myDataBase.close();
SQLiteDatabase.releaseMemory();
return pop_nameList;
}
public ArrayList<Integer> getPopularId() {
ArrayList<Integer> pop_nameList = new ArrayList<Integer>();
openDataBase();
Cursor c = myDataBase
.rawQuery(
"SELECT * FROM PopularCategory", null);
if (c != null) {
if (c.moveToFirst()) {
do {
pop_nameList.add(c.getInt(0));
} while (c.moveToNext());
c.close();
myDataBase.close();
SQLiteDatabase.releaseMemory();
return pop_nameList;
}
}
c.close();
myDataBase.close();
SQLiteDatabase.releaseMemory();
return pop_nameList;
}
}
4)How to use
package com.BabyName;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.BabyName.DB.databasehelper;
public class PopularName_Act extends Activity
{
ArrayList<String> pop_nameList;
ArrayList<Integer> pop_idList;
databasehelper dbHelp;
Button btn_back;
TextView txt_title;
private SelectedAdapter selectedadapter;
private ListView list_popularName;
private RelativeLayout relative_topbar;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.popularname);
dbHelp=new databasehelper(this);
pop_nameList = new ArrayList<String>();
pop_idList = new ArrayList<Integer>();
btn_back=(Button)findViewById(R.id.pname_btn_back);
list_popularName=(ListView) findViewById(R.id.popularname_list_name);
relative_topbar = (RelativeLayout) findViewById(R.id.nd_topbar);
btn_back.setOnLongClickListener(new Longclick());
relative_topbar.setOnLongClickListener(new Longclick());
pop_nameList=dbHelp.getPopularnames();
pop_idList=dbHelp.getPopularId();
txt_title=(TextView) findViewById(R.id.pname_txt_title);
Typeface typeface = Typeface.createFromAsset(PopularName_Act.this.getAssets(), "fonts/Bradleys Pen.ttf");
txt_title.setTypeface(typeface);
if(pop_nameList.size()>0)
{
selectedadapter = new SelectedAdapter(PopularName_Act.this,0,pop_nameList);
selectedadapter.setNotifyOnChange(true);
list_popularName.setAdapter(selectedadapter);
}
btn_back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
private class SelectedAdapter extends ArrayAdapter<Object>
{
@SuppressWarnings("unchecked")
public SelectedAdapter(Context context, int textViewResourceId,
@SuppressWarnings("rawtypes") List objects)
{
super(context, textViewResourceId, objects);
}
@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View v = convertView;
final String tname=this.getItem(position).toString();
// set LayoutInflater in adapter
LayoutInflater vi = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.lyt_pname, null);
final TextView txt_name = (TextView)v.findViewById(R.id.lyt_pname_txt_name);
txt_name.setText(tname);
txt_name.setOnLongClickListener(new Longclick());
v.setOnLongClickListener(new Longclick());
txt_name.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
{
Bundle bundal=new Bundle();
Intent i = new Intent(PopularName_Act.this,PopularNameList_Act.class);
int id=pop_idList.get(position);
bundal.putString("where","babyid IN (SELECT babynameid FROM babynamescategorytable WHERE babynamecatid ="+ id+")");
bundal.putString("title","Popular Names");
i.putExtras(bundal);
startActivity(i);
}
});
return(v);
}
}
}
Wednesday, 15 May 2013
Data Base how to use
1)Database Helper class
package com.surgeryflashcard.DB;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class databasehelper extends SQLiteOpenHelper {
private static String DATABASE_NAME = "dbSurgeryFlashCard.sqlite";
private SQLiteDatabase myDataBase;
private Context myContext;
@SuppressWarnings("unused")
private String TAG = this.getClass().getSimpleName();
private String path = "/data/data/com.surgeryflashcard/databases/";
public databasehelper(Context context) {
super(context, DATABASE_NAME, null, 2);
this.myContext = context;
}
// ---Create the database---
public void createDataBase() throws IOException {
// ---Check whether database is already created or not---
boolean dbExist = checkDataBase();
if (!dbExist) {
this.getReadableDatabase();
try {
// ---If not created then copy the database---
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
this.close();
}
}
// --- Check whether database already created or not---
private boolean checkDataBase() {
try {
String myPath = path + DATABASE_NAME;
File f = new File(myPath);
if (f.exists())
return true;
else
return false;
} catch (SQLiteException e) {
e.printStackTrace();
return false;
}
}
// --- Copy the database to the output stream---
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
String outFileName = path + DATABASE_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
// --- Open the database---
String myPath = path + DATABASE_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
myDataBase.setLockingEnabled(false);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase arg0) {
//arg0.execSQL("CREATE TABLE Msg (id text,title text,body text,date1 text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void update_delete_insertquery(String s) {
//myDataBase.execSQL(s);
}
public Cursor selectquery(String s) {
return myDataBase.rawQuery(s, null);
}
public ArrayList<CatagoryDB> getCatagoey() {
ArrayList<CatagoryDB> loc_infos = new ArrayList<CatagoryDB>();
openDataBase();
Cursor c = myDataBase
.rawQuery(
"SELECT DISTINCT(categoryName),categoryID FROM tblCategory ORDER BY lower(categoryName) ASC", null);
if (c != null) {
if (c.moveToFirst()) {
do {
CatagoryDB loc = new CatagoryDB();
loc.categoryName = c.getString(0).trim();
loc.categoryID = c.getString(1).trim();
loc_infos.add(loc);
} while (c.moveToNext());
}
}
c.close();
myDataBase.close();
SQLiteDatabase.releaseMemory();
return loc_infos;
}
public ArrayList<SubCatagoryDB> getSubCatagoey(String where) {
ArrayList<SubCatagoryDB> loc_infos = new ArrayList<SubCatagoryDB>();
openDataBase();
Cursor c = myDataBase
.rawQuery(
"SELECT DISTINCT subCategoryID,categoryID,(subCategoryName) FROM tblSubCategory WHERE categoryID = "+where, null);
if (c != null) {
if (c.moveToFirst()) {
do {
SubCatagoryDB loc = new SubCatagoryDB();
loc.subCategoryID = c.getString(0).trim();
loc.categoryID = c.getString(1).trim();
loc.subCategoryName = c.getString(2).trim();
loc_infos.add(loc);
} while (c.moveToNext());
}
}
c.close();
myDataBase.close();
SQLiteDatabase.releaseMemory();
return loc_infos;
}
public ArrayList<CardDB> getCard(String where) {
ArrayList<CardDB> loc_infos = new ArrayList<CardDB>();
openDataBase();
Cursor c = myDataBase
.rawQuery(
"SELECT * FROM tblCards WHERE subCategoryID = "+where, null);
if (c != null) {
if (c.moveToFirst()) {
do {
CardDB loc = new CardDB();
loc.cardID = c.getString(2).trim();
loc.cardDetail = c.getString(3).trim();
loc_infos.add(loc);
} while (c.moveToNext());
}
}
c.close();
myDataBase.close();
SQLiteDatabase.releaseMemory();
return loc_infos;
}
}
2)Db addepter
package com.surgeryflashcard.DB;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBAdapter {
private final String DATABASE_NAME = "dbSurgeryFlashCard.sqlite";
private final int DATABASE_VERSION = 1;
private Context context;
private DatabaseHelper DBHelper;
//private static SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
public class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
// db.execSQL(DATABASE_CREATE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//onCreate(db);
}
}
// ---opens the database---
@SuppressWarnings("unused")
public DBAdapter open() throws SQLException {
SQLiteDatabase db = DBHelper.getWritableDatabase();
return this;
}
// ---closes the database---
public void close() {
DBHelper.close();
}
}
3)MainActivity
package com.surgeryflashcard;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.surgeryflashcard.DB.CatagoryDB;
import com.surgeryflashcard.DB.databasehelper;
public class ListActivity extends Activity
{
databasehelper db;
ArrayList<CatagoryDB> arr_cat;
ListView list;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
db = new databasehelper(this);
try {
db.createDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list = (ListView) findViewById(R.id.list);
new GetData().execute();
}
//________________Methods______________________________
private class GetData extends AsyncTask<Void, Void, Void>
{
ProgressDialog pd;
@Override
protected void onPreExecute() {
pd = new ProgressDialog(ListActivity.this);
pd.setMessage("Loading...");
pd.show();
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
arr_cat = db.getCatagoey();
return null;
}
@Override
protected void onPostExecute(Void result) {
//if(pd.isShowing())
pd.dismiss();
list.setAdapter(new ItemsAdapter());
list.invalidate();
super.onPostExecute(result);
}
}
public class ItemsAdapter extends BaseAdapter {
@Override
public int getCount() {
// TODO Auto-generated method stub
return arr_cat.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View resultListView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (resultListView == null) {
resultListView = inflater.inflate(R.layout.lyt_home_left, null);
holder = new ViewHolder();
holder.txt_name = (TextView) resultListView.findViewById(R.id.lyt_txt_leftlist);
resultListView.setTag(holder);
} else {
holder = (ViewHolder) resultListView.getTag();
}
final CatagoryDB babyname = arr_cat.get(position);
holder.txt_name.setText("" + babyname.categoryName);
resultListView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
}
});
return resultListView;
}
class ViewHolder {
TextView txt_name;
}
}
}
package com.surgeryflashcard.DB;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class databasehelper extends SQLiteOpenHelper {
private static String DATABASE_NAME = "dbSurgeryFlashCard.sqlite";
private SQLiteDatabase myDataBase;
private Context myContext;
@SuppressWarnings("unused")
private String TAG = this.getClass().getSimpleName();
private String path = "/data/data/com.surgeryflashcard/databases/";
public databasehelper(Context context) {
super(context, DATABASE_NAME, null, 2);
this.myContext = context;
}
// ---Create the database---
public void createDataBase() throws IOException {
// ---Check whether database is already created or not---
boolean dbExist = checkDataBase();
if (!dbExist) {
this.getReadableDatabase();
try {
// ---If not created then copy the database---
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
this.close();
}
}
// --- Check whether database already created or not---
private boolean checkDataBase() {
try {
String myPath = path + DATABASE_NAME;
File f = new File(myPath);
if (f.exists())
return true;
else
return false;
} catch (SQLiteException e) {
e.printStackTrace();
return false;
}
}
// --- Copy the database to the output stream---
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
String outFileName = path + DATABASE_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
// --- Open the database---
String myPath = path + DATABASE_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
myDataBase.setLockingEnabled(false);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase arg0) {
//arg0.execSQL("CREATE TABLE Msg (id text,title text,body text,date1 text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void update_delete_insertquery(String s) {
//myDataBase.execSQL(s);
}
public Cursor selectquery(String s) {
return myDataBase.rawQuery(s, null);
}
public ArrayList<CatagoryDB> getCatagoey() {
ArrayList<CatagoryDB> loc_infos = new ArrayList<CatagoryDB>();
openDataBase();
Cursor c = myDataBase
.rawQuery(
"SELECT DISTINCT(categoryName),categoryID FROM tblCategory ORDER BY lower(categoryName) ASC", null);
if (c != null) {
if (c.moveToFirst()) {
do {
CatagoryDB loc = new CatagoryDB();
loc.categoryName = c.getString(0).trim();
loc.categoryID = c.getString(1).trim();
loc_infos.add(loc);
} while (c.moveToNext());
}
}
c.close();
myDataBase.close();
SQLiteDatabase.releaseMemory();
return loc_infos;
}
public ArrayList<SubCatagoryDB> getSubCatagoey(String where) {
ArrayList<SubCatagoryDB> loc_infos = new ArrayList<SubCatagoryDB>();
openDataBase();
Cursor c = myDataBase
.rawQuery(
"SELECT DISTINCT subCategoryID,categoryID,(subCategoryName) FROM tblSubCategory WHERE categoryID = "+where, null);
if (c != null) {
if (c.moveToFirst()) {
do {
SubCatagoryDB loc = new SubCatagoryDB();
loc.subCategoryID = c.getString(0).trim();
loc.categoryID = c.getString(1).trim();
loc.subCategoryName = c.getString(2).trim();
loc_infos.add(loc);
} while (c.moveToNext());
}
}
c.close();
myDataBase.close();
SQLiteDatabase.releaseMemory();
return loc_infos;
}
public ArrayList<CardDB> getCard(String where) {
ArrayList<CardDB> loc_infos = new ArrayList<CardDB>();
openDataBase();
Cursor c = myDataBase
.rawQuery(
"SELECT * FROM tblCards WHERE subCategoryID = "+where, null);
if (c != null) {
if (c.moveToFirst()) {
do {
CardDB loc = new CardDB();
loc.cardID = c.getString(2).trim();
loc.cardDetail = c.getString(3).trim();
loc_infos.add(loc);
} while (c.moveToNext());
}
}
c.close();
myDataBase.close();
SQLiteDatabase.releaseMemory();
return loc_infos;
}
}
2)Db addepter
package com.surgeryflashcard.DB;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBAdapter {
private final String DATABASE_NAME = "dbSurgeryFlashCard.sqlite";
private final int DATABASE_VERSION = 1;
private Context context;
private DatabaseHelper DBHelper;
//private static SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
public class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
// db.execSQL(DATABASE_CREATE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//onCreate(db);
}
}
// ---opens the database---
@SuppressWarnings("unused")
public DBAdapter open() throws SQLException {
SQLiteDatabase db = DBHelper.getWritableDatabase();
return this;
}
// ---closes the database---
public void close() {
DBHelper.close();
}
}
3)MainActivity
package com.surgeryflashcard;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.surgeryflashcard.DB.CatagoryDB;
import com.surgeryflashcard.DB.databasehelper;
public class ListActivity extends Activity
{
databasehelper db;
ArrayList<CatagoryDB> arr_cat;
ListView list;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
db = new databasehelper(this);
try {
db.createDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list = (ListView) findViewById(R.id.list);
new GetData().execute();
}
//________________Methods______________________________
private class GetData extends AsyncTask<Void, Void, Void>
{
ProgressDialog pd;
@Override
protected void onPreExecute() {
pd = new ProgressDialog(ListActivity.this);
pd.setMessage("Loading...");
pd.show();
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
arr_cat = db.getCatagoey();
return null;
}
@Override
protected void onPostExecute(Void result) {
//if(pd.isShowing())
pd.dismiss();
list.setAdapter(new ItemsAdapter());
list.invalidate();
super.onPostExecute(result);
}
}
public class ItemsAdapter extends BaseAdapter {
@Override
public int getCount() {
// TODO Auto-generated method stub
return arr_cat.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View resultListView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (resultListView == null) {
resultListView = inflater.inflate(R.layout.lyt_home_left, null);
holder = new ViewHolder();
holder.txt_name = (TextView) resultListView.findViewById(R.id.lyt_txt_leftlist);
resultListView.setTag(holder);
} else {
holder = (ViewHolder) resultListView.getTag();
}
final CatagoryDB babyname = arr_cat.get(position);
holder.txt_name.setText("" + babyname.categoryName);
resultListView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
}
});
return resultListView;
}
class ViewHolder {
TextView txt_name;
}
}
}
Call web Services
1)Http Helper Class
package com.Pharma.Httphelper;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import com.Pharma.Utils.Constants;
import com.Pharma.Utils.OderDisplay;
import com.Pharma.Utils.Offers;
import com.Pharma.Utils.PriscriptionNote;
import com.Pharma.Utils.Register;
import com.Pharma.Utils.Same;
import com.Pharma.Utils.login;
import com.Pharma.Utils.pharmacists;
import com.PharmaSeek.Act_Login;
import com.PharmaSeek.Act_OderDisplay;
import com.PharmaSeek.Act_PricriptionNote;
import com.PharmaSeek.Act_TabBar;
import com.PharmaSeek.Act_YourDetails;
public class HttpHelper extends AsyncTask<Object, Integer, Long>
{
private ProgressDialog dialog;
public static int requestNumber;
private String loadingMessage;
private Act_TabBar activity_tab;
private Act_Login activity_login;
private Act_YourDetails activity_register;
private Act_OderDisplay activity_same;
private Act_PricriptionNote activity_Prinote;
private Document response_xml;
pharmacists phm=new pharmacists();
login login=new login();
OderDisplay oderdisplay=new OderDisplay();
Same same=new Same();
Same Diffrent =new Same();
Register register=new Register();
PriscriptionNote prenote = new PriscriptionNote();
ArrayList<pharmacists>arr_phm=new ArrayList<pharmacists>();
ArrayList<Offers>arr_offers=new ArrayList<Offers>();
private WebAPIRequest webAPIRequest = new WebAPIRequest();
ArrayList<login>arr_login=new ArrayList<login>();
ArrayList<Register>arr_register=new ArrayList<Register>();
ArrayList<Same>arr_same=new ArrayList<Same>();
ArrayList<Same>arr_diffrent=new ArrayList<Same>();
ArrayList<OderDisplay>arr_oderdisplay=new ArrayList<OderDisplay>();
String Register_massage ;
private String response;
public HttpHelper(int request_num, Act_TabBar activity, String msg)
{
activity_tab = activity;
requestNumber = request_num;
dialog = new ProgressDialog(activity_tab);
dialog.setCancelable(true);
loadingMessage = msg;
}
public HttpHelper(int request_num, Act_Login activity, String msg)
{
activity_login = activity;
requestNumber = request_num;
dialog = new ProgressDialog(activity_login);
dialog.setCancelable(true);
loadingMessage = msg;
}
public HttpHelper(int request_num, Act_YourDetails activity, String msg)
{
activity_register = activity;
requestNumber = request_num;
dialog = new ProgressDialog(activity_register);
dialog.setCancelable(true);
loadingMessage = msg;
}
public HttpHelper(int request_num, Act_OderDisplay activity, String msg)
{
activity_same = activity;
requestNumber = request_num;
dialog = new ProgressDialog(activity_same);
dialog.setCancelable(true);
loadingMessage = msg;
}
public HttpHelper(int request_num, Act_PricriptionNote activity, String msg)
{
activity_Prinote = activity;
requestNumber = request_num;
dialog = new ProgressDialog(activity_Prinote);
dialog.setCancelable(true);
loadingMessage = msg;
}
protected void onPreExecute()
{
if(dialog != null)
{
dialog.setMessage(loadingMessage);
dialog.show();
}
}
@Override
protected Long doInBackground(Object... value)
{
// ................................LOGIN_API.............................
if(requestNumber == Constants.CODE_LOGIN)
{
String url = (String) value[0];
response = webAPIRequest.performGet(url);
if(response != null)
{
System.out.println("Login " + response);
try
{
JSONObject jsonObject = new JSONObject(response);
JSONObject obj = jsonObject.getJSONObject("Login");
boolean success = obj.getBoolean("success");
if(success)
{
login.success = true;
JSONObject objuserinfo = obj.getJSONObject("userinfo");
login.id = objuserinfo.getString("id");
login.first_name = objuserinfo.getString("first_name");
login.last_name = objuserinfo.getString("last_name");
login.address1 = objuserinfo.getString("address1");
login.address2 = objuserinfo.getString("address2");
login.postcode = objuserinfo.getString("postcode");
login.city = objuserinfo.getString("city");
login.dob = objuserinfo.getString("dob");
login.phone = objuserinfo.getString("phone");
login.email = objuserinfo.getString("email");
login.password = objuserinfo.getString("password");
login.offer_received = objuserinfo.getString("offer_received");
login.order_date = objuserinfo.getString("order_date");
}
else
{
login.success = false;
login.message = obj.getString("message");
}
arr_login.add(login);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
login.message = "The login details you provided were invalid. Please try again.";
login.success = false;
}
}
// ................................Register_API.............................
else if(requestNumber == Constants.CODE_REGISTER)
{
String url = (String) value[0];
response = webAPIRequest.performGet(url);
if(response != null)
{
System.out.println("Register " + response);
try
{
JSONObject jsonObject = new JSONObject(response);
JSONObject obj = jsonObject.getJSONObject("Registration");
boolean success = obj.getBoolean("success");
if(success)
{
register.success = true;
register.message = obj.getString("message");
}
else
{
register.success = false;
register.message = obj.getString("message");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
register.message = "OOPS! Please try again.";
register.success = false;
}
}
// ................................GetAllPrescriptions.............................
else if(requestNumber == Constants.CODE_ORDERDISPLAY)
{
String url = (String) value[0];
response = webAPIRequest.performGet(url);
if(response != null)
{
System.out.println("GetAllPrescriptions" + response);
try
{
JSONObject jsonObject = new JSONObject(response);
JSONObject obj = jsonObject.getJSONObject("GetAllPrescriptions");
boolean success = obj.getBoolean("success");
if(success)
{
oderdisplay.success = true;
//JSONObject jsonObject2 = jsonObject.getJSONObject("UserActivity");
JSONArray array = obj.getJSONArray("Prescriptions");
int n = array.length();
System.out.println("length"+n);
for (int i = 0; i < n; i++)
{
JSONObject object = array.getJSONObject(i);
oderdisplay.id = object.has("id")?object.getString("id"):"";
oderdisplay.first_name = object.has("first_name")?object.getString("first_name"):"";
oderdisplay.last_name = object.has("last_name")?object.getString("last_name"):"";
oderdisplay.address1 = object.has("address1")?object.getString("address1"):"";
oderdisplay.address2 = object.has("address2")?object.getString("address2"):"";
oderdisplay.postcode = object.has("postcode")?object.getString("postcode"):"";
oderdisplay.city = object.has("city")?object.getString("city"):"";
oderdisplay.dob = object.has("dob")?object.getString("dob"):"";
oderdisplay.phone = object.has("phone")?object.getString("phone"):"";
oderdisplay.email = object.has("email")?object.getString("email"):"";
oderdisplay.password = object.has("password")?object.getString("password"):"";
oderdisplay.offer_received = object.has("offer_received")?object.getString("offer_received"):"";
oderdisplay.order_date = object.has("order_date")?object.getString("order_date"):"";
oderdisplay.pharmacist_id = object.has("pharmacist_id")?object.getString("pharmacist_id"):"";
oderdisplay.pre_note = object.has("pre_note")?object.getString("pre_note"):"";
oderdisplay.pre_pic = object.has("pre_pic")?object.getString("pre_pic"):"";
oderdisplay.id2 = object.has("id2")?object.getString("id2"):"";
oderdisplay.pid = object.has("pid")?object.getString("pid"):"";
oderdisplay.name = object.has("name")?object.getString("name"):"";
oderdisplay.phone = object.has("phone")?object.getString("phone"):"";
arr_oderdisplay.add(oderdisplay);
}
}
else
{
JSONObject object = jsonObject.getJSONObject("GetAllPrescriptions");
oderdisplay.success = false;
oderdisplay.message = object.getString("message");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
oderdisplay.success = false;
oderdisplay.message = "OOPS! Please try again.";
}
}
else
{
oderdisplay.message = "OOPS! Please try again.";
oderdisplay.success = false;
}
}
// ................................24/7 Services.............................
else if(requestNumber == Constants.CODE_PHARMA)
{
String url = (String) value[0];
response = webAPIRequest.performGet(url);
pharmacists ph = new pharmacists();
if(response != null)
{
System.out.println("24/7 Services" + response);
try
{
JSONObject jsonObject = new JSONObject(response);
JSONObject obj = jsonObject.getJSONObject("GetNearByPharmacy");
boolean success = obj.getBoolean("success");
if(success)
{
ph.success = true;
//JSONObject jsonObject2 = jsonObject.getJSONObject("UserActivity");
JSONArray array = obj.getJSONArray("Pharmacies");
int n = array.length();
System.out.println("length"+n);
for (int i = 0; i < n; i++)
{
JSONObject object = array.getJSONObject(i);
//ph.id = object.has("id")?object.getInt("id"):0;
ph.id = object.has("id")?object.getString("id"):"";
ph.email = object.has("email")?object.getString("email"):"";
ph.password = object.has("password")?object.getString("password"):"";
ph.name = object.has("name")?object.getString("name"):"";
ph.website = object.has("website")?object.getString("website"):"";
ph.phone = object.has("phone")?object.getString("phone"):"";
ph.address1 = object.has("address1")?object.getString("address1"):"";
ph.address2 = object.has("address2")?object.getString("address2"):"";
ph.city = object.has("city")?object.getString("city"):"";
ph.area = object.has("area")?object.getString("area"):"";
ph.postcode = object.has("postcode")?object.getString("postcode"):"";
ph.country = object.has("country")?object.getString("country"):"";
ph.short_description = object.has("short_description")?object.getString("short_description"):"";
ph.description = object.has("description")?object.getString("description"):"";
ph.business_time = object.has("business_time")?object.getString("business_time"):"";
ph.twentyfourseven = object.has("twentyfourseven")?object.getString("twentyfourseven"):"";
ph.image1 = object.has("image1")?object.getString("image1"):"";
ph.image2 = object.has("image2")?object.getString("image2"):"";
ph.image3 = object.has("image3")?object.getString("image3"):"";
ph.image4 = object.has("image4")?object.getString("image4"):"";
ph.parking_type = object.has("parking_type")?object.getString("parking_type"):"";
ph.subscription_plan = object.has("subscription_plan")?object.getString("subscription_plan"):"";
ph.subscription_type = object.has("subscription_type")?object.getString("subscription_type"):"";
ph.date = object.has("date")?object.getString("date"):"";
ph.expiry_date = object.has("expiry_date")?object.getString("expiry_date"):"";
ph.setord = object.has("setord")?object.getString("setord"):"";
ph.pagename = object.has("pagename")?object.getString("pagename"):"";
ph.active = object.has("active")?object.getString("active"):"";
ph.pharma_pay_status = object.has("pharma_pay_status")?object.getString("pharma_pay_status"):"";
ph.cust_paypal_id = object.has("cust_paypal_id")?object.getString("cust_paypal_id"):"";
ph.upgraded = object.has("upgraded")?object.getString("upgraded"):"";
ph.charge_changed = object.has("charge_changed")?object.getString("charge_changed"):"";
ph.latitude = object.has("latitude")?object.getString("latitude"):"";
ph.longitude = object.has("longitude")?object.getString("longitude"):"";
ph.CountryName = object.has("CountryName")?object.getString("CountryName"):"";
ph.AreaName = object.has("AreaName")?object.getString("AreaName"):"";
ph.CityName = object.has("CityName")?object.getString("CityName"):"";
ph.parking_type_name = object.has("parking_type_name")?object.getString("parking_type_name"):"";
ph.subscription_plan_name = object.has("subscription_plan_name")?object.getString("subscription_plan_name"):"";
ph.distance = object.has("distance")?object.getString("distance"):"";
arr_phm.add(ph);
}
}
else
{
JSONObject object = jsonObject.getJSONObject("GetNearByPharmacy");
ph.success = false;
ph.message = object.getString("message");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ph.success = false;
ph.message = "OOPS! Please try again.";
}
}
else
{
ph.message = "OOPS! Please try again.";
ph.success = false;
}
}
// ................................Get Offers.............................
else if(requestNumber == Constants.CODE_OFFERS_DETAILS)
{
String url = (String) value[0];
response = webAPIRequest.performGet(url);
Offers offers = new Offers();
if(response != null)
{
System.out.println("Get Offers" + response);
try
{
JSONObject jsonObject = new JSONObject(response);
JSONObject obj = jsonObject.getJSONObject("GetOffers");
boolean success = obj.getBoolean("success");
if(success)
{
offers.success = true;
//JSONObject jsonObject2 = jsonObject.getJSONObject("UserActivity");
JSONArray array = obj.getJSONArray("Offers");
int n = array.length();
System.out.println("length"+n);
for (int i = 0; i < n; i++)
{
JSONObject object = array.getJSONObject(i);
offers.id = object.has("id")?object.getInt("id"):0;
offers.pid = object.has("pid")?object.getInt("pid"):0;
offers.offer_name = object.has("offer_name")?object.getString("offer_name"):"";
offers.offer_description = object.has("offer_description")?object.getString("offer_description"):"";
offers.offer_type = object.has("offer_type")?object.getString("offer_type"):"";
offers.offer_sdate = object.has("offer_sdate")?object.getString("offer_sdate"):"";
offers.offer_fdate = object.has("offer_fdate")?object.getString("offer_fdate"):"";
offers.offer_code = object.has("offer_code")?object.getString("offer_code"):"";
offers.offer_terms = object.has("offer_terms")?object.getString("offer_terms"):"";
arr_offers.add(offers);
}
}
else
{
JSONObject object = jsonObject.getJSONObject("GetOffers");
offers.success = false;
offers.message = object.getString("message");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
offers.success = false;
offers.message = "OOPS! Please try again.";
}
}
else
{
oderdisplay.message = "OOPS! Please try again.";
oderdisplay.success = false;
}
}
// ................................Same_API.............................
else if(requestNumber == Constants.CODE_SAME)
{
String url = (String) value[0];
response = webAPIRequest.performGet(url);
if(response != null)
{
System.out.println("Same " + response);
try
{
JSONObject jsonObject = new JSONObject(response);
JSONObject obj = jsonObject.getJSONObject("Reorder");
boolean success = obj.getBoolean("success");
if(success)
{
same.success = true;
same.message = obj.getString("message");
}
else
{
same.success = false;
same.message = obj.getString("message");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
same.message = "OOPS! Please try again.";
same.success = false;
}
}
// ................................Differnt_API.............................
else if(requestNumber == Constants.CODE_DIFFRENT)
{
String url = (String) value[0];
response = webAPIRequest.performGet(url);
if(response != null)
{
System.out.println("Differnt_API " + response);
try
{
JSONObject jsonObject = new JSONObject(response);
JSONObject obj = jsonObject.getJSONObject("Reorder");
boolean success = obj.getBoolean("success");
if(success)
{
same.success = true;
same.message = obj.getString("message");
}
else
{
same.success = false;
same.message = obj.getString("message");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
same.message = "OOPS! Please try again.";
same.success = false;
}
}
// ................................Post Priscription_API.............................
else if(requestNumber == Constants.CODE_POSTPRISCRIPTION)
{
String url = (String) value[0];
response = webAPIRequest.performGet(url);
if(response != null)
{
System.out.println("Differnt_API " + response);
try
{
JSONObject jsonObject = new JSONObject(response);
JSONObject obj = jsonObject.getJSONObject("CreatePrescription");
boolean success = obj.getBoolean("success");
if(success)
{
prenote.success = true;
prenote.message = obj.getString("message");
}
else
{
prenote.success = false;
prenote.message = obj.getString("message");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
prenote.message = "OOPS! Please try again.";
prenote.success = false;
}
}
return null;
}
protected void onPostExecute(Long result)
{
if(dialog != null)
{
dialog.dismiss();
}
if(requestNumber == Constants.CODE_PHARMA)
{
activity_tab.setBackApiResponse(requestNumber, arr_phm);
}
else if(requestNumber == Constants.CODE_OFFERS_DETAILS)
{
activity_tab.setBackApiResponse(requestNumber, arr_offers);
}
else if(requestNumber == Constants.CODE_LOGIN)
{
activity_login.setBackApiResponse(requestNumber, arr_login);
}
else if(requestNumber == Constants.CODE_REGISTER)
{
activity_register.setBackApiResponse(requestNumber, register);
}
else if(requestNumber == Constants.CODE_SAME)
{
activity_same.setBackApiResponse(requestNumber, same);
}
else if(requestNumber == Constants.CODE_DIFFRENT)
{
activity_tab.setBackApiResponse(requestNumber, same);
}
else if(requestNumber == Constants.CODE_ORDERDISPLAY)
{
activity_same.setBackApiResponse(requestNumber, arr_oderdisplay);
}
else if(requestNumber == Constants.CODE_POSTPRISCRIPTION)
{
activity_Prinote.setBackApiResponse(requestNumber, prenote);
}
}
String getValueFromNode(Element childNode, String tagName)
{
String strValue = "";
try
{
Element node = (Element)childNode.getElementsByTagName(tagName).item(0);
for(int i=0;i<node.getChildNodes().getLength();i++)
{
strValue = strValue.concat(node.getChildNodes().item(i).getNodeValue());
}
}
catch(Exception exp)
{
}
return strValue;
}
int parseIntValue(String strValue)
{
int value=0;
if(strValue!=null && strValue.length()>0)
{
value = Integer.parseInt(strValue);
}
return value;
}
float parseFloatValue(String strValue)
{
float value=0.0f;
if(strValue!=null && strValue.length()>0)
{
value = Float.parseFloat(strValue);
}
return value;
}
double parseDoubleValue(String strValue)
{
double value=0.0f;
if(strValue!=null && strValue.length()>0)
{
value = Double.parseDouble(strValue);
}
return value;
}
}
2)WebAPIResposce Class
package com.Pharma.Httphelper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.os.Bundle;
import android.util.Log;
public class WebAPIRequest
{
public static String convertStreamToString(InputStream is) throws IOException {
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally {
is.close();
}
return sb.toString();
} else {
return "false";
}
}
public String performGet(String url)
{
String doc = null;
try
{
DefaultHttpClient client = new DefaultHttpClient();
URI uri = new URI(url);
HttpGet method = new HttpGet(uri);
HttpResponse res = client.execute(method);
InputStream data = res.getEntity().getContent();
doc = convertStreamToString(data);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
return doc;
}
public String performPost(String apiUrl, Bundle bundle)
{
// TODO Auto-generated method stub
String doc = null;
try {
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(apiUrl);
HttpResponse response;
httppost.setEntity(new UrlEncodedFormEntity(getListOfNameValuePair(bundle)));
response = client.execute(httppost);
//System.out.println(response.getEntity().getContentType().toString());
InputStream data = response.getEntity().getContent();
doc = convertStreamToString(data);
} catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return doc;
}
public String performPostMatipart(String url, Bundle nameValuePairs) throws Exception {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
for (String key : nameValuePairs.keySet()) {
if(nameValuePairs.get(key) instanceof String)
{ entity.addPart(key,
new StringBody(nameValuePairs.getString(key)));
Log.e(key, nameValuePairs.getString(key));
}
else
{
entity.addPart(key, new ByteArrayBody((byte[]) nameValuePairs.get(key),"Image.jpg"));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
return convertStreamToString(response.getEntity().getContent());
} catch (Exception e) {
throw e;
}
}
//Make List Of NameValuePair
public static List<NameValuePair> getListOfNameValuePair(Bundle parameters)
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
if (parameters == null) return null;
for (String key : parameters.keySet())
{
nameValuePairs.add(new BasicNameValuePair(key, parameters.getString(key)));
}
return nameValuePairs;
}
}
3)Main Activity
package com.PharmaSeek;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.Pharma.Httphelper.HttpHelper;
import com.Pharma.Utils.Constants;
import com.Pharma.Utils.Same;
import com.Pharma.Utils.pharmacists;
public class Act_Pharmacy extends Act_TabBar implements OnClickListener
{
private LayoutInflater lyt_Inflater = null;
private ItemsAdapter adpt;
private ListView Listview;
private Button btn_back,btn_map;
private int ButtonID , Reoder ;
String orderid;
private TextView txt_title;
String Fname,Lname,Add1,Add2,PostalCode,DOB,MobNumber,Email,PreNote ,id;
Same MSG;
String idphm;
@SuppressWarnings("unchecked")
public void setBackApiResponse(int requestNumber,Object obj)
{
if(requestNumber == Constants.CODE_DIFFRENT)
{
MSG=(Same) obj;
//System.out.print("MSG====="+MSG);
Toast.makeText(Act_Pharmacy.this, MSG.message, Toast.LENGTH_LONG).show();
//dialog_message2(MSG.message);
}
else
{
Constants.arr_phm=(ArrayList<pharmacists>) obj;
try
{
if(Constants.arr_phm.size()>0)
{
adpt=new ItemsAdapter(Act_Pharmacy.this,Constants.arr_phm);
Listview.setAdapter(adpt);
Listview.invalidate();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.pharmacy);
ButtonID=getIntent().getIntExtra("ButtonID",0);
Reoder=getIntent().getIntExtra("reoder",0);
orderid=getIntent().getStringExtra("orderid");
//pharmaemail=getIntent().getStringExtra("pharmaemail");
Initialize_Controls();
Get_PreferenceResponce();
Get_PharmacyResponce();
}
private void Get_PreferenceResponce()
{
SharedPreferences ph=this.getSharedPreferences(Constants.Pref_PharmaSeek, 0);
Fname=ph.getString("FNAME","");
Lname=ph.getString("LNAME","");
Add1=ph.getString("ADD1","");
Add2=ph.getString("ADD2","");
PostalCode=ph.getString("MOB","");
DOB=ph.getString("DOB","");
MobNumber=ph.getString("POSTALCODE","");
Email=ph.getString("EMAIL","");
PreNote=ph.getString("NOTE","");
}
private void Initialize_Controls()
{
super.initialize_Bottombar(1);
txt_title=(TextView) findViewById(R.id.Phm_txt_title);
Listview=(ListView) findViewById(R.id.list_pharmacy);
btn_back=(Button) findViewById(R.id.Phm_btn_back);
btn_map=(Button) findViewById(R.id.Phm_btn_Map);
btn_back.setOnClickListener(this);
btn_map.setOnClickListener(this);
if(ButtonID==1)
{
txt_title.setText(R.string.textphYou1);
//btn_map.setVisibility(View.GONE);
}
else
{
txt_title.setText(R.string.textphYou);
//btn_map.setVisibility(View.VISIBLE);
}
}
private void Get_PharmacyResponce()
{
if(isOnline())
{
String req = String.format(Constants.Pharmacy_url,Constants.Radius,Act_Main.cur_latitude,Act_Main.cur_longitude,"","",0);
HttpHelper helper = new HttpHelper(Constants.CODE_PHARMA, Act_Pharmacy.this, "Loading pharmacist. Please wait...");
helper.execute(req);
System.out.println("Get_PharmacyResponce" +req);
//for xml********************************************************************
String req = String.format(Constants.Pharmacy_resq_xml,Constants.Radius,Act_Main.cur_latitude,Act_Main.cur_longitude,"","",0);
HttpHelper helper = new HttpHelper(Constants.CODE_PHARMA, Act_Pharmacy.this, "Loading pharmacist. Please wait...");
helper.execute(req);
}
else
{
String mess = getResources().getString(R.string.Internet_msg);
Toast.makeText(Act_Pharmacy.this, mess, Toast.LENGTH_LONG).show();
//dialog_message(mess);
}
}
private class ItemsAdapter extends BaseAdapter
{
private ArrayList<pharmacists> arrphm;
public ItemsAdapter(Context context,ArrayList<pharmacists> items)
{
this.arrphm = items;
}
@Override
public int getCount()
{
return arrphm.size();
}
@Override
public Object getItem(int position)
{
return null;
}
@Override
public long getItemId(int position)
{
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View view_lyt = convertView;
try
{
if(Constants.arr_phm.size()>0)
{
final pharmacists phmst = Constants.arr_phm.get(position);
String Name=phmst.name;
Email=phmst.email;
String Distance=phmst.distance;
String Address="";
String Address1=phmst.address1;
String Address2=phmst.address2;
String areaName=phmst.AreaName;
String CityName=phmst.CityName;
idphm = phmst.id;
if(Address1.length()>0)
{
Address=Address1;
}
if(Address2.length()>0)
{
Address=Address2;
}
if(Address1.length()>0 && Address2.length()>0)
{
Address=Address1+","+" "+Address2 ;
}
lyt_Inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view_lyt = lyt_Inflater.inflate(R.layout.lyt_view, null);
TextView txtnm=(TextView) view_lyt.findViewById(R.id.lyt_txt_name);
txtnm.setText(Name);
TextView txtdistance=(TextView) view_lyt.findViewById(R.id.lyt_txt_distance);
txtdistance.setText(Distance);
TextView txtadd=(TextView) view_lyt.findViewById(R.id.lyt_txt_add);
txtadd.setText(Address+" "+areaName+" "+CityName);
view_lyt.setTag(phmst);
//view_lyt.setBackgroundResource(R.drawable.raw_selector);
view_lyt.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
pharmacists temp = (pharmacists) v.getTag();
if(ButtonID == 6)
{
Intent i=new Intent(Act_Pharmacy.this,Act_PricriptionNote.class);
i.putExtra("Email",Email);
i.putExtra("id",idphm);
startActivity(i);
finish();
}
else
{
if(Reoder == 100)
{
if(isOnline())
{
String req = String.format(Constants.Same_url,"different",orderid ,temp.id);
HttpHelper helper = new HttpHelper(Constants.CODE_DIFFRENT, Act_Pharmacy.this, "Please wait...");
helper.execute(req);
System.out.println("Different_req*****" +req);
}
else
{
String mess = getResources().getString(R.string.Internet_msg);
Toast.makeText(Act_Pharmacy.this, mess, Toast.LENGTH_LONG).show();
//dialog_message(mess);
}
}
else {
Constants.CODE_TAB=1;
if(ButtonID==1)
{
if(Fname.length()>0)
{
Dialog_Msg();
}
else
{
Intent i=new Intent(Act_Pharmacy.this,Act_YourDetails.class);
i.putExtra("Old&New","NEW");
i.putExtra("Email",Email);
i.putExtra("id",idphm);
startActivity(i);
//finish();
}
}
else
{
Intent i=new Intent(Act_Pharmacy.this,Act_Details.class);
i.putExtra("ID", position);
startActivity(i);
//finish();
}
}
}
}
});
}
}
catch (Exception e)
{
Log.i("Exception==", e.toString());
}
return view_lyt;
}
}
public void onClick(View v)
{
super.onClick(v);
if(v==btn_back)
{
Intent i=new Intent(Act_Pharmacy.this,Act_Home.class);
startActivity(i);
finish();
}
else if (v==btn_map)
{
Intent i=new Intent(Act_Pharmacy.this,Act_Map.class);
startActivity(i);
}
}
private void Dialog_Msg()
{
final AlertDialog alertDialog = new AlertDialog.Builder(Act_Pharmacy.this).create();
alertDialog.setTitle("Personal Details");
String Msg=getString(R.string.Dialog_Text);
alertDialog.setMessage(Msg);
alertDialog.setButton("Use old details", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Intent i=new Intent(Act_Pharmacy.this,Act_YourDetails.class);
i.putExtra("Old&New","OLD");
i.putExtra("id",idphm);
i.putExtra("Email",Email);
startActivity(i);
// finish();
}
});
alertDialog.setButton2("Enter new details", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Intent i=new Intent(Act_Pharmacy.this,Act_YourDetails.class);
i.putExtra("Old&New","NEW");
i.putExtra("Email",Email);
i.putExtra("id",idphm);
startActivity(i);
//finish();
}
});
alertDialog.show();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode==KeyEvent.KEYCODE_BACK)
{
Intent i=new Intent(Act_Pharmacy.this,Act_Home.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
return super.onKeyDown(keyCode, event);
}
public void dialog_message2(String msg)
{
final AlertDialog alertDialog = new AlertDialog.Builder(Act_Pharmacy.this).create();
alertDialog.setTitle("Alert !");
alertDialog.setMessage(msg);
alertDialog.setCancelable(false);
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
alertDialog.dismiss();
Intent i = new Intent(Act_Pharmacy.this,Act_OderDisplay.class);
startActivity(i);
finish();
}
});
alertDialog.show();
}
}
4)For Xml
public static int CODE_PHARMA=100;
public static String register_xml_req ="<Registration>"+
"<fname>%s</fname>"+
"<lname>%s</lname>"+
"<address1>%s</address1>"+
"<address2>%s</address2>"+
"<postcode>%s</postcode>"+
"<city>%s</city>"+
"<dob>%s</dob>"+
"<phone>%s</phone>"+
"<email>%s</email>"+
"<image>%s</image>"+
"<note>%s</note>"+
"<phid>%s</phid>"+
"<pharmaemail>%s</pharmaemail>"+
"</Registration>";
httpHelper
if(requestNumber == Constants.CODE_PHARMA)
{
String request = value[0];
response_xml = webAPIRequest.performPost(Constants.Pharmacy_Url, request);
if(response_xml != null)
{
NodeList root = (NodeList) response_xml.getElementsByTagName("GetNearByPharmacy");
Element childnode_root = (Element) root.item(0);
phm.success = getValueFromNode(childnode_root, "success");
Log.i("RESULT===", String.valueOf(phm.success));
if(phm.success.equalsIgnoreCase("true"))
{
NodeList nodelist_phmsist = (NodeList) childnode_root.getElementsByTagName("pharmacist");
for (int i = 0; i < nodelist_phmsist.getLength(); i++)
{
pharmacists Ph = new pharmacists();
Element ch_node = (Element) nodelist_phmsist.item(i);
try
{
Ph.id = parseIntValue(getValueFromNode(ch_node,"id"));
Ph.email=getValueFromNode(ch_node,"email");
Ph.password=getValueFromNode(ch_node,"password");
Ph.name=getValueFromNode(ch_node,"name");
Ph.website=getValueFromNode(ch_node,"website");
Ph.phone=getValueFromNode(ch_node,"phone");
Ph.address1=getValueFromNode(ch_node,"address1");
Ph.address2=getValueFromNode(ch_node,"address2");
Ph.city=getValueFromNode(ch_node,"city");
Ph.area=getValueFromNode(ch_node,"area");
Ph.postcode=getValueFromNode(ch_node,"postcode");
Ph.country=getValueFromNode(ch_node,"country");
Ph.short_description=getValueFromNode(ch_node,"short_description");
Ph.description=getValueFromNode(ch_node,"description");
Ph.business_time=getValueFromNode(ch_node,"business_time");
Ph.twentyfourseven=getValueFromNode(ch_node,"twentyfourseven");
Ph.image1=getValueFromNode(ch_node,"image1");
Ph.image2=getValueFromNode(ch_node,"image2");
Ph.image3=getValueFromNode(ch_node,"image3");
Ph.image4=getValueFromNode(ch_node,"image4");
Ph.parking_type=getValueFromNode(ch_node,"parking_type");
Ph.subscription_plan=getValueFromNode(ch_node,"subscription_plan");
Ph.subscription_type=getValueFromNode(ch_node,"subscription_type");
Ph.date=getValueFromNode(ch_node,"date");
Ph.expiry_date=getValueFromNode(ch_node,"expiry_date");
Ph.setord=getValueFromNode(ch_node,"setord");
Ph.pagename=getValueFromNode(ch_node,"pagename");
Ph.active=getValueFromNode(ch_node,"active");
Ph.latitude=getValueFromNode(ch_node,"latitude");
Ph.longitude=getValueFromNode(ch_node,"longitude");
Ph.CountryName=getValueFromNode(ch_node,"CountryName");
Ph.AreaName=getValueFromNode(ch_node,"AreaName");
Ph.CityName=getValueFromNode(ch_node,"CityName");
Ph.parking_type_name=getValueFromNode(ch_node,"parking_type_name");
Ph.subscription_plan_name=getValueFromNode(ch_node,"subscription_plan_name");
Ph.distance=getValueFromNode(ch_node,"distance");
arr_phm.add(Ph);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
}
else if (requestNumber == Constants.CODE_REGISTER)
{
String request3 = value[0];
response_xml = webAPIRequest.performPost(Constants.Login_url, request3);
if(response_xml != null)
{
NodeList root = (NodeList) response_xml.getElementsByTagName("Registration");
Element childnode_root = (Element) root.item(0);
register.success = getValueFromNode(childnode_root, "success");
register.message = getValueFromNode(childnode_root, "message");
}
}
webapiresponce
package com.Pharma.Httphelper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import android.os.Bundle;
import android.util.Log;
// This class use for Https Request..
public class WebAPIRequest
{
String res = null;
public Document performPost(String apiUrl, String request)
{
// TODO Auto-generated method stub
Document doc = null;
try
{
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(apiUrl);
HttpResponse response;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("xmlrequest", request));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = client.execute(httppost);
InputStream data = response.getEntity().getContent();
// if (HttpHelper.requestNumber == Constants.CODE_REGISTER)
// Log.i("Responce========", convertStreamToString(data));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(data);
Log.e("Responce========", getStringFromDocument(doc));
} catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return doc;
}
public static String convertStreamToString(InputStream is) throws IOException {
if (is != null)
{
StringBuilder sb = new StringBuilder();
String line;
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while ((line = reader.readLine()) != null)
{
sb.append(line).append("\n");
}
}
finally
{
//is.close();
}
return sb.toString();
}
else
{
return "";
}
}
public String getStringFromDocument(Document doc)
{
try
{
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
return writer.toString();
}
catch(TransformerException ex)
{
ex.printStackTrace();
}
return null;
}
public static List<NameValuePair> getListOfNameValuePair(Bundle parameters) throws IOException
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
if (parameters == null)
return null;
for (String key : parameters.keySet())
{
try
{
nameValuePairs.add(new BasicNameValuePair(key, parameters.getString(key)));
}
catch (Exception e)
{
e.printStackTrace();
}
}
return nameValuePairs;
}
}
Subscribe to:
Posts (Atom)