Sunday, 15 June 2014

Date and Alert dialog (Register) example

package com.rws.ohmsantihyoga;

import java.util.Calendar;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.rws.localwsutils.AppUtil;
import com.rws.wsutil.PostAndGetData.onJsonResult;
import com.rwsutil.masterview.GroupPrefrences.RegisterPref;
import com.rwsutil.masterview.MyBaseActivityWS;
import com.rwsutil.masterview.WebServiceUrl;

public class RegisterActivity extends MyBaseActivityWS implements onJsonResult,
RegisterPref, WebServiceUrl, OnClickListener {

private EditText edtUserName, edtFirstName, edtLastName, edtDateOfBirth,
edtGender, edtStreetAddress, edtAppartment, edtTownCity,
edtPostCode;
private EditText edtEmailAddress, edtPhoneNumber, edtAccountPassword,
edtConfirmPassword, edtNote, edtContry;
private int register_responcCode = 900;
private ImageView iconMenu, iconHome;
private Button btnSubmit;
private int Year = 0, Month = 0, Day = 0,iCount = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_activity);
setTitle("Register");
setBehindContentView(R.layout.menu_frame);
getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getActionBar().setCustomView(R.layout.headder_back);
getActionBar().setBackgroundDrawable(
new ColorDrawable(R.color.brn_lite));
getSlidingMenu().setSlidingEnabled(false);
// mAppUtil = AppUtil.getInstance();

// mSPreferences = getSharedPreferences(
// Constants.SHAREDPREFERENCE.SHAREDPREFERENCES, 0);

// strUserID = mSPreferences.getString(Constants.USER_ID, "");
// strUserRole = mSPreferences.getString(Constants.USER_ROLE, "");

iconMenu = (ImageView) findViewById(R.id.iconMenu);
iconMenu.setVisibility(ImageView.VISIBLE);
iconMenu.setOnClickListener(this);
iconHome = (ImageView) findViewById(R.id.iconHome);
iconHome.setOnClickListener(this);

edtUserName = (EditText) findViewById(R.id.edtUserName);
observeText(edtUserName);
edtFirstName = (EditText) findViewById(R.id.edtFirstName);
observeText(edtFirstName);
edtLastName = (EditText) findViewById(R.id.edtLastName);

observeText(edtLastName);
edtStreetAddress = (EditText) findViewById(R.id.edtStreetAddress);
edtDateOfBirth = (EditText) findViewById(R.id.edtDateOfBirth);
edtDateOfBirth.requestFocus();
edtDateOfBirth.setOnClickListener(this);
edtGender = (EditText) findViewById(R.id.edtGender);
edtGender.requestFocus();
edtGender.setOnClickListener(this);
edtStreetAddress = (EditText) findViewById(R.id.edtStreetAddress);
observeText(edtStreetAddress);
edtAppartment = (EditText) findViewById(R.id.edtAppartment);
edtTownCity = (EditText) findViewById(R.id.edtTownCity);
observeText(edtTownCity);
edtPostCode = (EditText) findViewById(R.id.edtPostalCode);
observeText(edtPostCode);
edtContry = (EditText) findViewById(R.id.edtContry);
observeText(edtContry);
edtEmailAddress = (EditText) findViewById(R.id.edtEmailAddress);
observeText(edtEmailAddress);
edtPhoneNumber = (EditText) findViewById(R.id.edtPhoneNumber);
observeText(edtPhoneNumber);
edtAccountPassword = (EditText) findViewById(R.id.edtAccountPassword);
observeText(edtAccountPassword);
edtConfirmPassword = (EditText) findViewById(R.id.edtConfirmPassword);
observeText(edtConfirmPassword);
edtNote = (EditText) findViewById(R.id.edtNote);
onFocusChange(edtNote);
// imgLeftDevider = (ImageView)findViewById(R.id.imgLeftDivider);
// imgLeftDevider.setVisibility(ImageView.INVISIBLE);
// iconMenu = (ImageView)findViewById(R.id.iconMenu);
// iconMenu.setVisibility(ImageView.INVISIBLE);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(this);
edtDateOfBirth = (EditText) findViewById(R.id.edtDateOfBirth);
edtDateOfBirth.requestFocus();
edtDateOfBirth.setOnClickListener(this);
edtDateOfBirth
.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
DateDialog();
}
}
});
edtGender = (EditText) findViewById(R.id.edtGender);
edtGender.requestFocus();
edtGender.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
onCreateDialog();
}
}
});

// edtGender.setOnClickListener(this);

final Calendar c = Calendar.getInstance();
Year = c.get(Calendar.YEAR);
Month = c.get(Calendar.MONTH);
Day = c.get(Calendar.DAY_OF_MONTH);
// updateDisplay();

}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSubmit:
JSONObject validResponce = getValidResponce();
if (validResponce != null) {
callWsPost(REGISTER_URL, validResponce, register_responcCode)
.setCacheEnable(false);
}
break;
// case R.id.edtDateOfBirth:
// DateDialog();
// break;
// case R.id.edtGender:
// onCreateDialog();
// break;
case R.id.iconMenu:
finish();
break;
case R.id.edtDateOfBirth:
DateDialog();
break;
case R.id.edtGender:
onCreateDialog();
break;

