Saturday, November 28, 2015

Android JSON Parser

Android JSON Parser

 

JSON Parser or how do we parse JSON string from web services, for who never know what is JSON string is look like here you can see the example :

[{
    "CreatedBy":2147483647,
    "CreatedDate":"\/Date(928124400000+0700)\/",
    "Employee_Id":2147483647,
    "UpdatedBy":2147483647,
    "UpdatedDate":"\/Date(928124400000+0700)\/",
    "datBirdthDate":"\/Date(928124400000+0700)\/",
    "datJointDate":"\/Date(928124400000+0700)\/",
    "datResignDate":"\/Date(928124400000+0700)\/",
    "intLevel":2147483647,
    "strDepartmentCode":"String content",
    "strDepartmentName":"String content",
    "strDivisionCode":"String content",
    "strDivisionName":"String content",
    "strEmail_Address":"String content",
    "strEmplName":"String content",
    "strPhoneExt":"String content",
    "strSAP_Code":"String content",
    "strSMFNumber":"String content",
    "strSectionCode":"String content",
    "strSectionName":"String content",
    "strSex":"String content",
    "strShiftCode":"String content",
    "strStatus":"String content"
}]

We can test some webservices that available in the internet by call the webservices with the parameter by typing webservices in browser address bar

For example :




In the example above I call “http://localhost/Login.svc/Section/400P”
Login.svc as the service and Section as webservice operation then 400P as the parameter
The JSON string as the result.

Okay let’s we call it every body now know what is JSON string look like , now let’s back to the Android JSON parser client I use client cause the android application will consume these JSON string for the application. And we will discuss how to parse the JSON string in android as the client of webservices.

And this is it for the procedure

public static String getJSON(String url)  {
 String json = “”;
   StringBuilder sb=new StringBuilder();
    JSONObject jObj= new JSONObject();
    int cp;
    try {
        URL requestUrl=new URL(url);
        URLConnection con = requestUrl.openConnection();
        BufferedReader in = new BufferedReader(new  InputStreamReader(con.getInputStream()));
        while((cp=in.read())!=-1){
            sb.append((char)cp);
            json=sb.toString();
          //  jObj = new JSONObject(json);
        }
    }
        catch(Exception e){
            e.printStackTrace();
        }
return json;
}

In getJSON procedure I pass String url as the url of webservice 

Url: “http://localhost/Login.svc/Section/400P”

getJSON() use String as return the JSON string that we will use it with JSONObject or JSONArray it’s based on webservice JSON return.

For JSONObject we can use the JSON string like this:

