November 18, 2014

How to parse a json file In Android

                   In this blog I am going to explain How to parse a json file. Here I am going to explain how to parse a json file stored in Asset folder. Here my file name is user_details.json which stored in asset folder(json_file/user_details.json). Here is my json file.

user_details.json

{
  "Name": "Shidhin",
  "UserId" : "1",
  "Website" : "http://shidhints.com",
  "Mobile" : "+91XXXXXXXXXX",
  "Qualification": [
    {
            "Name": "Name1",
            "Institute": "Institute Name1",
    "Year": "2006 - 2009",
            "Mark": "87%"
    }, 
    {
            "Name": "Name2",
            "Institute": "Institute Name2",
    "Year": "2004 - 2006",
            "Mark": "78%"
    }, 
    {
             "Name": "Name3",
            "Institute": "Institute Name3",
    "Year": "2004",
            "Mark": "93%"
    }
  ]
}

                  In this Json file I am having Strings Name, UserId, Website, Mobile and an Array Qualification which is also contains some Strings.

Java Code

                   Here we are parsing the json file with the help of JSONObject. First we will create a JSONObject and we will extract the String using .getString() method. Here is the sample code.
   
       try {
InputStream is = getApplicationContext().getAssets().open("json_file/user_details.json");
String jString = ReadInputStreamAsString(is);
JSONObject jObject = new JSONObject(jString);

//Extracting Strings
String nameStr = jObject.getString("Name");  // Extract Name
String userIdStr = jObject.getString("UserId");  // Extract UserId
String websiteStr = jObject.getString("Website");  // Extract Website
String mobileStr = jObject.getString("Mobile");   // Extract Mobile

//Extracting Qualification Array
   JSONArray viewsObject = jObject.getJSONArray("Qualification");
for (int i = 0; i < viewsObject.length(); i++) {
JSONObject object = viewsObject.getJSONObject(i); //Creating Json object
String name = object.getString("Name");
String institute = object.getString("Institute");
String year = object.getString("Year");
String mark = object.getString("Mark");
}

} catch (Exception e) {
Helper.reportException(CreateCard.this, e);
}


ReadInputStreamAsString

                               This Function will convert the given InputStream to a String. Using this string we will create a json Object to parse the json.

         public static String ReadInputStreamAsString(InputStream in) throws IOException {

BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while (result != -1) {
byte b = (byte) result;
buf.write(b);
result = bis.read();
}
return buf.toString();
        }

November 12, 2014

How to call a webservice in android.

            In this blog I am going to explain How to call a .Net xml webservice in android with the help of an login WebService.

XML Request

POST /Service.asmx HTTP/1.1
Host: shidhints.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://shidhints.com/Login"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <Login xmlns="http://shidhints.com/">
        <Email>string</Email>
        <Password>string</Password>
    </Login>
  </soap:Body>
</soap:Envelope>

                  In this WebService request Our Function name is  "Login " and the parameters we are passing are "Email" which is "string" format and  "Password" which is also in "string" format.

XML Responc

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <LoginResponse xmlns="http://shidhints.com/">
         <LoginResult>
             <IsValidLogin>boolean</IsValidLogin>
             <ErrorOnFailure>string</ErrorOnFailure>
             <Token>string</Token>
       </LoginResult>
    </LoginResponse>
  </soap:Body>
</soap:Envelope>

               In this WebService response we are getting result through the parameters "IsValidLogin" which is a "boolean" value and  "ErrorOnFailurewhich is a "string" value and  "Tokenwhich is also a "string" value. Here if the "IsValidLogin" is true then it will pass the "Token" otherwise it will pass "ErrorOnFailure" which contains the reason of failure.

Android Code

                  In Android I am calling this WebService with the help of a Library called Ksoap. You can get more about Ksoap form Here. First we need to download the Ksoap .Jar file and add that library to your Android project.

Java Code

private static String NAMESPACE = "http://shidhints.com/";
private static String URL = "http://shidhints.com/Service.asmx?wsdl";