case R.id.iconHome:
Intent mIntent = new Intent(this, HomeActivity.class);
mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mIntent);
finish();
break;
}
}

@Override
public void onResult(int mResponceCode, JSONArray mResponce) {
try {
JSONObject mJsonRegisterResponse = mResponce.getJSONObject(0);
String mRegisterStatus = mJsonRegisterResponse.getString("bStatus");
String response = mJsonRegisterResponse.getString("sMessage");
if (TextUtils.equals(mRegisterStatus, "1")) {
AlertDialogRegFailed(RegisterActivity.this, getResources()
.getString(R.string.app_name), response);
// clearPrefrenc();
// Intent mIntent = new Intent(this, LoginActivity.class);
// startActivity(mIntent);
} else {
AlertDialogRegSuccessfully(RegisterActivity.this, getResources()
.getString(R.string.app_name), response);
}
} catch (Exception e) {
e.printStackTrace();
}
}

private void clearPrefrenc() {
edtUserName.setText("");
edtFirstName.setText("");
edtLastName.setText("");
edtDateOfBirth.setText("");
edtGender.setText("");
edtStreetAddress.setText("");
edtAppartment.setText("");
edtTownCity.setText("");
edtPostCode.setText("");
edtContry.setText("");
edtEmailAddress.setText("");
edtPhoneNumber.setText("");
edtAccountPassword.setText("");
edtConfirmPassword.setText("");
edtNote.setText("");

putPref(REG_USER_NAME, "");
putPref(REG_FIRSTNAME, "");
putPref(REG_LASTNAME, "");
putPref(REG_DATE_OF_BIRTH, "");
putPref(REG_GENDER, "");
putPref(REG_STREET_ADDRESS, "");
putPref(REG_APPARTMENT, "");
putPref(REG_TOWNCITY, "");
putPref(REG_POSTAL_CODE, "");
putPref(REG_COUNTRY, "");
putPref(REG_EMAIL_ADDRESS, "");
putPref(REG_PHONE_NUMBER, "");
putPref(REG_ACCOUNT_PASSWORD, "");
putPref(REG_CONFIRM_PASSWORD, "");
putPref(REG_NOTE, "");

}

// validations
public JSONObject getValidResponce() {
String strUserName = edtUserName.getText().toString().trim();
String strFirstName = edtFirstName.getText().toString().trim();
String strLastName = edtLastName.getText().toString().trim();
String strBirthDate = edtDateOfBirth.getText().toString().trim();
String strStreetAddress = edtStreetAddress.getText().toString().trim();
String strStreetAddress2 = edtAppartment.getText().toString().trim();
String strTownCity = edtTownCity.getText().toString().trim();
String strPostCode = edtPostCode.getText().toString().trim();
String strCountry = edtContry.getText().toString().trim();
String strEmailAddress = edtEmailAddress.getText().toString().trim();
String strPhoneNumber = edtPhoneNumber.getText().toString().trim();
String strAccountPassword = edtAccountPassword.getText().toString()
.trim();
String strConfirmPassword = edtConfirmPassword.getText().toString()
.trim();
String strGender = edtGender.getText().toString().trim();
String strNote = edtNote.getText().toString().trim();

if (TextUtils.isEmpty(strUserName)) {
edtUserName.requestFocus();
edtUserName.setError("Please Enter User Name");
return null;
} else if (TextUtils.isEmpty(strFirstName)) {
edtFirstName.requestFocus();
edtFirstName.setError("Please Enter First Name");
return null;
} else if (TextUtils.isEmpty(strLastName)) {
edtLastName.requestFocus();
edtLastName.setError("Please Enter Last Name");
return null;
} else if (TextUtils.isEmpty(strStreetAddress)) {
edtStreetAddress.requestFocus();
edtStreetAddress.setError("Please Enter Address");
return null;
} else if (TextUtils.isEmpty(strTownCity)) {
edtTownCity.requestFocus();
edtTownCity.setError("Please Enter City");
return null;
} else if (TextUtils.isEmpty(strPostCode)) {
edtPostCode.requestFocus();
edtPostCode.setError("Please Enter PostCode");
return null;
} else if (TextUtils.isEmpty(strCountry)) {
edtContry.requestFocus();
edtContry.setError("Please Enter Country");
return null;
} else if (!AppUtil.isValidEmail(strEmailAddress)) {
edtEmailAddress.requestFocus();
edtEmailAddress.setError("Please Enter Valid Email Address");
return null;
} else if (TextUtils.isEmpty(strPhoneNumber)) {
edtPhoneNumber.requestFocus();
edtPhoneNumber.setError("Please Enter Phone Number");
return null;
} else if (TextUtils.isEmpty(strAccountPassword)) {
edtAccountPassword.requestFocus();
edtAccountPassword.setError("Please Enter Account Password");
return null;
} else if (edtAccountPassword.getText().toString().length() < 5) {
edtAccountPassword.requestFocus();
edtAccountPassword.setError("Password is too short");
return null;
} else if (TextUtils.isEmpty(strConfirmPassword)) {
edtConfirmPassword.requestFocus();
edtConfirmPassword.setError("Please Enter Confirm Password");
return null;
} else if (edtConfirmPassword.getText().toString().length() < 5) {
edtConfirmPassword.requestFocus();
edtConfirmPassword.setError("Password is too short");
return null;
} else if (!TextUtils.equals(strConfirmPassword, strAccountPassword)) {
edtConfirmPassword.requestFocus();
edtConfirmPassword.setError("Password does not match");
return null;
} else {
JSONObject mJsonObject = new JSONObject();
try {
mJsonObject.put("user_login", strUserName);
mJsonObject.put("user_pass", strAccountPassword);
mJsonObject.put("user_email", strEmailAddress);
mJsonObject.put("first_name", strFirstName);
mJsonObject.put("last_name", strLastName);
mJsonObject.put("billing_address_1", strStreetAddress);
mJsonObject.put("billing_city", strTownCity);
mJsonObject.put("billing_postcode", strPostCode);
mJsonObject.put("billing_country", strCountry);
mJsonObject.put("billing_phone", strPhoneNumber);
mJsonObject.put("birthdate", strBirthDate);
mJsonObject.put("gender", strGender);
mJsonObject.put("order_notes", strNote);
mJsonObject.put("billing_address_2", strStreetAddress2);
return mJsonObject;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}

// @Override
// public void onDateSet(DatePicker view, int year, int monthOfYear,int
// dayOfMonth) {
// String date = String.valueOf(dayOfMonth) + "-"
// + String.valueOf(monthOfYear + 1) + "-" + String.valueOf(year);
// edtDateOfBirth.setText(date);
// // Toast.makeText(RegisterActivity.this, date, Toast.LENGTH_LONG)
// // .show();
// }

public void onCreateDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final String[] strgender = new String[] { "Male", "Female" };
builder.setTitle("Select Gender").setItems(strgender,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
edtGender.setText(strgender[which]);
}
});
builder.create().show();
}

