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