Create DatabaseHelper class and create table. and queries related to it.
DBHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
int mStatus;
String TAG="DatabaseHelper";
private static final int DB_VERSION = 15;
private static final String DB_NAME = "CursorDemo";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE paypal_secondary_receivers(sp_profile_id varchar NOT NULL,"+
"paypal_merchant_id varchar ,"+
"email_id varchar ,"+
"profile_type INTEGER ,"+
"secondary_receiver_percentage float ,"+
"delay_time_days INTEGER ,"+
"merchant_street_address varchar ,"+
"merchant_city varchar ,"+
"merchant_country varchar ,"+
"merchant_postcode varchar )");
}
/**
* GetMerchantAccount Details
*/
public Merchant getMerchantAccount(String profileid){
Merchant merchant=null;
SQLiteDatabase database = this.getWritableDatabase();
Cursor data= database.query("paypal_secondary_receivers", new String[] {"sp_profile_id", "paypal_merchant_id","email_id",
"merchant_street_address",
"merchant_city",
"merchant_country",
"merchant_postcode"},new String("sp_profile_id"+"=?"),new String[]{profileid.toString()}, null, null, null);
if (data!= null)
{
if (data.moveToFirst()){
do{
String sp_profileid=data.getString(data.getColumnIndex("sp_profile_id"));
String paypal_merchant_id=data.getString(data.getColumnIndex("paypal_merchant_id"));
String email_id=data.getString(data.getColumnIndex("email_id"));
//String profile_type=data.getString(data.getColumnIndex("profile_type"));
String merchant_street_address=data.getString(data.getColumnIndex("merchant_street_address"));
String merchant_city=data.getString(data.getColumnIndex("merchant_city"));
String merchant_country=data.getString(data.getColumnIndex("merchant_country"));
String merchant_postcode=data.getString(data.getColumnIndex("merchant_postcode"));
merchant=new Merchant();
merchant.sp_profile_id=sp_profileid;
merchant.email_id=email_id;
merchant.paypal_merchant_id=paypal_merchant_id;
merchant.merchant_street_address=merchant_street_address;
merchant.merchant_city=merchant_city;
merchant.merchant_country=merchant_country;
merchant.merchant_postcode=merchant_postcode;
}while(data.moveToNext());
}
data.close();
//database.close();
}
return merchant;
}
ApplicationManager.java
String TAG="ApplicationManager";
private DatabaseHelper mDBHelper;
private NetworkManager mNWmgr;
private Context mCtx;
private static ApplicationManager mApplicationMgr;
private ApplicationManager(Context context) {
mCtx = context;
mDBHelper =null;
mNWmgr=null;
}
/**
* getting Instance
* @param context
* @return DBAdapter
*/
public static synchronized ApplicationManager getApplicationMgrInstance(Context context) {
if (mApplicationMgr == null) {
mApplicationMgr = new ApplicationManager(context);
}
return mApplicationMgr;
}
/**
* method to get NetworkManager class instance
*
*/
public NetworkManager getNetworkManager()
{
if(mNWmgr==null)
{
mNWmgr=new NetworkManager(mCtx);
}
return mNWmgr;
}
/**
* method to get DatabaseHelper class instance
*
*/
public DatabaseHelper getDbHelper()
{
if(mDBHelper==null)
{
mDBHelper=new DatabaseHelper(mCtx);
}
return mDBHelper;
}
public Merchant getMerchantDetail(String key) {
Log.d(TAG,"merchant detail called");
if(mDBHelper==null)
{
mDBHelper=new DatabaseHelper(mCtx);
}
return mDBHelper.getMerchantAccount(key);
}
}
BaseClass.java
/*which stores dilogs like session handling,checking network connection etc.
public class BaseClass extends Activity {
private static String TAG="BaseClass";
private Context mContext;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
void sessionTimeOut(Context ctx)
{
mContext = ctx;
AlertDialog.Builder dialog1 = new AlertDialog.Builder(mContext);
dialog1.setTitle("ALERT");
dialog1.setMessage("Session Timed OUT!Relogin");
dialog1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog1, int id) {
Intent i=new Intent(mContext,LoginInfo.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(i);
finish();
}
});
dialog1.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert =dialog1.create();
// Title for AlertDialog
alert.setTitle("Session Expired");
// Icon for AlertDialog
alert.setIcon(R.drawable.icon);
alert.show();
}
public void popIt(Context ctx, String title, String message ){
mContext = ctx;
AlertDialog.Builder dialog2 = new AlertDialog.Builder(mContext);
dialog2.setTitle( title );
dialog2.setMessage( message );
dialog2.setPositiveButton("Ok", new OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do stuff onclick of YES
}
});
AlertDialog alert =dialog2.create();
// Title for AlertDialog
alert.setTitle("");
// Icon for AlertDialog
alert.setIcon(R.drawable.icon);
alert.show();
}
public void popError(Context ctx, String title, String message ){
mContext = ctx;
AlertDialog.Builder dialog3 = new AlertDialog.Builder(ctx);
dialog3.setTitle( title );
dialog3.setMessage( message );
dialog3.setPositiveButton("Ok", new OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do stuff onclick of YES
}
});
AlertDialog alert =dialog3.create();
// Title for AlertDialog
alert.setTitle(title);
// Icon for AlertDialog
alert.setIcon(R.drawable.icon);
alert.show();
}
void showAlertNoConnection(Context ctx) {
mContext = ctx;
Log.i(TAG,"Entered base clas "+"no connection alert");
AlertDialog.Builder dialog1 = new AlertDialog.Builder(mContext);
dialog1.setTitle("ALERT");
dialog1.setMessage("No Connection! Try Later");
dialog1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog1, int id) {
finish();
}
});
AlertDialog alert =dialog1.create();
// Title for AlertDialog
alert.setTitle("OUT OF CONNECTION");
// Icon for AlertDialog
alert.setIcon(R.drawable.icon);
alert.show();
}
}
merchant layout
merchnatac.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:background="@drawable/bk_gnd">
<TextView android:id="@+id/pubprof_name" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:textSize="@dimen/menu_buttons_text_size"
android:textColor="@color/menu_buttons" android:textStyle="bold"
android:text="Merchant Account" android:gravity="center" />
<TextView android:layout_width="fill_parent"
android:layout_height="20dip" />
<TableRow>
<TextView android:text="Merchant id" android:id="@+id/emid"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:padding="5dip"
android:textColor="@color/menu_buttons" />
<EditText android:id="@+id/emidv" android:layout_width="150px"
android:padding="3dip"
android:background="@android:drawable/editbox_background"
android:cursorVisible="true" android:typeface="normal"
android:editable="true" />
</TableRow>
<TableRow>
<TextView android:text="Email Id" android:id="@+id/editmail"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:padding="5dip"
android:textColor="@color/menu_buttons" />
<EditText android:id="@+id/editemail" android:layout_width="150px"
android:padding="3dip"
android:background="@android:drawable/editbox_background"
android:cursorVisible="true" android:typeface="normal"
android:editable="true" />
</TableRow>
<TableRow>
<TextView android:text="City" android:id="@+id/emcity"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:textColor="@color/menu_buttons"
android:padding="5dip" />
<EditText android:id="@+id/emcityv" android:layout_width="150px"
android:padding="3dip"
android:background="@android:drawable/editbox_background"
android:cursorVisible="true" android:typeface="normal"
android:editable="true" />
</TableRow>
<TableRow>
<TextView android:text="Country" android:id="@+id/emcnt"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:padding="5dip"
android:textColor="@color/menu_buttons" />
<EditText android:id="@+id/emcntv" android:layout_width="150px"
android:padding="3dip"
android:background="@android:drawable/editbox_background"
android:cursorVisible="true" android:typeface="normal"
android:editable="true" />
</TableRow>
<TableRow>
<TextView android:text=" Street Address" android:id="@+id/estadd"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:padding="5dip"
android:textColor="@color/menu_buttons" />
<EditText android:id="@+id/estreet" android:layout_width="150px"
android:padding="3dip"
android:background="@android:drawable/editbox_background"
android:cursorVisible="true" android:typeface="normal"
android:editable="true" />
</TableRow>
<TableRow>
<TextView android:text="Postal Code" android:id="@+id/epc"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:padding="5dip"
android:textColor="@color/menu_buttons"/>
<EditText android:id="@+id/epostcode" android:layout_width="150px"
android:padding="3dip"
android:background="@android:drawable/editbox_background"
android:cursorVisible="true" android:typeface="normal"
android:editable="true" />
</TableRow>
<Button android:id="@+id/mdone" android:text="Done"
android:textSize="@dimen/menu_buttons_text_size" android:textColor="@color/menu_buttons"
android:textStyle="bold" android:gravity="center"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_below="@id/upload_image" android:background="@drawable/button_menu" />
<Button android:id="@+id/refresh1" android:text="Refresh"
android:textSize="@dimen/menu_buttons_text_size" android:textColor="@color/menu_buttons"
android:textStyle="bold" android:layout_gravity="center"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@drawable/button_menu" />
</TableLayout>
</ScrollView>
MyMerchantAccount.java
//which displayes merchant details
/**
* Class Name :MyMerchantAccount
*
* Parent Class :BaseClass
*
* Interfaces: None
*
* Description:This class displays Merchant Details like Paypal account details
*
*/
public class MyMerchantAccount extends BaseClass {
private static final String TAG="MyMerchantAccount";
private EditText mMerchantId,mCity,mCountry,mEmail,mStreet,mPostal;
private String mMerchantId1,mCity1,mCountry1,mEmail1,mStreet1,mPostal1;
Button mDone,mRefresh;
public static String mProfile_id;
TextView mTxt;
private ProgressDialog mProgDlg;
boolean mIsBound;
Merchant mMyMerchantAccount;
private static ApplicationManager mAppMgr;
private DatabaseHelper mDBHelper;
private static final int INDETERMINATE = 0;
private Context mContext;
BaseClass mBaseClass = new BaseClass();
final Messenger mMessenger = new Messenger(new IncomingHandler());
Messenger mService = null;
class IncomingHandler extends Handler {
/**
* Callback method to handle messages coming from server
*
*/
@Override
public void handleMessage(Message msg) {
Log.e(TAG,"UIAct "+"handleMessage for mymerchant");
switch (msg.what) {
case NetworkService.MSG_RETRIEVED_MERCHANT_ACCOUNT_DETAILS:
String key = (String) msg.obj;
Bundle b9 =msg.getData();
String status=b9.getString("status");
Log.i(TAG,"My Key handle msg of mymerchant status : "+status);
if(status.equals("200")){
Log.i(TAG,"My Key handle msg of mymerchant key : "+key);
mMyMerchantAccount=mAppMgr.getMerchantDetail(key);
//doUnbindService();
//mProgDlg.dismiss();
mMerchantId1=mMyMerchantAccount.paypal_merchant_id;
mCity1=mMyMerchantAccount.merchant_city;
mCountry1=mMyMerchantAccount.merchant_country;
mEmail1=mMyMerchantAccount.email_id;
mStreet1=mMyMerchantAccount.merchant_street_address;
mPostal1=mMyMerchantAccount.merchant_postcode;
mMerchantId.setText(mMerchantId1);
mCity.setText(mCity1);
mCountry.setText(mCountry1);
mEmail.setText(mEmail1);
mStreet.setText(mStreet1);
mPostal.setText(mPostal1);
mProgDlg.dismiss();
doUnbindService();
}
else if(status.equals("408"))
{
mBaseClass.sessionTimeOut(mContext);
}
else{
mProgDlg.dismiss();
setContentView(R.layout.nodata);
mTxt=(TextView) findViewById(R.id.nodata);
mTxt.setText("No Data Under this Profile!");
//doUnbindService();
}
break;
default:
super.handleMessage(msg);
}
}
}
/**
* Callback method to get connection from server
*
*/
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
Log.e(TAG,"binding to "+"service in ServiceConnection ");
try {
Message msg = Message.obtain(null, NetworkService.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
msg = Message.obtain(null, NetworkService.MSG_GET_MERCHANT_ACCOUNT);
Bundle b1=new Bundle();
b1.putString("profileid",mProfile_id);
msg.setData(b1);
Log.d(TAG,"connecting "+"for merchantaccountdetail");
msg.replyTo = mMessenger;
mService.send(msg);
}
catch (RemoteException e) {
// In this case the service has crashed before we could even do anything with it
}
}
/**
* Callback method to get disconnect from server
*
*/
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been unexpectedly disconnected - process crashed.
mService = null;
Log.e(TAG,"UIAct "+"onServiceDisconnected");
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAppMgr = ApplicationManager.getApplicationMgrInstance(this.getApplicationContext());
setContentView(R.layout.merchantac);
mMerchantId=(EditText) findViewById(R.id.emidv);
mCity=(EditText) findViewById(R.id.emcityv);
mCountry=(EditText) findViewById(R.id.emcntv);
mEmail=(EditText) findViewById(R.id.editemail);
mStreet=(EditText) findViewById(R.id.estreet);
mPostal=(EditText) findViewById(R.id.epostcode);
mDone=(Button) findViewById(R.id.mdone);
mRefresh=(Button) findViewById(R.id.refresh1);
mContext=this;
Intent ip = getIntent();
mProfile_id=(String) ip.getCharSequenceExtra("profileid");
Log.d(TAG,"profile id is : "+mProfile_id);
mMyMerchantAccount=mAppMgr.getMerchantDetail(mProfile_id);
if(mMyMerchantAccount==null)
{
if (NetworkUtilService.getInstance(this).isOnline(this)) {
Log.e(TAG,"binding to "+"service for merchant account details");
doBindService();
// bindService(new Intent(this, NetworkService.class), mConnection, Context.BIND_AUTO_CREATE);
showDialog(INDETERMINATE);
} else {
ShowAlertNoConnection();
}
}
else
{
mMerchantId1=mMyMerchantAccount.paypal_merchant_id;
mCity1=mMyMerchantAccount.merchant_city;
mCountry1=mMyMerchantAccount.merchant_country;
mEmail1=mMyMerchantAccount.email_id;
mStreet1=mMyMerchantAccount.merchant_street_address;
mPostal1=mMyMerchantAccount.merchant_postcode;
mMerchantId.setText(mMerchantId1);
mCity.setText(mCity1);
mCountry.setText(mCountry1);
mEmail.setText(mEmail1);
mStreet.setText(mStreet1);
mPostal.setText(mPostal1);
}
if(EditAccount.mCurrentview==Globals.EDIT_ACCOUNT)
{
doBindService();
showDialog(INDETERMINATE);
mDone.setVisibility(View.VISIBLE);
mRefresh.setVisibility(View.GONE);
}
else
{
mDone.setVisibility(View.GONE);
}
mDone.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
EditAccount.mCurrentview=Globals.EDIT_ACCOUNT;
Intent ip = getIntent();
String profileid1=(String) ip.getCharSequenceExtra("profileid");
Log.e(TAG,"profileid1 : "+profileid1);
mMyMerchantAccount.paypal_merchant_id=mMerchantId.getText().toString();
mMyMerchantAccount.merchant_city=mCity.getText().toString();
mMyMerchantAccount.merchant_country=mCountry.getText().toString();
mMyMerchantAccount.email_id=mEmail.getText().toString();
mMyMerchantAccount.merchant_street_address=mStreet.getText().toString();
Log.e(TAG,"mMyMerchantAccount.email_id in DONE button "+mMyMerchantAccount.email_id);
mMyMerchantAccount.merchant_postcode=mPostal.getText().toString();
Intent resultIntent=new Intent(MyMerchantAccount.this,EditAccount.class);
Bundle b=new Bundle();
b.putParcelable("merchantdetails",mMyMerchantAccount);
resultIntent.putExtra("mdetails",b);
setResult(RESULT_OK, resultIntent);
finish();
}
});
mRefresh.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
Boolean connected = networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
Log.d(TAG,"connection "+connected);
if (connected)
{
Log.e(TAG,"button 1 clicked");
Log.e(TAG,"binding to "+"service for transactiondetails in refresh");
doBindService();
//bindService(new Intent(MyTransactions.this, NetworkService.class), mConnection, Context.BIND_AUTO_CREATE);
showDialog(INDETERMINATE);
//doUnbindService();
}
else
{
ShowAlertNoConnection();
}
}
});
}
protected void ShowAlertNoConnection() {
AlertDialog.Builder dialog1 = new AlertDialog.Builder(MyMerchantAccount.this);
dialog1.setTitle("ALERT");
dialog1.setMessage("No Connection! Try Later");
dialog1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog1, int id) {
MyMerchantAccount.this.finish();
//dialog1.cancel();
}
});
AlertDialog alert =dialog1.create();
// Title for AlertDialog
alert.setTitle("OUT OF CONNECTION");
// Icon for AlertDialog
alert.setIcon(R.drawable.icon);
alert.show();
}
void doBindService() {
// Establish a connection with the service. We use an explicit
// class name because there is no reason to be able to let other
// applications replace our component.
bindService(new Intent(MyMerchantAccount.this,
NetworkService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
// If we have received the service, and hence registered with
// it, then now is the time to unregister.
if (mService != null) {
try {
Message msg = Message.obtain(null,
NetworkService.MSG_UNREGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
// There is nothing special we need to do if the service
// has crashed.
}
}
// Detach our existing connection.
unbindService(mConnection);
mIsBound = false;
}
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case INDETERMINATE: {
mProgDlg = new ProgressDialog(this);
mProgDlg.setTitle("Indeterminate");
mProgDlg.setMessage("Please wait while loading...");
mProgDlg.setIndeterminate(true);
mProgDlg.setCancelable(true);
return mProgDlg;
}
}
return null;
}
@Override
public void onDestroy() {
Log.i(TAG,"onDestroy Called");
super.onDestroy();
try {
unbindService(mConnection);
} catch (Throwable t) {
}
}
}
NetworkService.java
public class NetworkService extends Service {
private static boolean mIsRunning = false;
private static ApplicationManager mAppMgr;
RegistrationRes mRes1;
NetworkManager mNtwMngr;
ArrayList<Phnos > mPhnolist;
String TAG="NetworkService";
// Target we publish for clients to send messages to IncomingHandler.
final Messenger mMessenger = new Messenger(new IncomingHandler());
//constants
public static final int MSG_REGISTER_CLIENT = 1;
public static final int MSG_UNREGISTER_CLIENT = 2;
public static final int MSG_GET_MERCHANT_ACCOUNT=117;
public static final int MSG_RETRIEVED_MERCHANT_ACCOUNT_DETAILS=36;
private String mProfileid;
int mLogin;
int mCatv=0;
@Override
public IBinder onBind(Intent intent) {
mAppMgr = ApplicationManager.getApplicationMgrInstance(this.getApplicationContext());
mNtwMngr=mAppMgr.getNetworkManager();
Log.e(TAG, "OnBind is called for intent" + intent.describeContents());
return mMessenger.getBinder();
}
/**
* Class Name :IncomingHandler
*
* Parent Class :Handler
*
* Interfaces: None
*
* Description:Handler class for handling
*
* incoming messages from client
*/
class IncomingHandler extends Handler {
// Handler of incoming messages from clients.
/**
* Callback method to handle messages coming from client
*
*/
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REGISTER_CLIENT:
mClients.add(msg.replyTo);
Log.e(TAG,"client "+"added");
break;
case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
Log.e(TAG,"client "+"removed");
break;
case MSG_GET_MERCHANT_ACCOUNT:
Bundle b11 = msg.getData();
final String key11 = b11.getString("profileid");
Log.e(TAG,"My Merchant Key handle msg"+key11);
String status11=null;
try {
status11 = mNtwMngr.getMyMerchantAccountDetailsFromServer(key11);
} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
sendMessageToClient11(MSG_RETRIEVED_MERCHANT_ACCOUNT_DETAILS,key11,status11);
break;
default:
super.handleMessage(msg);
}
}
}
private void sendMessageToClient11(int intvaluetosend,String key,String status ) {
for (int i=mClients.size()-1; i>=0; i--) {
try {
// Send data as an Integer
Message msg = Message.obtain(null,MSG_RETRIEVED_MERCHANT_ACCOUNT_DETAILS,key);
Log.e(TAG,"servermsg in sending msg to client for mysps"+key);
Bundle b5=new Bundle();
b5.putString("status",status);
Log.e(TAG,"status "+status);
msg.setData(b5);
mClients.get(i).send(msg);
} catch (RemoteException e) {
// The client is dead. Remove it from the list; we are going through the list from back to front so this is safe to do inside the loop.
mClients.remove(i);
}
}
}
NetworkManager.java
public class NetworkManager {
public NetworkManager(Context context) {
mCtx = context;
mAppMgr = ApplicationManager.getApplicationMgrInstance(mCtx);
}
String getMyMerchantAccountDetailsFromServer(final String key) throws Exception {
mDBHelper =mAppMgr.getDbHelper();
String MyMerchantAcctDetail=CustomHttpClient.executeHttpGet(Configure.SM_SERVER_URL_PREFIX+"merchantDetails?profile_id="+key+"&client_type=mc&catalog_version_id=0");
String status=JSONSMParser.parseStatus(MyMerchantAcctDetail);
Log.d(TAG,MyMerchantAcctDetail);
if(status.equals("200")){
mMyMerchantAcctDetail=JSONSMParser.parseMyMerchantAcctDetail(MyMerchantAcctDetail);
createMyMerchantAcctDetail(mDBHelper,key);
Log.e(TAG,"mysubscriberdetails");
return status;
}
else if(status.equals("408"))
{
return status;
}
else
return status;
}
private void createMyMerchantAcctDetail(DatabaseHelper mDBHelper,String key) {
// TODO Auto-generated method stub
SQLiteDatabase database = mDBHelper.getWritableDatabase();
ContentValues acctdetail= new ContentValues();
String pay_merchant_id=mMyMerchantAcctDetail.paypal_merchant_id;
Log.d(TAG,"paymerchatid "+ pay_merchant_id);
String merchant_city=mMyMerchantAcctDetail.merchant_city;
String merchat_country=mMyMerchantAcctDetail.merchant_country;
String email_id=mMyMerchantAcctDetail.email_id;
String merchant_postcode=mMyMerchantAcctDetail.merchant_postcode;
String merchant_street_address=mMyMerchantAcctDetail.merchant_street_address;
Log.d(TAG,"merchant_street_address : "+ merchant_street_address);
acctdetail.put("sp_profile_id", key);
acctdetail.put("paypal_merchant_id", pay_merchant_id);
acctdetail.put("email_id", email_id);
acctdetail.put("merchant_city", merchant_city);
acctdetail.put("merchant_country", merchat_country);
acctdetail.put("merchant_street_address", merchant_street_address);
acctdetail.put("merchant_postcode", merchant_postcode);
database.insert("paypal_secondary_receivers",null,acctdetail);
}
//follwoing method to post the data to server example
/**
* change password
*/
public String getchangepassword(final String key_existingpass, final String key_newpass,final String key_newrepass,final String profileid) throws Exception {
Log.e(TAG,"expass "+key_existingpass);
Log.e(TAG,"newpass "+key_newpass);
Log.e(TAG,"newrepass "+key_newrepass);
Log.e(TAG,"id "+profileid);
String mRes=null;
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("existing_password", key_existingpass));
postParameters.add(new BasicNameValuePair("new_password", key_newpass ));
postParameters.add(new BasicNameValuePair("confirm_password",key_newrepass));
postParameters.add(new BasicNameValuePair("profileId",profileid));
postParameters.add(new BasicNameValuePair("client_type", "mc"));
mDBHelper =mAppMgr.getDbHelper();
String response = CustomHttpClient.executeHttpPost2(Configure.SM_SERVER_URL_PREFIX+"changepass", postParameters);
Log.i(TAG,response);
String status=JSONSMParser.parseStatus(response);
if(status.equals("200")){
return status;
}
else
return status;
}
JSONSMParser.java
public class JSONSMParser{
/**
* method to parse login status coming from server
*
*/
public static String parseStatus(String jsonString) {
String login_statuscode=null;
String status_msg=null;
try {
JSONObject jObject = new JSONObject(jsonString);
login_statuscode=jObject.getString("status_code");
status_msg=jObject.getString("status_msg");
Log.d(TAG,"login status "+jObject.getString("status_code"));
}
catch (JSONException e) {
e.printStackTrace();
}
return login_statuscode;
}
public static Merchant parseMyMerchantAcctDetail(String myMerchantAcctDetail) {
/*{"merchantAccountBean":["ssell_1316531348_biz@inceptionitsystems.com",
"Hyderabad","India","naresh.mogili@gmail.com","5000082",
"Banjara Hils"]}*/
Merchant m = new Merchant();
try {
JSONObject jObject = new JSONObject(myMerchantAcctDetail);
JSONArray menuitemArray1 = jObject.getJSONArray("merchantAccountBean");
for(int i=0;i<menuitemArray1.length();i++){
m.paypal_merchant_id=menuitemArray1.getString(i);
Log.e(TAG,"paypal merchant id "+m.paypal_merchant_id);
m.email_id=menuitemArray1.getString(++i);
m.merchant_street_address=menuitemArray1.getString(++i);
m.merchant_city=menuitemArray1.getString(++i);
m.merchant_country=menuitemArray1.getString(++i);
m.merchant_postcode=menuitemArray1.getString(++i);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return m;
}
}
CustomHttpClient.java
package com.inception.network;
/**
* Class Name : CustomHttpClient
*
* Parent Class :
*
* Interfaces: None
*
* Description: Handles Http get and post.
*
*/
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.net.HttpURLConnection;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
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.client.protocol.ClientContext;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.cookie.Cookie;
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.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;
public class CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
private static HttpContext mHttpContext;
private static Bitmap bitmap;
public static Cookie mSessionCookie;
static String TAG="CustomHttpClient";
/**
* Get our single instance of our HttpClient object.
*
* @return an HttpClient object with connection parameters set
*/
public static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
private static HttpContext getHttpContext(){
if(mHttpContext==null){
mHttpContext=new BasicHttpContext();
}
return mHttpContext;
}
private static String connect(String url){
HttpClient client = getHttpClient();
HttpGet httpget = new HttpGet(url);
httpget.getAllHeaders();
HeaderElementIterator it1 = new BasicHeaderElementIterator(
httpget.headerIterator());
System.out.println(httpget.getURI());
while (it1.hasNext()) {
HeaderElement elem = it1.nextElement();
System.out.println("session name"+elem.getName() + " = " + elem.getValue());
NameValuePair[] params = elem.getParameters();
for (int i = 0; i < params.length; i++) {
System.out.println(" " + params[i]);
}
}
// Execute the request
HttpResponse response;
// return string
String returnString = null;
try {
// Open the webpage.
response =client.execute(httpget);
// if(response.getStatusLine().getStatusCode() == 200){
if(true) {
// Connection was established. Get the content.
HttpEntity entity = response.getEntity();
//SetCookie c=new Cookie();
//SetCookie.setValue(mSessionId);
response.getAllHeaders();
Log.e("headers",""+response.getAllHeaders());
HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator());
while (it.hasNext()) {
HeaderElement elem = it.nextElement();
System.out.println(elem.getName() + " = " + elem.getValue());
NameValuePair[] params = elem.getParameters();
for (int i = 0; i < params.length; i++) {
System.out.println(" " + params[i]);
}
}
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
// Load the requested page converted to a string into a JSONObject.
// JSONObject myAwway = new JSONObject(convertStreamToString(instream));
returnString = convertStreamToString(instream);
// Log.e(TAG,"instream : "+convertStreamToString(instream));
// Log.e(TAG,"myawway : "+ myAwway);
// Get the query value'
//String query = myAwway.getString("query");
// JSONObject menuObject =myAwway.getJSONObject("photos");
// Make array of the suggestions
// JSONArray suggestions =menuObject.getJSONArray("photo");
// Build the return string.
// returnString = "Found: " + suggestions.length() ;
// for (int i = 0; i < suggestions.length(); i++) {
// returnString += "\n\t" +(suggestions.getJSONObject(i).getString("id").toString());
// }
// returnString = "Found";
// Cose the stream.
instream.close();
}
}
else {
// code here for a response othet than 200. A response 200 means the webpage was ok
// Other codes include 404 - not found, 301 - redirect etc...
// Display the response line.
returnString = "Unable to load page - " + response.getStatusLine();
}
return returnString ;
}
catch (IOException ex) {
// thrown by line 80 - getContent();
// Connection was not established
returnString = "Connection failed; " + ex.getMessage();
}
// catch (JSONException ex){
// JSON errors
// returnString = "JSON failed; " + ex.getMessage();
// }
return returnString;
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.e("sb string : ",""+ sb.toString());
return sb.toString();
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* @param url The web address to post the request to
* @param postParameters The parameters to send via the request
* @return The result of the request
* @throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpContext localContext=getHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
Log.e( "postParameters",""+ postParameters);
Log.e("formEntity",""+formEntity);
/* MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("returnformat", new StringBody("json"));
entity.addPart("uploaded", new ByteArrayBody(data,
"myImage.jpg"));*/
request.setEntity(formEntity);
HttpResponse response = client.execute(request,localContext);
//HttpResponse response = client.execute(request);
Log.e("headers",""+response.headerIterator());
//String mSessionId=null;
// Log.e("mSessionId",""+mSessionId);
HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator());
while (it.hasNext()) {
HeaderElement elem = it.nextElement();
System.out.println(elem.getName() + " = " + elem.getValue());
if(elem.getName().equals("JSESSIONID")){
NetworkManager.mSessionId=elem.getValue();
}
NameValuePair[] params = elem.getParameters();
for (int i = 0; i < params.length; i++) {
System.out.println(" " + params[i]);
}
}
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
List<Cookie> cookies = cookieStore.getCookies();
Log.e("CustomHttpClient","Cookies size= " + cookies.size());
for (int i = 0; i < cookies.size(); i++) {
Cookie cookie = cookies.get(i);
Log.e("CustomHttpClient","Local cookie: " + cookie);
mSessionCookie = cookie;
Log.e("CustomHttpClient",""+cookie.getValue());
}
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static String executeHttpPost2(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
// Create a local instance of cookie store
//CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpContext localContext=getHttpContext();
// Bind custom cookie store to the local context
//localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
Log.e( "postParameters",""+ postParameters);
Log.e("formEntity",""+formEntity);
/* MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("returnformat", new StringBody("json"));
entity.addPart("uploaded", new ByteArrayBody(data,
"myImage.jpg"));*/
request.setEntity(formEntity);
HttpResponse response = client.execute(request,localContext);
//HttpResponse response = client.execute(request);
Log.e("headers",""+response.headerIterator());
//String mSessionId=null;
// Log.e("mSessionId",""+mSessionId);
HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator());
while (it.hasNext()) {
HeaderElement elem = it.nextElement();
System.out.println(elem.getName() + " = " + elem.getValue());
if(elem.getName().equals("JSESSIONID")){
NetworkManager.mSessionId=elem.getValue();
}
NameValuePair[] params = elem.getParameters();
for (int i = 0; i < params.length; i++) {
System.out.println(" " + params[i]);
}
}
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
/* List<Cookie> cookies = cookieStore.getCookies();
Log.e("CustomHttpClient","Cookies size= " + cookies.size());
for (int i = 0; i < cookies.size(); i++) {
Cookie cookie = cookies.get(i);
Log.e("CustomHttpClient","Local cookie: " + cookie);
mSessionCookie = cookie;
Log.e("CustomHttpClient",""+cookie.getValue());
}*/
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static String executeHttpPost1(String url,ArrayList<NameValuePair> postParameters ) throws Exception {
HttpPost post = new HttpPost(url);
Bitmap bitmap;
String Result_STR=null;
HttpClient client = getHttpClient();
HttpContext localContext=getHttpContext();
HttpEntity resmarkMessagesReadFrom =null;
MultipartEntity reqmarkMessagesReadFrom = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
Log.e(TAG+"postParameters.size()",""+postParameters.size());
for(int i=0;i<postParameters.size();i++){
Log.e(TAG+"parameters",""+postParameters.get(i).getName()+""+postParameters.get(i).getValue());
if(postParameters.get(i).getName().equals("spProfilePic")){
bitmap = BitmapFactory.decodeFile(postParameters.get(i).getValue());
// you can change the format of you image compressed for what do you want;
//now it is set up to 640 x 480;
Bitmap bmpCompressed = Bitmap.createScaledBitmap(bitmap, 640, 480, true);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// CompressFormat set up to JPG, you can change to PNG or whatever you want;
bmpCompressed.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
Log.e(TAG,"data"+data);
reqmarkMessagesReadFrom.addPart(postParameters.get(i).getName(), new ByteArrayBody(data, "temp.jpg"));
Log.e(TAG,"bitmap"+bitmap);
}
else
reqmarkMessagesReadFrom.addPart(postParameters.get(i).getName(), new StringBody(postParameters.get(i).getValue()));
}
post.setEntity(reqmarkMessagesReadFrom);
Log.e(TAG,"after for loop"+post.getEntity());
HttpResponse response = client.execute(post,localContext);
Log.e("headers",""+response.getAllHeaders());
resmarkMessagesReadFrom = response.getEntity();
if (resmarkMessagesReadFrom != null) {
Result_STR=EntityUtils.toString(resmarkMessagesReadFrom);
// mMSGBox.setText(Result_STR);
}
}
catch(Exception e){
Log.e(TAG,e.toString());
}
finally {
}
return Result_STR;
}
/**
* Performs an HTTP GET request to the specified url.
*
* @param url The web address to post the request to
* @return The result of the request
* @throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
HttpContext localContext=getHttpContext();
request.setURI(new URI(url));
HttpResponse response = client.execute(request,localContext);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
Log.e("headers",""+response.headerIterator());
//String mSessionId=null;
// Log.e("mSessionId",""+mSessionId);
HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator());
while (it.hasNext()) {
HeaderElement elem = it.nextElement();
System.out.println(elem.getName() + " = " + elem.getValue());
if(elem.getName().equals("JSESSIONID")){
NetworkManager.mSessionId=elem.getValue();
}
NameValuePair[] params = elem.getParameters();
for (int i = 0; i < params.length; i++) {
System.out.println(" " + params[i]);
}
}
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
for abouve Customhttp class use commons-io-2.0.1.jar & httpmime-4.1-beta1.jar
No comments:
Post a Comment