// Dialog for show error msg
public void AlertDialogRegFailed(Context mContext, String mStrDailogTitle,
String mStrDailogMsg) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
mContext);
// alertDialogBuilder.setTitle(Constant.LOGIN.LOGIN_FAIL_MESSAGE);
alertDialogBuilder.setMessage(mStrDailogMsg).setTitle(mStrDailogTitle)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
   clearPrefrenc();
dialog.cancel();
}
});

AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
// Dialog for show error msg
public void AlertDialogRegSuccessfully(Context mContext, String mStrDailogTitle,
String mStrDailogMsg) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
mContext);
// alertDialogBuilder.setTitle(Constant.LOGIN.LOGIN_FAIL_MESSAGE);
alertDialogBuilder.setMessage(mStrDailogMsg).setTitle(mStrDailogTitle)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Intent mIntent = new Intent(RegisterActivity.this, LoginActivity.class);
// //mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(mIntent);
dialog.cancel();
finish();
}
});

AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}


private DatePicker mdatePicker = null;
private Dialog mDialog = null;
private View mView = null;

private void DateDialog() {
mDialog = new Dialog(this);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mdatePicker = new DatePicker(this);
mdatePicker.setCalendarViewShown(false);
mView = LayoutInflater.from(this).inflate(R.layout.xdatelayout, null);
LinearLayout datedialogview = (LinearLayout) mView
.findViewById(R.id.datedialogview);
datedialogview.addView(mdatePicker);

Button btnok = (Button) mView.findViewById(R.id.btnok);
btnok.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Toast.makeText(getApplicationContext(), "OK",
// Toast.LENGTH_SHORT).show();
DateValidation();
}
});

Button btncancel = (Button) mView.findViewById(R.id.btncancel);
btncancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Toast.makeText(getApplicationContext(), "CANCEL",
// Toast.LENGTH_SHORT).show();
mDialog.dismiss();
}
});

mDialog.setContentView(mView);
InitDateSet();
mDialog.show();
}

private void InitDateSet() {
final Calendar c = Calendar.getInstance();
Year = c.get(Calendar.YEAR);
Month = c.get(Calendar.MONTH);
Day = c.get(Calendar.DAY_OF_MONTH);
mdatePicker.init(Year, Month, Day, mDatePickListener);
}

// updates the date in the TextView
@SuppressWarnings("deprecation")
private void updateDisplay() {
Date mDate = new Date();
mDate.setYear(Year - 1900);
mDate.setMonth(Month);
mDate.setDate(Day);

String selectedDate = (String) DateFormat.format("yyyy-MM-dd", mDate)
.toString();
edtDateOfBirth.setText(selectedDate);
}