public LoginToken login(String Email, String Password ) throws Exception {
        String METHOD_NAME = "Login";
        String SOAP_ACTION = "http://shidhints.com/Login";

        SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
        Request.addProperty("Email", Email); // Adding Email to request
        Request.addProperty("Password", Password ); // Adding Password to request

        LoginResult loginResult;
        try
        {
            SoapObject response = executeRequest(Request, SOAP_ACTION);
            if(response != null){
                  loginResult= new LoginResult((SoapObject) response.getProperty(0));
                  return loginResult;
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
return null;
 }

// This function is to call the webservice
private SoapObject executeRequest(SoapObject Request, String SOAP_ACTION) throws IOException{

    System.setProperty("http.keepAlive", "false");
   
    SoapSerializationEnvelope envelope = new  SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;
    envelope.setOutputSoapObject(Request);
    envelope.implicitTypes=true;
    envelope.dotNet = true; 
    envelope.setAddAdornments(false);
    envelope.encodingStyle = SoapSerializationEnvelope.XSD;
    envelope.enc = SoapSerializationEnvelope.ENC;
    envelope.xsd = SoapEnvelope.XSD;
    envelope.xsi = SoapEnvelope.XSI;
     
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
    androidHttpTransport.debug = true; 
    SoapObject response;
    try
           {
               androidHttpTransport.call(SOAP_ACTION, envelope);
               response = (SoapObject) envelope.bodyIn;
                return response;
           }
           catch(Exception e)
           {
               e.printStackTrace();
           }
    return null;
}

                      Here I am executing the request through "executeRequest" function. The result will be in "SoapObject" format. Now I will pass this result to my "LoginResult " class. In that class It will parse the response.

Parsing SoapObject 

 public LoginResult (SoapObject response){
    Boolean LoginStatus= false;
    String Token = "" , ErrorOnFailure = "";
    ValidLogin = response.getProperty("IsValidLogin").toString();
    if(ValidLogin.equalsIgnoreCase("true")){
    LoginStatus=true;
    Token = response.getProperty("Token").toString();
    }else{
    ErrorOnFailure = response.getProperty("ErrorOnFailure").toString();
     } 

}



November 11, 2014

SQLite Database in android

                           
               In this blog I am going to explain SQLite database in android. It is an Open Source Database, Also Its is embedded to all the android devices so there is no need to add any library to the application. You are need to import SQLiteDatabase and SQLiteOpenHelper for that.

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


Also I an going to explain How to create a Database, Tables, Inserting values, Updating values, Deleting values from the Database operations in Android.

More Information about SQLite :  http://www.sqlite.org
More Information about SQLite Data-types:  http://www.sqlite.org/datatype3.html

Creating Database

     First you are needed to create a class for database. Here I am going to create a class "DbHelper".

public class DbHelper {

}

Now I need to extend SQLiteOpenHelper on this class. While extending this we need to add constructor and some unimplemented methods. Also I am going to declare the "DATABASE_VERSION" and "DATABASE_NAME" on this class.

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DbHelper  extends SQLiteOpenHelper {


     private static final int DATABASE_VERSION = 3;
    public static final String DATABASE_NAME = "MyExample.sqlite";
    private Context context;

    public DbHelper(Context myContext) {
        super(myContext, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = myContext;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
    }

}


           Here "DATABASE_VERSION"  is the version if the database. If there is a version change it will automatically call the unimplemented method "onUpgrade". In this method we need to specify the modification we need to done on the database.

"DATABASE_NAME" is the name which the database is to be saved. While Initializing the database class id we add a path here "DbPath" is the path of  Db to be stored, It will save the database on that location, like,

public DbHelper(Context myContext) {
        super(myContext, DbPath+DATABASE_NAME, null, DATABASE_VERSION);
        this.context = myContext;
 }

Table Creation:

Here I am going to create a table for storing user details,

  public static final String USERS_TABLE_NAME = "Users";  //User Table Name

  //User Table Fields.
  private static final String UserID = "UserID";
  private static final String Email = "Email";
  private static final String Name = "Name";
  private static final String Role = "Role"; 

  //Table Creation Query
 private static final String USERS_TABLE_CREATE =  "CREATE TABLE " + USERS_TABLE_NAME + " (" + UserID + " INTEGER PRIMARY KEY, " + Email + " TEXT , "+ Name + " TEXT , "+ Role + " INTEGER );";

Insertion:

          Here is a function to insert the details, Here I am passing an object of User and after inserting it will return the Id of inserted object.

public long SaveUsers(Users users){
SQLiteDatabase ceilDb = this.getWritableDatabase();
long id = 0;
Cursor c = null;
try { 
ContentValues values = new ContentValues();
values.put(UserID, users.getUserID());
values.put(Email, users.getEmail());
values.put(Name, users.getName());
values.put(Role, users.getRole());

id = ceilDb.insert(USERS_TABLE_NAME, null, values);
System.out.println("Db :> User Saved ID : "+id);

} catch (Exception e) {
System.out.println("Db :> Failed to Save User, Error is: "+ e.getMessage().toString());
e.printStackTrace();
}
c.close();
ceilDb.close();
return id;
}

Deletion:

            Here is a function to insert the details, Here I am passing the id of User first it will check if the user is exist if the user exist then it will delete the row.

public long DeleteUsers(long Id){
SQLiteDatabase ceilDb = getReadableDatabase();
Cursor c = null;

String[] cols = { UserID, Email, Name, Role};
try{
c = ceilDb.query(USERS_TABLE_NAME, cols, UserID + "=" + Id, null, null, null, null);
int k=c.getCount();
if (k!=0) {
if (c.moveToFirst()) {
do {
ceilDb.delete(USERS_TABLE_NAME,  UserID + "=" + Id , null);
} while (c.moveToNext());
}
System.out.println("Db :> User Deleted ID : "+Id);
}
} catch (Exception e) {
System.out.println("Db :> Failed to Save User, Error is: "+ e.getMessage().toString());
e.printStackTrace();
}
c.close();
ceilDb.close();
return id;
}

Updation:

           Here is a function to Update the details, Here I am passing an object of User first it will check if the user is exist if the user exist then it will delete the row.

public long UpdateUsers(Users users){
SQLiteDatabase ceilDb = this.getWritableDatabase();
long id = 0;
Cursor c = null;
try { 
ContentValues values = new ContentValues();
values.put(UserID, users.getUserID());
values.put(Email, users.getEmail());
values.put(Name, users.getName());
values.put(Role, users.getRole());

String[] cols = { UserID , Email};
c = ceilDb.query(USERS_TABLE_NAME, cols, UserID + "=" + users.getUserID(), null, null, null, null);
int k=c.getCount();
if (k!=0) {
if (c.moveToFirst()) {
do {
id = ceilDb.update(USERS_TABLE_NAME, values, UserID + "=" + users.getUserID() , null);
} while (c.moveToNext());
}
System.out.println("Db :> User Updated ID : "+users.getUserID());
}
} catch (Exception e) {
System.out.println("Db :> Failed to Save User, Error is: "+ e.getMessage().toString());
e.printStackTrace();
}
c.close();
ceilDb.close();
return id;
}

Retrive:

          Here is a function to insert the details, Here I am passing the id of User first it will check if the user is exist if the user exist then it will take the details from db and return it.


public Users getUser(long Id){
SQLiteDatabase ceilDb = getReadableDatabase();
Users users = null;
Cursor c = null;

String[] cols = { UserID, Email, Name, Role};
try{
c = ceilDb.query(USERS_TABLE_NAME, cols, UserID + "=" + Id, null, null, null, null);
int k=c.getCount();
if (k!=0) {
if (c.moveToFirst()) {
do {
users = new Users();
users.setUserID(c.getInt(0));
users.setEmail(c.getString(1));
users.setName(c.getString(2));
users.setRole(c.getInt(3));

} while (c.moveToNext());
}
System.out.println("Db :>Get Users ");
}
} catch (Exception e) {
System.out.println("Db :> Failed to Retrive Users Error is: "+ e.getMessage().toString());
e.printStackTrace();
}
c.close();
ceilDb.close();
return users;
}


Implementation to DbHelper  class.

public class DbHelper  extends SQLiteOpenHelper {

     private static final int DATABASE_VERSION = 3;
    public static final String DATABASE_NAME = "MyExample.sqlite";
    private Context context;


    public static final String USERS_TABLE_NAME = "Users";  //User Table Name

    //User Table Fields.
    private static final String UserID = "UserID";
    private static final String Email = "Email";
    private static final String Name = "Name";
    private static final String Role = "Role"; 

    //User Table Creation Query
 private static final String USERS_TABLE_CREATE =  "CREATE TABLE " + USERS_TABLE_NAME + " (" + UserID + " INTEGER PRIMARY KEY, " + Email + " TEXT , "+ Name + " TEXT , "+ Role + " INTEGER );";


    public DbHelper(Context myContext) {
        super(myContext, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = myContext;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(USERS_TABLE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
     
    }


//Function to insert User details
  public long SaveUsers(Users users){
SQLiteDatabase ceilDb = this.getWritableDatabase();
long id = 0;
Cursor c = null;
try { 
ContentValues values = new ContentValues();
values.put(UserID, users.getUserID());
values.put(Email, users.getEmail());
values.put(Name, users.getName());
values.put(Role, users.getRole());

id = ceilDb.insert(USERS_TABLE_NAME, null, values);
System.out.println("Db :> User Saved ID : "+id);

} catch (Exception e) {
System.out.println("Db :> Failed to Save User, Error is: "+ e.getMessage().toString());
e.printStackTrace();

c.close();
ceilDb.close();
return id;
}

//Function to get user details
public Users getUser(long Id){
SQLiteDatabase ceilDb = getReadableDatabase();
Users users = null;
Cursor c = null;

String[] cols = { UserID, Email, Name, Role};
try{
c = ceilDb.query(USERS_TABLE_NAME, cols, UserID + "=" + Id, null, null, null, null);
int k=c.getCount();
if (k!=0) {
if (c.moveToFirst()) {
do {
users = new Users();
users.setUserID(c.getInt(0));
users.setEmail(c.getString(1));
users.setName(c.getString(2));
users.setRole(c.getInt(3));

} while (c.moveToNext());
}
System.out.println("Db :>Get Users ");
}
} catch (Exception e) {
System.out.println("Db :> Failed to Retrive Users Error is: "+ e.getMessage().toString());
e.printStackTrace();
}
c.close();
ceilDb.close();
return users;
}

//Function to Update Table
public long UpdateUsers(Users users){
SQLiteDatabase ceilDb = this.getWritableDatabase();
long id = 0;
Cursor c = null;
try { 
ContentValues values = new ContentValues();
values.put(UserID, users.getUserID());
values.put(Email, users.getEmail());
values.put(Name, users.getName());
values.put(Role, users.getRole());

String[] cols = { UserID , Email};
c = ceilDb.query(USERS_TABLE_NAME, cols, UserID + "=" + users.getUserID(), null, null, null, null);
int k=c.getCount();
if (k!=0) {
if (c.moveToFirst()) {
do {
id = ceilDb.update(USERS_TABLE_NAME, values, UserID + "=" + users.getUserID() , null);
} while (c.moveToNext());
}
System.out.println("Db :> User Updated ID : "+users.getUserID());
}
} catch (Exception e) {
System.out.println("Db :> Failed to Save User, Error is: "+ e.getMessage().toString());
e.printStackTrace();

c.close();
ceilDb.close();
return id;
}

//Function to Delete User
public long DeleteUsers(long Id){
SQLiteDatabase ceilDb = getReadableDatabase();
Cursor c = null;

String[] cols = { UserID, Email, Name, Role};
try{
c = ceilDb.query(USERS_TABLE_NAME, cols, UserID + "=" + Id, null, null, null, null);
int k=c.getCount();
if (k!=0) {
if (c.moveToFirst()) {
do {
ceilDb.delete(USERS_TABLE_NAME,  UserID + "=" + Id , null);
} while (c.moveToNext());
}
System.out.println("Db :> User Deleted ID : "+Id);
}
} catch (Exception e) {
System.out.println("Db :> Failed to Save User, Error is: "+ e.getMessage().toString());
e.printStackTrace();

c.close();
ceilDb.close();
return Id;
}

}


Calling DB Functions

When you initialize the object of  DbHelper class it will check if the Db is exist if it doesn't exist it will create the Db and table by executing the methods  DbHelper  and  onCreate. If there is a version change it will automatically call the unimplemented method "onUpgrade". In this method we need to specify the modification we need to done on the database.

Database Initialization
       
  private DbHelper dbHelper = new DbHelper(context);

Calling Database Operations

Insertion
private DbHelper dbHelper = new DbHelper(context);
dbHelper.SaveUsers(users) // here user is an object to insert.

Deletion
private DbHelper dbHelper = new DbHelper(context);
dbHelper.DeleteUsers(Id// here Id is an id of the user to be deleted

Updation
private DbHelper dbHelper = new DbHelper(context);
dbHelper.UpdateUsers(users) // here user is an object to be updated.

Retrive
private DbHelper dbHelper = new DbHelper(context);
users = dbHelper.getUser(Id)// here Id is an id of the user