Thursday 14 November 2013

JsonParsing

1)create a class Login.java
==================
package com.example.jsonpasrsing;

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

import com.example.jsonpasrsing.PostAndGetData.onJsonResult;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.provider.SyncStateContract.Constants;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class LoginActivity extends AppPrefs implements onJsonResult,
OnClickListener {
private Button btnSignUpNow = null;
private ImageView imgLogin;
private LinearLayout lytForgotPassword;
private EditText edtUserName, edtPassword;
private String regId;
private PostAndGetData mAndGetData;
private AppUtil mAppUtil;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
mAppUtil = AppUtil.getInstance();
// regId = GCMRegistrar.getRegistrationId(this);
//
// if (regId.equals("")) {
// GCMRegistrar.register(this, GCM_SENDER_ID);
// }

btnSignUpNow = (Button) findViewById(R.id.btnSignUpNow);
btnSignUpNow.setOnClickListener(this);

imgLogin = (ImageView) findViewById(R.id.imgLogin);
imgLogin.setOnClickListener(this);

lytForgotPassword = (LinearLayout) findViewById(R.id.lytForgotPassword);
lytForgotPassword.setOnClickListener(this);

edtUserName = (EditText) findViewById(R.id.edtUserName);
edtUserName.setText("");
observeText(edtUserName);
edtPassword = (EditText) findViewById(R.id.edtPassword);
edtPassword.setText("");
observeText(edtPassword);

edtUserName.setText("");
edtPassword.setText("");
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imgLogin:
if (isValidDetails()) {
mAndGetData = new PostAndGetData(this);
String strURL = getResources().getString(R.string.login_url);
JSONObject mJsonData = new JSONObject();

try {
String mDeviceToken = GCMRegistrar
.getRegistrationId(LoginActivity.this);
mJsonData.put(Constants.LOGIN.USER_NAME, edtUserName
.getText().toString());
mJsonData.put(Constants.LOGIN.PASSWORD, edtPassword
.getText().toString().trim());
mJsonData.put(Constants.LOGIN.DEVICE_ID, mDeviceToken);
} catch (Exception e) {
e.printStackTrace();
}
AsyncData mAsyncData = new AsyncData(PostType.POST, true);
mAsyncData.setBASEURL(strURL);
mAsyncData.setParams(mJsonData);
mAsyncData.setRootParam("webdata");
mAndGetData.execute(true, mAsyncData,mAsyncData);
}
break;
default:
break;
}
}

private boolean isValidDetails() {
if (edtUserName.getText().toString().equals("")) {
edtUserName.requestFocus();
edtUserName.setError("Please Enter User Name");
return false;
} else if (edtPassword.getText().toString().equals("")) {
edtPassword.requestFocus();
edtPassword.setError("Please Enter Valid Password");
return false;
}
return true;
}

public void clearData() {
edtUserName.setText("");
edtPassword.setText("");
}

private void storeInSharedPreference(JSONObject mLoginUserData)
throws JSONException {
SharedPreferences mSharedPreferences = getSharedPreferences(
Constants.SHAREDPREFERENCE.SHAREDPREFERENCES, 0);
SharedPreferences.Editor mEditor = mSharedPreferences.edit();
mEditor.putString(Constants.LOGIN.ID,
mLoginUserData.getString(Constants.LOGIN.ID));
mEditor.putString(Constants.LOGIN.USERNAME,
mLoginUserData.getString(Constants.LOGIN.USERNAME));
mEditor.putString(Constants.LOGIN.EMAIL,
mLoginUserData.getString(Constants.LOGIN.EMAIL));
mEditor.putString(Constants.LOGIN.PASSWORD_RESPONSE,
mLoginUserData.getString(Constants.LOGIN.PASSWORD_RESPONSE));
mEditor.putString(Constants.LOGIN.NAME,
mLoginUserData.getString(Constants.LOGIN.NAME));
mEditor.putString(Constants.LOGIN.PHONE_NO,
mLoginUserData.getString(Constants.LOGIN.PHONE_NO));
mEditor.putString(Constants.LOGIN.DEVICE_KEY,
mLoginUserData.getString(Constants.LOGIN.DEVICE_KEY));
mEditor.putString(Constants.LOGIN.LATITUDE,
mLoginUserData.getString(Constants.LOGIN.LATITUDE));
mEditor.putString(Constants.LOGIN.LONGITUDE,
mLoginUserData.getString(Constants.LOGIN.LONGITUDE));
mEditor.putString(Constants.LOGIN.CREATED_DATE,
mLoginUserData.getString(Constants.LOGIN.CREATED_DATE));
mEditor.putString(Constants.LOGIN.LAST_UPDATED_DATE,
mLoginUserData.getString(Constants.LOGIN.LAST_UPDATED_DATE));
mEditor.commit();
}

@Override
public void onResult(int mResponceCode, JSONArray mResponce) {
try {
JSONObject mJsonLoginResponse = mResponce.getJSONObject(0);
String mLoginStatus = mJsonLoginResponse
.getString(Constants.LOGIN.STATUS);
String strLoginMessage = mJsonLoginResponse
.getString(Constants.LOGIN.MESSAGE);

System.out.println("strLoginSuccess==" + strLoginMessage);

if (mLoginStatus.equalsIgnoreCase(Constants.LOGIN.SUCCESS)) {
JSONArray mJsonArray = mJsonLoginResponse
.getJSONArray("LoginUserData");
JSONObject mjobjLoginUSerData = mJsonArray.getJSONObject(0);
storeInSharedPreference(mjobjLoginUSerData);
// Toast.makeText(LoginActivity.this,
// strLoginMessage.toString(),
// Toast.LENGTH_LONG).show();
Intent mIntent = new Intent(LoginActivity.this,ConnectActivity.class);
startActivity(mIntent);
clearData();
} else {
mAppUtil.ShowAlertDialog(LoginActivity.this,"AppName", "LoginFail");
}

} catch (JSONException e) {
e.printStackTrace();
}
}
}
2)create another class PostandGetData.java
==============================
package com.example.jsonpasrsing;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
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.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 com.example.jsonpasrsing.AsyncData.PostType;

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