private DatePicker.OnDateChangedListener mDatePickListener = new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
Year = year;
Month = monthOfYear;
Day = dayOfMonth;
}
};

/**
* 0 if the times of the two Calendars are equal, -1 if the time of this
* Calendar is before the other one, 1 if the time of this Calendar is after
* the other one.
*/
private int FirstDateCheck(int year, int month, int day) {
final Calendar CurrentDate = Calendar.getInstance();
Calendar NewDate = (Calendar) CurrentDate.clone();
NewDate.set(year, month, day);
return NewDate.compareTo(CurrentDate);
}

private void DateValidation() {
int Result = FirstDateCheck(Year, Month, Day);
if (Result == 0) {
// Toast.makeText(ServiceSetupRequest.this, "equal",
// Toast.LENGTH_SHORT).show();
updateDisplay();
mDialog.dismiss();
} else if (Result == -1) {
mDialog.dismiss();
updateDisplay();
} else if (Result == 1) {
Toast.makeText(RegisterActivity.this, "Please enter valid date",
Toast.LENGTH_SHORT).show();
// updateDisplay();
// mDialog.dismiss();
}
}

public void onFocusChange(final EditText edittext) {
edittext.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
edittext.setError(null);
}
}
});
}
}

Monday, 12 May 2014

JSonParsing Example

1) Create a class AsyncData.java
======================
package com.rws.util.ws;

import java.io.File;
import java.util.HashMap;

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

public class AsyncData {

private final PostType postType;
private final int responceCode;
private boolean progressDialog;
private JSONObject mParams = null;
private JSONArray mResonpnce = new JSONArray();

private HashMap<String, File> mFileList;

private String rootParam;

public enum PostType {
POST, GET, POST_NAME_VAL
}

public AsyncData(String BASE_URL, JSONObject mParams, int responceCode,
PostType PostType) {
this.BASE_URL = BASE_URL;
this.mParams = mParams;
this.responceCode = responceCode;
this.postType = PostType;
}

public AsyncData(PostType PostType, boolean progressDialog) {
this.postType = PostType;
this.responceCode = (int) System.currentTimeMillis();
}

public AsyncData(PostType PostType, boolean progressDialog, int responceCode) {
this.postType = PostType;
this.responceCode = responceCode;
}

private String BASE_URL = null;

public String getBASEURL() {
return BASE_URL;
}

public void setBASEURL(String bASEURL) {
BASE_URL = bASEURL;
}

public JSONObject getParams() {
return mParams;
}

public void setParams(JSONObject mParams) {
this.mParams = mParams;
}

public JSONArray getResonpnce() {
return mResonpnce;
}

public void setResonpnce(JSONArray mResonpnce) {
this.mResonpnce = mResonpnce;
}

public PostType getPostType() {
return postType;
}

public boolean isProgressDialog() {
return progressDialog;
}

public void setProgressDialog(boolean progressDialog) {
this.progressDialog = progressDialog;
}

public int getResponceCode() {
return responceCode;
}

public String getRootParam() {
return rootParam;
}

public void setRootParam(String rootParam) {
this.rootParam = rootParam;
}

public HashMap<String, File> getFileList() {
return mFileList;
}

public void addFile(String key, File mFile) {
if (mFileList == null)
mFileList = new HashMap<String, File>();
mFileList.put(key, mFile);
}

}
2) Create a class PostAndGetData.java
===========================package com.rws.util.ws;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
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.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.rws.apputil.AppUtil;
import com.rws.myavailability.R;
import com.rws.myavailability.SuperActivity;
import com.rws.util.ws.AsyncData.PostType;

public class PostAndGetData {

private final onJsonResult mJsonResult;
final SuperActivity mContext;

private ProgressDialogStack mProgressDialog;
private boolean isProgressCancelable = false;

public AsyncData[] execute(boolean showProgress, String BASE_URL,
JSONObject mParams, int responceCode, PostType mPostType) {
return execute(showProgress, new AsyncData(BASE_URL, mParams,
responceCode, mPostType));
}

ArrayList<AsyncTask<AsyncData, Float, AsyncData>> mAsyncTasks = new ArrayList<AsyncTask<AsyncData, Float, AsyncData>>();

public AsyncData[] execute(boolean isProgress, AsyncData... mAsyncDatas) {

if (AppUtil.isNetworkAvalible(mContext)) {
for (AsyncData mAsyncData : mAsyncDatas) {
mAsyncData.setProgressDialog(isProgress);
if (mAsyncData.isProgressDialog() && mContext instanceof SuperActivity) {
if (getProgressDialog() == null) {
ProgressDialogStack mProgressDialog2 = (ProgressDialogStack) mContext
.findViewById(R.id.progressBarLoading);
setProgressDialog(mProgressDialog2);
// getProgressDialog().setCancelable(
// isProgressCancelable());
}
getProgressDialog().addStack();
}

myAsyncTask = new MyAsyncTask();
mAsyncTasks.add(myAsyncTask);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
myAsyncTask.executeOnExecutor(
AsyncTask.THREAD_POOL_EXECUTOR, mAsyncData);
} else
myAsyncTask.execute(mAsyncData);
}
} else {
mContext.showHeadderMessage(mContext
.getString(R.string.network_connection_error));
}

return mAsyncDatas;
}

public boolean isAlive() {
return myAsyncTask != null
&& myAsyncTask.getStatus() != AsyncTask.Status.FINISHED
&& !myAsyncTask.isCancelled();
}

public PostAndGetData CancelAllTasks() {
for (AsyncTask<AsyncData, Float, AsyncData> mTasks : mAsyncTasks) {
if (!mTasks.isCancelled())
mTasks.cancel(true);
}
return this;
}

private MyAsyncTask myAsyncTask;

public interface onJsonResult {
public void onResult(int mResponceCode, JSONArray mResponce);

}

public PostAndGetData(Context mContext) {

this.mContext = (SuperActivity) mContext;

if (mContext instanceof onJsonResult)
this.mJsonResult = (onJsonResult) mContext;
else
this.mJsonResult = null;
}

public PostAndGetData(Context mContext, onJsonResult mJsonResult) {
this.mContext = (SuperActivity) mContext;
this.mJsonResult = mJsonResult;

}

public onJsonResult getJsonResult() {
return mJsonResult;
}

public ProgressDialogStack getProgressDialog() {

return mProgressDialog;
}

private void setProgressDialog(ProgressDialogStack mProgressDialog) {
this.mProgressDialog = mProgressDialog;
}

public boolean isProgressCancelable() {
return isProgressCancelable;
}

public void setProgressCancelable(boolean isProgressCancelable) {
this.isProgressCancelable = isProgressCancelable;
}

public class MyAsyncTask extends AsyncTask<AsyncData, Float, AsyncData> {

@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected AsyncData doInBackground(AsyncData... mAsyncDatas) {

AsyncData mAsyncData = mAsyncDatas[0];
try {

switch (mAsyncData.getPostType()) {
case GET:
return getData(mAsyncData);
case POST:
return postData(mAsyncData);
case POST_NAME_VAL:
return postDataNameValue(mAsyncData);
default:
break;
}
} catch (Exception e) {
e.printStackTrace();
}
return mAsyncDatas[0];

}

public AsyncData postDataNameValue(AsyncData mAsyncData)
throws JSONException, IOException, ClientProtocolException {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(mAsyncData.getBASEURL());
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
JSONObject params = mAsyncData.getParams();
String mRoot = mAsyncData.getRootParam();
if (TextUtils.isEmpty(mRoot)) {
@SuppressWarnings("unchecked")
Iterator<String> i = params.keys();
while (i.hasNext()) {
String key = i.next();
nameValuePairs.add(new BasicNameValuePair(key, params
.getString(key)));
}
} else {
nameValuePairs.add(new BasicNameValuePair(mAsyncData
.getRootParam(), params.toString()));
}

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String responce = EntityUtils.toString(response.getEntity());
mAsyncData.setResonpnce(toJsonArray(responce));

return mAsyncData;

}

public AsyncData postDataDemo(AsyncData mAsyncData)
throws JSONException, IOException, ClientProtocolException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost;
httppost = new HttpPost(
"http://192.168.0.136/myavailability/webservices/auth/photo_upload");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
try {
reqEntity.addPart("userid", new StringBody("1"));
reqEntity.addPart("user_type", new StringBody("freelancer"));
File file = new File(Environment.getExternalStorageDirectory()
.toString() + "/EyeCare/", "banner.jpg");
if (file.exists())
reqEntity.addPart("fileUpload", new FileBody(file));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

httppost.setEntity(reqEntity);

// httppost.setEntity(new StringEntity(getURL(mAsyncData),
// HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
String responce = EntityUtils.toString(response.getEntity());
mAsyncData.setResonpnce(toJsonArray(responce));
return mAsyncData;
}

public AsyncData postDataWithFile(AsyncData mAsyncData)
throws JSONException, IOException, ClientProtocolException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost;
httppost = new HttpPost(mAsyncData.getBASEURL());
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);

JSONObject params = mAsyncData.getParams();
@SuppressWarnings("unchecked")
Iterator<String> i = params.keys();
while (i.hasNext()) {
String key = i.next();
reqEntity.addPart(key, new StringBody(params.getString(key)));
}

HashMap<String, File> fileList = mAsyncData.getFileList();
for (String key : fileList.keySet()) {
File file = fileList.get(key);
if (file.exists())
reqEntity.addPart("fileUpload", new FileBody(file));
}
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
String responce = EntityUtils.toString(response.getEntity());
mAsyncData.setResonpnce(toJsonArray(responce));
return mAsyncData;
}

