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

Friday, 25 April 2014

GCM push Notification good link

use this link : http://fundroiding.wordpress.com/2012/06/29/google-cloud-messaging-for-android-gcm-simple-tutorial/

Google Cloud Messaging For Android (GCM) Simple Tutorial

Important: C2DM has been officially deprecated as of June 26, 2012.
It has been replaced by Google Cloud Messaging For Android (GCM)
This Tutorial will guide you how to create a sample simple application using the GCM functionality,
This demo will help you registering and unRegistering android device from GCM server
Getting your Sender ID
  • STEP 1.  Register Here .
  • STEP 2.  Click Create project. Your browser URL will change to something like:
    " https://code.google.com/apis/console/#project:4815162342 "
    Take note of the value after#project: (4815162342 in this example). This is your project ID, and it will be used later on as the GCM sender ID. This Id will be used by the Android Device while Registering for Push Notification.
  • STEP 3. Choose Service tab from the left side menu on the web page. and turn on ” Google Cloud Messaging for Android “
  • STEP 4. Go to API Access tab from the left menu of web page.
press Create new Server key and note down the generated key

CREATING APP FOR GCM
  1. Update ADT plugin 20 .
  2. update SDK > install Extras > Google Cloud Messaging for Android Library.
  3. Add gcm.jar to libs folder.(will be in the  android_sdk/extras/google/gcm after updating ADT and SDK)
  • STEP 5. Create A new Project in Android with the following specifications
Android Version 2.2
Package   =  com.sagar.gcma
Main Activity  =  PushAndroidActivity
  • Source Code for PushAndroidActivity.java:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.sagar.gcma;
import static com.sagar.gcma.CommonUtilities.SENDER_ID;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gcm.GCMRegistrar;
public class PushAndroidActivity extends Activity {
private String TAG = "** pushAndroidActivity **";
private TextView mDisplay;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkNotNull(SENDER_ID, "SENDER_ID");
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
setContentView(R.layout.main);
mDisplay = (TextView) findViewById(R.id.display);
final String regId = GCMRegistrar.getRegistrationId(this);
Log.i(TAG, "registration id =====  "+regId);
if (regId.equals("")) {
GCMRegistrar.register(this, SENDER_ID);
} else {
Log.v(TAG, "Already registered");
}
mDisplay.setText("ffffff        "+regId);
}
private void checkNotNull(Object reference, String name) {
if (reference == null) {
throw new NullPointerException(
getString(R.string.error_config, name));
}
}
@Override
protected void onPause() {
super.onPause();
GCMRegistrar.unregister(this);
}
}

  • Source code for GCMIntentService.java :
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.sagar.gcma;
import android.app.Notification; import android.app.Notification.Builder; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.util.Log; import com.google.android.gcm.GCMBaseIntentService; public class GCMIntentService extends GCMBaseIntentService { public static final String GCM_SENDER_ID = "378946919077"; public GCMIntentService() { super(GCM_SENDER_ID); } @SuppressWarnings("deprecation") @Override protected void onMessage(Context context, Intent intent) { try { final Bundle bundle = intent.getExtras(); String message = bundle.getString("message"); Log.i(TAG, "message: " + message); // MainActivity mainActivity = MainActivity.getMainActivity(); // if (mainActivity != null) { // mainActivity.onPushMessage(message); // clearPushMessage(); // } else // Intent notificationIntent = new Intent(this, MyClass.class); // PendingIntent contentIntent = PendingIntent.getActivity(this, 0, // notificationIntent, 0); Intent mIntent = new Intent(context, LoginActivity.class); mIntent.putExtra("pushmessage", message); mIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); final PendingIntent contentIntent = PendingIntent.getActivity( context, (int) System.currentTimeMillis(), mIntent, 0); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { setPushMessage(message); final Notification notification = new Notification(); final Object systemService = context .getSystemService(Context.NOTIFICATION_SERVICE); final NotificationManager notificationMgr = (NotificationManager) systemService; notification.flags |= Notification.FLAG_AUTO_CANCEL; // notification.defaults |= Notification.DEFAULT_SOUND; notification.defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE; notification.vibrate = new long[] { 0, 100, 200, 300 }; notification.contentIntent = contentIntent; notification.icon = R.drawable.ic_launcher; notification.tickerText = context.getString(R.string.app_name); String appName = context.getResources().getString( R.string.app_name); notification.setLatestEventInfo(this, appName, message, contentIntent); // notification.setLatestEventInfo(context, contentTitle, // contentText, contentIntent); int ss = (int) System.currentTimeMillis(); notificationMgr.notify(ss, notification); } else { NotificationManager m_notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Builder m_builder = new Notification.Builder(this); m_builder .setContentTitle(context.getString(R.string.app_name)) .setContentText(message) .setSmallIcon(R.drawable.ic_launcher) .setContentIntent(contentIntent) .setAutoCancel(true) .setVibrate(new long[] { 0, 100, 200, 300 }) .setDefaults( Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE); String appName = context.getResources().getString( R.string.app_name); Notification m_notification = new Notification.BigTextStyle( m_builder).bigText(message).build(); m_notification.setLatestEventInfo(this, appName, message, contentIntent); int ss = (int) System.currentTimeMillis(); m_notificationManager.notify(ss, m_notification); } } catch (Exception e) { e.printStackTrace(); } } private void setPushMessage(String message) { final SharedPreferences mSharedPreferences = getSharedPreferences( "PushNotification", 0); final SharedPreferences.Editor mEditor = mSharedPreferences.edit(); mEditor.putString("message", message); mEditor.commit(); } public void clearPushMessage() { final SharedPreferences mSharedPreferences = getSharedPreferences( "PushNotification", 0); final SharedPreferences.Editor mEditor = mSharedPreferences.edit(); mEditor.putString("message", null); mEditor.commit(); } private static final String TAG = "GCMIntentService"; @Override protected void onRegistered(Context arg0, String registrationId) { Log.i(TAG, "Device registered: regId = " + registrationId); } @Override protected void onUnregistered(Context arg0, String arg1) { Log.i(TAG, "unregistered = " + arg1); } @Override protected void onError(Context arg0, String errorId) { Log.i(TAG, "Received error: " + errorId); } @Override protected boolean onRecoverableError(Context context, String errorId) { return super.onRecoverableError(context, errorId); } }

  • Source Code for CommonUtilities.java
?
1
2
3
4
5
6
7
package com.sagar.gcma;
public final class CommonUtilities {
static final String SENDER_ID = "515850168860";
}
  • Source Code for AndroidManifest.xml
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?xml version="1.0" encoding="utf-8"?>
package="com.sagar.gcma"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<permission
android:name="com.sagar.gcma.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.sagar.gcma.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".PushAndroidActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.sagar.gcma" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
</application>
</manifest>

  • SourceCode of main.xml
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre>
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/display"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#ffffff" />
</ScrollView>
<pre>
Package explorer ScreenShot
Logcat ScreenShot
Important links: