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