public AsyncData postData(AsyncData mAsyncData) throws JSONException,
IOException, ClientProtocolException {
if (mAsyncData.getFileList() != null) {
postDataWithFile(mAsyncData);
}
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost;
httppost = new HttpPost(mAsyncData.getBASEURL());
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded");
httppost.setEntity(new StringEntity(getURL(mAsyncData), HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
String responce = EntityUtils.toString(response.getEntity());
mAsyncData.setResonpnce(toJsonArray(responce));
return mAsyncData;
}

public AsyncData getData(AsyncData mAsyncData) throws JSONException,
IOException, ClientProtocolException {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget;
httpget = new HttpGet(getURL(mAsyncData));
httpget.setHeader("Content-Type",
"application/x-www-form-urlencoded");
HttpResponse response = httpclient.execute(httpget);
String responce = EntityUtils.toString(response.getEntity());
mAsyncData.setResonpnce(toJsonArray(responce));
return mAsyncData;
}

public JSONArray toJsonArray(String responce) throws JSONException {
JSONArray mArrayResponce = null;

JSONObject mJsonObject = null;
if (responce.trim().startsWith("{")
&& responce.trim().endsWith("}")) {
mJsonObject = new JSONObject(responce);
}

if (!responce.startsWith("[")) {
mArrayResponce = new JSONArray();
if (mJsonObject == null)
mArrayResponce.put(responce.trim());
else
mArrayResponce.put(mJsonObject);

} else {
mArrayResponce = new JSONArray(responce);
}
return mArrayResponce;
}

@Override
protected void onPostExecute(AsyncData mAsyncData) {
super.onPostExecute(mAsyncData);

if (mAsyncData.isProgressDialog()) {
getProgressDialog().popStack();
}
logResponce(mAsyncData);
if (mJsonResult != null)
mJsonResult.onResult(mAsyncData.getResponceCode(),
mAsyncData.getResonpnce());
}

@Override
protected void onProgressUpdate(Float... mAsyncDatas) {
super.onProgressUpdate(mAsyncDatas);
}
}

public void logResponce(AsyncData mAsyncData) {
Log.e("ssp-responce " + mAsyncData.getResponceCode(), ""
+ mAsyncData.getResonpnce().toString());
}

public void logURL(AsyncData mAsyncData, String url) {
Log.e("ssp-url " + mAsyncData.getResponceCode(), "" + url);
}

public String getURL(AsyncData mAsyncData)
throws UnsupportedEncodingException, JSONException {
String url = mAsyncData.getBASEURL() + "?";
JSONObject params = mAsyncData.getParams();

@SuppressWarnings("unchecked")
Iterator<String> i = params.keys();
String mRoot = mAsyncData.getRootParam();
if (TextUtils.isEmpty(mRoot)) {
while (i.hasNext()) {
String key = i.next();
url += "&" + key + "="
+ URLEncoder.encode(params.getString(key), "UTF-8");
}
} else {
url += "&" + mRoot + "="
+ URLEncoder.encode(params.toString(), "UTF-8");
}
logURL(mAsyncData, URLDecoder.decode(url, "UTF-8"));
return url;
}
}
3)Create a class ProgressDialogStack.java
=============================
package com.rws.util.ws;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ProgressBar;

public class ProgressDialogStack extends ProgressBar {

public ProgressDialogStack(Context context, AttributeSet attrs) {
super(context, attrs);
}

public ProgressDialogStack(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

public ProgressDialogStack(Context context) {
super(context);
}

private int mCount = 0;

public int stackCount() {
return mCount;
}

public void popStack() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if ((mCount -= 1) == 0)
setVisibility(View.GONE);
}
}, 500);
}

public void addStack() {
mCount += 1;
if(getVisibility() == View.GONE)
setVisibility(View.VISIBLE);
}
}
4)create a class WebServiceUrl.java
==========================

public interface WebServiceUrl {

String BASE_URL = "http://rightwaysolution.us/myavailability2/myavailability/index.php/webservices/";

String SUCCESS = "1";
String FAIL = "0";

/**
* @param email
*            user_email
*/
String FREELANCER_SEND_EXCEL = BASE_URL + "auth/freelancer_send_excel";
int FREELANCER_SEND_EXCEL_RES = 918;
}

4) call web service functions
private void profileSkill(){
Log.i("String==", strSkill);
JSONObject mJsonData = new JSONObject();
try {
mJsonData.put("userid", getPrefString("user_id"));
mJsonData.put("skills", strFullSkill);
} catch (JSONException e){
e.printStackTrace();
}
callWebService(EDIT_SKILL_URL, mJsonData, EDIT_SKILL_RES);
}

public void onResult(int mResponceCode, JSONArray mResponce) {
try {
JSONObject mJOBResponse = mResponce.getJSONObject(0);
Log.i("mJOBResponse==>", mJOBResponse.toString());
if (mJOBResponse != null) {
String strStatus = mJOBResponse.getString("status");
String strMessage = mJOBResponse.getString("message");
if (TextUtils.equals(strMessage, "success")) {
Intent mIntent = new Intent(SkillsProfileActivty.this,EditProfileActivity.class);
startActivity(mIntent);
} else {
showHeadderMessage(strMessage, Color.RED);
}
}
} catch (JSONException e) {
}
}