public class PostAndGetData {

private final onJsonResult mJsonResult;
final Context 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> mAsyncTasks = new ArrayList>();

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

if (AppUtil.isNetworkAvalible(mContext)) {
for (AsyncData mAsyncData : mAsyncDatas) {
mAsyncData.setProgressDialog(isProgress);
if (mAsyncData.isProgressDialog()) {
if (getProgressDialog() == null) {
setProgressDialog(new ProgressDialogStack(mContext));
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 {
AppUtil mAppUtil = AppUtil.getInstance();
mAppUtil.showAlertDialog(mContext,"Net work connection");
}

return mAsyncDatas;
}

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

public PostAndGetData cancleAllTasks() {
for (AsyncTask 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 = mContext;

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

public PostAndGetData(Context mContext, onJsonResult mJsonResult) {
this.mContext = 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 {

@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 nameValuePairs = new ArrayList(2);
JSONObject params = mAsyncData.getParams();
String mRoot = mAsyncData.getRootParam();
if (TextUtils.isEmpty(mRoot)) {
@SuppressWarnings("unchecked")
Iterator 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 postData(AsyncData mAsyncData) throws JSONException,
IOException, ClientProtocolException {
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 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 class AsyncData.java
=======================
package com.example.jsonpasrsing;

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

}
4)AppUtil.java
=============
package com.example.jsonpasrsing;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

public class AppUtil {
private ConnectivityManager connectivity = null;
private NetworkInfo netinfo = null;
private AlertDialog alertDialog;

private AppUtil(){
}
static AppUtil mAppUtil = null;

public static synchronized AppUtil getInstance() {
if (mAppUtil == null)
return new AppUtil();
return mAppUtil;
}

public static boolean isNetworkAvalible(Context p_context) {
ConnectivityManager _connectivityManager = (ConnectivityManager) p_context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo _networkInfo = _connectivityManager.getActiveNetworkInfo();
return _networkInfo != null;
}

/**
* This method use for check Network Connectivity
*/
public boolean CheckNetwork(Context mContext) {
this.connectivity = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
this.netinfo = connectivity.getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnected() == true) {
return true;
} else {
Toast.makeText(mContext, "Network not available",
Toast.LENGTH_LONG).show();
return false;
}
}

/**
* This method use for check Network Connectivity No Message
*/
public boolean CheckNetworkNoMessage(Context mContext) {
this.connectivity = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
this.netinfo = connectivity.getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnected() == true) {
return true;
} else {
return false;
}
}

// ************************************************************************************************************************
/**
* This method use for email validation check
*/
public static boolean isEmailValid(String email) {
int lastDotIndex = 0;

String regExpn = "[A-Z0-9a-z][A-Z0-9a-z._%+-]*@[A-Za-z0-9][A-Za-z0-9.-]*\\.[A-Za-z]{2,6}";

CharSequence inputStr = email;

Pattern pattern = Pattern.compile(regExpn, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);

if (matcher.matches()) {

lastDotIndex = email.lastIndexOf(".");
String substr = email.substring(lastDotIndex, email.length());

String[] domains = { ".aero", ".asia", ".biz", ".cat", ".com",
".coop", ".edu", ".gov", ".info", ".int", ".jobs", ".mil",
".mobi", ".museum", ".name", ".net", ".org", ".pro",
".tel", ".travel", ".ac", ".ad", ".ae", ".af", ".ag",
".ai", ".al", ".am", ".an", ".ao", ".aq", ".ar", ".as",
".at", ".au", ".aw", ".ax", ".az", ".ba", ".bb", ".bd",
".be", ".bf", ".bg", ".bh", ".bi", ".bj", ".bm", ".bn",
".bo", ".br", ".bs", ".bt", ".bv", ".bw", ".by", ".bz",
".ca", ".cc", ".cd", ".cf", ".cg", ".ch", ".ci", ".ck",
".cl", ".cm", ".cn", ".co", ".cr", ".cu", ".cv", ".cx",
".cy", ".cz", ".de", ".dj", ".dk", ".dm", ".do", ".dz",
".ec", ".ee", ".eg", ".er", ".es", ".et", ".eu", ".fi",
".fj", ".fk", ".fm", ".fo", ".fr", ".ga", ".gb", ".gd",
".ge", ".gf", ".gg", ".gh", ".gi", ".gl", ".gm", ".gn",
".gp", ".gq", ".gr", ".gs", ".gt", ".gu", ".gw", ".gy",
".hk", ".hm", ".hn", ".hr", ".ht", ".hu", ".id", ".ie",
" No", ".il", ".im", ".in", ".io", ".iq", ".ir", ".is",
".it", ".je", ".jm", ".jo", ".jp", ".ke", ".kg", ".kh",
".ki", ".km", ".kn", ".kp", ".kr", ".kw", ".ky", ".kz",
".la", ".lb", ".lc", ".li", ".lk", ".lr", ".ls", ".lt",
".lu", ".lv", ".ly", ".ma", ".mc", ".md", ".me", ".mg",
".mh", ".mk", ".ml", ".mm", ".mn", ".mo", ".mp", ".mq",
".mr", ".ms", ".mt", ".mu", ".mv", ".mw", ".mx", ".my",
".mz", ".na", ".nc", ".ne", ".nf", ".ng", ".ni", ".nl",
".no", ".np", ".nr", ".nu", ".nz", ".om", ".pa", ".pe",
".pf", ".pg", ".ph", ".pk", ".pl", ".pm", ".pn", ".pr",
".ps", ".pt", ".pw", ".py", ".qa", ".re", ".ro", ".rs",
".ru", ".rw", ".sa", ".sb", ".sc", ".sd", ".se", ".sg",
".sh", ".si", ".sj", ".sk", ".sl", ".sm", ".sn", ".so",
".sr", ".st", ".su", ".sv", ".sy", ".sz", ".tc", ".td",
".tf", ".tg", ".th", ".tj", ".tk", ".tl", ".tm", ".tn",
".to", ".tp", ".tr", ".tt", ".tv", ".tw", ".tz", ".ua",
".ug", ".uk", ".us", ".uy", ".uz", ".va", ".vc", ".ve",
".vg", ".vi", ".vn", ".vu", ".wf", ".ws", ".ye", ".yt",
".za", ".zm", ".zw" };

for (int i = 0; i < domains.length; i++) {
if (substr.trim().equals(domains[i])) {
return true;
}
}
}
return false;
}

/** This function use for check service running or not */
public static boolean IsServiceRunning(Context context, String package_class) {
ActivityManager manager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager
.getRunningServices(Integer.MAX_VALUE)) {
if (package_class.equals(service.service.getClassName())) {
return true;
}
}
return false;
}

public void showAlertDialog(Context mContext, String mStrDailogMsg) {
ShowAlertDialog(mContext,
mContext.getResources().getString(R.string.app_name),
mStrDailogMsg);
}
public void ShowAlertDialog(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) {
dialog.cancel();
}
});
alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}

5)ProgressDialogStack.java
===================
package com.example.jsonpasrsing;

import android.app.ProgressDialog;
import android.content.Context;

public class ProgressDialogStack extends ProgressDialog {

private int mCount = 0;

public ProgressDialogStack(Context context, int theme) {
super(context, theme);
setIcon(R.drawable.app_logo);
setTitle(context.getResources().getString(R.string.app_name));
setMessage("Please Wait...");

}

public ProgressDialogStack(Context context) {
super(context);
setIcon(R.drawable.app_logo);
setTitle(context.getResources().getString(R.string.app_name));
setMessage("Please Wait...");
}

public int stackCount() {
return mCount;
}

public void popStack() {
if ((mCount -= 1) == 0)
dismiss();
}

public void addStack() {
this.mCount += 1;
if (!isShowing())
show();
}

}
6)Constants.java
==============
package com.example.jsonpasrsing;

public class Constants {
public static String TAG = "AppNAme";
public static final String NETWORK_NOT_AVAILABLE = "Network not available";
public final static String SERVERCONNERROR = "Could not connect to server, Please try again";
public final static String LOCATION_NOT_AVAILABLE = "Location Not Available";
public final static String DIALOG_TITLE = "TravelSafe";
public static final class SHAREDPREFERENCE {
public static final String SHAREDPREFERENCES = "AppNAme";
public static final String SHAREDPREFERENCES_CONTACTS = "TravelSafeContacts";
public final static String DEVICE_ID = "device_id";
}

public static final class LOGIN {
public static final String USER_NAME = "sUsername";
public static final String PASSWORD = "sPassword";
public static final String DEVICE_ID = "sDeviceID";
// public static final String BLANK_FIELD_MSG = "Please enter UserName and Password";
public static final String LOGIN_FAILD_MSG = "Please enter valid username and password";

// Response
public static final String MESSAGE = "Message";
public static final String STATUS = "Status";
public static final String SUCCESS = "Success";
public static final String LOGIN_USER_DATA = "LoginUSerData";
public static final String ID = "id";
public static final String USERNAME = "username";
public static final String EMAIL = "email";
public static final String PASSWORD_RESPONSE = "password";
public static final String NAME = "name";
public static final String PHONE_NO = "phone_no";
public static final String DEVICE_KEY = "device_key";
public static final String LATITUDE = "latitude";
public static final String LONGITUDE = "longitude";
public static final String CREATED_DATE = "created_date";
public static final String LAST_UPDATED_DATE = "last_updated_date";
}

public static final class JSON {
public static final String TYPE = "type";
public static final String OK = "ok";
}

public static final class PROGRESSBAR {
public static final String LOADING = "Loading";
}

public static final class REJECT {
public static final String MESSAGE = "Does not want to follow you";
public static final String NO_USERNAME_MESSAGE = "There is no user name as";
}

public static final class ACCEPT {
public static final String MESSAGE = "want to follow you";
public static final String WAIT_MESSAGE = "Wait while we ask prmission from";
}
}
7)AppPrefs.java
=============
package com.example.jsonpasrsing;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;