JSONObject jObj;
try {
    jObj = new JSONObject(json);
catch (JSONException e) {
    Log.e("JSON Parser""Error parsing data " + e.toString());
}

and for JSONArray we can use it like this:

JSONArray jsonArray;
try {
    jsonArray = new JSONArray(json);
catch (JSONException e) {
    Log.e("JSON Parser""Error parsing data " + e.toString());
}

To get JSONObject from JSONArray we can use for conditional:
JSONArray androids = new JSONArray(json);
for(int i = 0i < androids.length()i++) {
    JSONObject c = androids.getJSONObject(i);
}

And for get the value of JSONObject we can get it by

 public void setValue(JSONObject jsonObject){
        try {
            UserId = jsonObject.getInt("UserId");
            StrUserName = jsonObject.getString("StrUserName");
            StrPassword =jsonObject.getString("StrPassword");
            StrDisplayName =jsonObject.getString("StrDisplayName");
            StrStatus =jsonObject.getString("StrStatus");
            strSAPCode =jsonObject.getString("strSAPCode");
//           isEmpty="1";
        catch (Exception e) {
            e.printStackTrace();
        }
    }

Let see Sample explanation:

            UserId = jsonObject.getInt("UserId");
 
The string “UserId” is the name variable that we get from JSONObject string.

{"CreatedBy":0,"CreatedDate":null,"DatInactived":null,"DatStartActive":null,"StrDisplayName":"M. SUBHAN AKBAR","StrPassword":"XDCXDVC","StrStatus":"A","StrUserName":"1125614","UpdatedBy":0,"UpdatedDate":null,"UserId":207,"strSAPCode":"1125614","ysnFirstLogin":null}
The value off “UserId” is 207

Okay guys and lads lets call it a day,

Just remember guys nobody is perfect and nobody is not perfect, we perfect cause we trying and we not perfect cause we did not trying, cause we never know what we capable without trying. 

Stop thinking. just do it when we have trouble then we think . why it's become the trouble? then we will fix it together or by yourself

Android Singleton Pattern class

Singleton Pattern class



Singleton pattern class is a static class to one object, this class is very useful when one object is needed for the whole application that we created. It’s quite a like session state in web programming, we can get object entity in every class without re declaration of the object. Just like it’s name Singleton this class is a single class with a ton entities , like a one Class Army this class can handle many entities so we don’t have to retrieve a value for every state in application from database or configuration file that required for our application.

Okay ladies, let see what is the Singleton pattern class is look like.:

In these example I use singleton pattern for my android application, 

package com.subhan.core;

import com.subhan.model.userLogin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;

/**
 * Created by Subhan on 10/19/2015.
 */
public class Singleton {
    private static Singleton  mSingleton null;
    private String mString;
    private JSONArray jsonArray;
    private JSONObject jsonObject;
    private userLogin userLogin;
    private List<userLogin> userLoginList;
    private String urlws"http://172.16.110.35:80/Login.svc";

    public List<com.subhan.model.userLogin> getUserLoginList() {
        return userLoginList;
    }

    public void setUserLoginList(JSONArray jsonArray) {
        if(jsonArray.length()>0){
            userLogin usr = new userLogin();
            for (int i=0;i<jsonArray.length();i++) {
                try {
                    usr.setValue(jsonArray.getJSONObject(i));
                catch (JSONException e) {
                    e.printStackTrace();
                }
                this.userLoginList.add(usr);
            }
        }
        this.userLoginList userLoginList;
    }


    public String getUrlws() {
        return urlws;
    }

    public void setUrlws(String urlws) {
        this.urlws = urlws;
    }



    public static Singleton getInstance(){
        if(mSingleton== null)
        {
            mSingletonnew Singleton();
        }
        return mSingleton;
    }
    public com.subhan.model.userLogin getUserLogin() {
        return userLogin;
    }

    public void setUserLogin(com.subhan.model.userLogin userLogin) {
        this.userLogin = userLogin;
    }



    public JSONArray getJsonArray() {
        return jsonArray;
    }

    public void setJsonArray(JSONArray jsonArray) {
        this.jsonArray = jsonArray;
    }

    public JSONObject getJsonObject() {
        return jsonObject;
    }

    public void setJsonObject(JSONObject jsonObject) {
        this.jsonObject = jsonObject;
    }

    private Singleton(){
        mString "Hello";
    }



    public String getString(){
        return this.mString;
    }

    public void setString(String value){
        mString = value;
    }
}
  
At the start the singleton declaration is declared it self :

private static Singleton mSingletonnull;

And create static procedure for initiation of the singleton for every time we will use these Singleton class:



public static Singleton getInstance(){
        if(mSingleton== null)
        {
            mSingletonnew Singleton();
        }
        return mSingleton;
    }

At first the getInstance() have to check are the instance of singleton is available or not by

        if(mSingleton== null)
        {
            mSingletonnew Singleton();
        }

And if not the getInstance() will create a new singleton.
Then return the singleton instance for our application to be use.

This singleton class is can provide a lot of entities , remember the “TON” word even a object.

In these example we can see :

    private String mString;
    private JSONArray jsonArray;
    private JSONObject jsonObject;
    private userLogin userLogin;
    private List<userLogin> userLoginList;
    private String urlws"http://172.16.110.35:80/Login.svc";
And we just had to create a getter and setter for those entities to be use.


How to use Singleton Pattern


We can access this singleton by call the static function getInstance(), for example :

private static String url = Singleton.getInstance().getUrlws()+"/Section/120p";

See , I call   Singleton.getInstance().getUrlws()+"/Section/120p"; 

I use it to retrieve url value that I will use for my application

Okay my dear friend and foe or cyborg from the future that will kill John Connor Mother.. Thank’s for read these blog.. If there’s some thing wrong please let me know. ^__^ V