5)Login.java
=======
package com.rws.login;

import java.util.Iterator;

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

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.widget.TextView;

import com.rws.apputil.AppUtil;
import com.rws.custom.EditTextCancelable;
import com.rws.myavailability.R;
import com.rws.myavailability.SuperActivity;
import com.rws.profile.NewProfileActivity;
import com.rws.util.ws.PostAndGetData.onJsonResult;

public class LoginActivity extends SuperActivity implements onJsonResult {
private TextView txtForgotPassword, txtDummyText;
private EditTextCancelable etxtEmail, etxtPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.m_login_activity);
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setHeadderTitle(getRstring(R.string.log_in));

txtForgotPassword = (TextView) findViewById(R.id.txtForgotPassword);
txtForgotPassword.setOnClickListener(this);
txtForgotPassword.setTypeface(getFontProxNovaLight());
txtDummyText = (TextView) findViewById(R.id.txtdummyText);
txtDummyText.setTypeface(getFontProxNovaLight());

imgFwd.setVisibility(View.VISIBLE);
imgBack.setVisibility(View.VISIBLE);

etxtEmail = (EditTextCancelable) findViewById(R.id.etxtEmail);
etxtEmail.setText("jagruti.gajjar@rightwaysolution.com");
etxtPassword = (EditTextCancelable) findViewById(R.id.etxtPassword);
etxtPassword.setText("123456");
etxtPassword.setOnKeyListener(new OnKeyListener() {

@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
setData();
return true;
}
return false;
}
});
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iconLeft:
this.finish();
overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_out_right);
// finish();
break;
case R.id.iconRight:
// Login
setData();
break;
case R.id.txtForgotPassword:
if (AppUtil.isNetworkAvalible(this)){
Intent mIntent = new Intent(this, ForgotPasswordActivity.class);
startActivity(mIntent);
}else{
showHeadderMessage(getResources().getString(R.string.check_your_internet_connection), getResources().getColor(R.color.red));
}
break;
default:
break;
}
}

@Override
public void onResult(int mResponceCode, JSONArray mResponce) {
try {
JSONObject mJOBLoginResponse = mResponce.getJSONObject(0);
if (mJOBLoginResponse != null) {
String strStatus = mJOBLoginResponse.getString("status");
String strMessage = mJOBLoginResponse.getString("message");
if (TextUtils.equals(strStatus, "1")) {
JSONObject mJOBUserData = mJOBLoginResponse
.getJSONObject("user_data");
JSONArray mArraySkill = mJOBUserData.getJSONArray("skills");
System.out.println("");

Iterator<?> keys = mJOBUserData.keys();

while (keys.hasNext()) {
String key = (String) keys.next();
putPref(key, mJOBUserData.getString(key));
}

Intent mIntent = new Intent(this, NewProfileActivity.class);
startActivity(mIntent);
finish();

} else {
// clearData();
showHeadderMessage(strMessage, Color.RED);
}
}
} catch (JSONException e) {

}
}

// validations
private boolean isValidDetails() {
if (etxtEmail.getText().toString().equals("")) {
etxtEmail.requestFocus();
showHeadderMessage(getString(R.string.please_enter_email));
return false;
} else if (!etxtEmail.isValidEmail()) {
showHeadderMessage(getString(R.string.enter_valid_email));
return false;
}
if (etxtPassword.getText().toString().equals("")) {
etxtPassword.requestFocus();
showHeadderMessage(getString(R.string.please_enter_password));
return false;
}
return true;
}

// For clear editFields
public void clearData() {
etxtEmail.setText("");
etxtPassword.setText("");
}

public void setData() {
if (isValidDetails()) {
JSONObject mJsonData = new JSONObject();
try {
mJsonData.put("email", etxtEmail.getText().toString().trim());
mJsonData.put("password", etxtPassword.getText().toString().trim());
} catch (Exception e) {
e.printStackTrace();
}
callWebService(LOGIN_URL, mJsonData, LOGIN_URL_RES);
}
}
}

6)SuperActivity.java
=============
package com.rws.myavailability;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.rws.util.ws.AsyncData;
import com.rws.util.ws.AsyncData.PostType;
import com.rws.util.ws.PostAndGetData;
import com.rws.util.ws.WebServiceUrl;