public class AppPrefs extends AppSafePrefAct {

@Override
protected void onPause() {
if (isLaunchAsMain()) {
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString("lastActivity", getClass().getName());
Bundle mBundle = getIntent().getExtras();
if (mBundle != null)editor.putString("oldBundle", mBundle.toString());
editor.commit();
}
super.onPause();
}

public boolean isLaunchAsMain() {
return launchAsMain;
}

public void setLaunchAsMain(boolean launchAsMain){
this.launchAsMain = launchAsMain;
}

private boolean launchAsMain = true;

}
8)AppSafePrefAct.java
================
package com.example.jsonpasrsing;

import android.app.Activity;
import android.content.SharedPreferences;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public class AppSafePrefAct extends Activity {

public String getUserId() {
SharedPreferences mSPreferences = getSharedPreferences(
Constants.SHAREDPREFERENCE.SHAREDPREFERENCES, 0);
return mSPreferences.getString(Constants.LOGIN.ID, "");
}

public String getUserName() {
SharedPreferences mSPreferences = getSharedPreferences(
Constants.SHAREDPREFERENCE.SHAREDPREFERENCES, 0);
return mSPreferences.getString(Constants.LOGIN.NAME, "");
}

public String getUserEmail() {
SharedPreferences mSPreferences = getSharedPreferences(
Constants.SHAREDPREFERENCE.SHAREDPREFERENCES, 0);
return mSPreferences.getString(Constants.LOGIN.EMAIL, "");
}
public void observeText(final EditText editText){
editText.addTextChangedListener(new TextWatcher() {
       @Override
       public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (!editText.getText().toString().equals("")) {
    editText.setError(null);
        }
       }
       @Override
       public void beforeTextChanged(CharSequence s, int start, int count, int after) {
       }
       @Override
       public void afterTextChanged(Editable s) {
       
       }
   });
}
}

No comments:

Post a Comment