public class SuperActivity extends FragmentActivity implements OnClickListener,
WebServiceUrl {
private SharedPreferences preferences;
public TextView txtHeaderTitle, textRight;
private String title = "";
public ImageView imgBack, imgFwd;
public ImageView imgProfilePic;
public boolean isHeadderMsgShowing;
public TextView errorText;
private ErrMsgRunnable mErrRunnable;
private int color;
private boolean animateFinshAct;
private boolean animateStartAct;
public RelativeLayout mHeadderLayout;

@SuppressLint("InlinedApi")
@Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
color = getResources().getColor(R.color.errRed);

preferences = getSharedPreferences("AppPref",
Context.MODE_MULTI_PROCESS);

txtHeaderTitle = (TextView) findViewById(R.id.headderTitle);
txtHeaderTitle.setTypeface(getFontProxNovaBold());
txtHeaderTitle.setText(getTitle());
imgBack = (ImageView) findViewById(R.id.iconLeft);
imgBack.setOnClickListener(this);
imgFwd = (ImageView) findViewById(R.id.iconRight);
imgFwd.setOnClickListener(this);
textRight = (TextView) findViewById(R.id.textRight);
textRight.setOnClickListener(this);
errorText = (TextView) findViewById(R.id.errorMessage);
errorText.bringToFront();
errorText.requestLayout();
errorText.invalidate();

mHeadderLayout = (RelativeLayout) findViewById(R.id.headder);
mHeadderLayout.bringToFront();
mHeadderLayout.invalidate();
}

public void startActivity(Intent intent, boolean animate) {
animateStartAct = animate;
startActivity(intent);
this.animateFinshAct = true;
}

@Override
public void startActivity(Intent intent) {
super.startActivity(intent);
if (animateStartAct)
overridePendingTransition(R.anim.slide_in_right,
R.anim.slide_out_left);
}

public void finish(boolean animate) {
this.animateFinshAct = animate;
finish();
this.animateFinshAct = true;
}

@Override
public void finish() {
super.finish();
if (animateFinshAct)
overridePendingTransition(R.anim.slide_in_right,
R.anim.slide_out_left);
}

public void showHeadderMessage(String message) {
showHeadderMessage(message, color);
}

public void toast(String mString) {
Toast.makeText(this, mString, Toast.LENGTH_SHORT).show();
}

public void showHeadderMessage(String messae, int color) {
this.color = color;
if (isHeadderMsgShowing) {
mErrRunnable.closeErr();
}
isHeadderMsgShowing = true;
errorText.setText(messae);
errorText.setBackgroundColor(color);
errorText.animate().translationY(errorText.getHeight());
mErrRunnable = new ErrMsgRunnable();
errorText.postDelayed(mErrRunnable, 2000);
}

public class ErrMsgRunnable implements Runnable {
public boolean close = false;

public void closeErr() {
close = true;
errorText.animate().translationY(-errorText.getHeight());
isHeadderMsgShowing = false;
}

@Override
public void run() {
if (!close) {
closeErr();
}
}
}

public Typeface getFontProxNovaLight() {
return Typeface.createFromAsset(getAssets(),
"fonts/ProximaNova-Light.otf");
}

public Typeface getFontProxNovaRegular() {
return Typeface.createFromAsset(getAssets(),
"fonts/ProximaNova-Regular.otf");
}

public Typeface getFontProxNovaBold() {
return Typeface.createFromAsset(getAssets(),
"fonts/ProximaNova-Bold.otf");
}

public Typeface getFontProxNovaSemibold() {
return Typeface.createFromAsset(getAssets(),
"fonts/ProximaNova-Semibold.otf");
}

public void callWebService(String url, JSONObject mJsonData, int respncecode) {
AsyncData mAsyncData = new AsyncData(PostType.POST, true, respncecode);
PostAndGetData mAndGetData = new PostAndGetData(this);
mAsyncData.setBASEURL(url);
mAsyncData.setParams(mJsonData);
mAsyncData.setRootParam("webdata");
mAndGetData.execute(true, mAsyncData);
}

public void putPref(String KEY, String VAL) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(KEY, VAL);
editor.commit();
}

public void putPref(String KEY, int VAL) {
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(KEY, VAL);
editor.commit();
}

public void putPref(String KEY, boolean VAL) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(KEY, VAL);
editor.commit();
}

public String getPrefString(String KEY) {
return preferences.getString(KEY, "");
}

public int getPrefInt(String KEY) {
return preferences.getInt(KEY, 0);
}

public boolean getPrefBoolean(String KEY) {
return preferences.getBoolean(KEY, false);
}

@Override
public void onClick(View v) {

}

public String getHeadderTitle() {
return title;
}

public void setHeadderTitle(String title) {
this.title = title;
if (txtHeaderTitle != null)
txtHeaderTitle.setTypeface(getFontProxNovaBold());
txtHeaderTitle.setText(getHeadderTitle());
}

public String getRstring(int id) {
return getResources().getString(id);
}
}



Sunday, 11 May 2014

Get category id

private String GetCategory(){
String category_id="";
OpenDatabase();
Cursor c = mDbHelper.GetSelectedCategoryList(mSQLiteDatabase, 1);
if(c!=null){
    if(c.getCount() > 0){
    c.moveToFirst();
    int i=0;
while(c.isAfterLast() == false){
if(i==0){
category_id="" +c.getInt(0);
}
else{
category_id=category_id+","+c.getInt(0);
}

if(i==c.getCount()-1){
category_id=category_id + "";
}
i++;
c.moveToNext();
};
    }
    c.close();
}
CloseDataBase();
return category_id;
}