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

June 16, 2014

AsyncTask in Android.

    
       AsyncTask  is one Class which is used to perform background processes without having threads. For an AsyncTask is having 4 steps. onPreExecute, doInBackground, onProgressUpdate, onPostExecute

onPreExecute method is invoked first while calling the AsyncTask. Here comes the fuctions which are to be performed at the starting. The functions such as  showing progress dialog etc..

doInBackground method will execute after onPreExecute method. Here comes the functions which are to be done in background. The functions such as downloading files uploading files etc...

onProgressUpdate method is invoked while the progress is changed. Here we will write the code to perform the action while changing the progress.

onPostExecute method is invoked after the doInBackground method is completed. This method will execute at last. Here we will write code to perform the actions at last. The functions such as progress dialog dismiss, parse the result, redirection to another page etc..

Here is One Example:

 private class LoginProcessing extends AsyncTask<Object, Void, Void> {
         private LoginCredentials myLoginCredentials;
         private LoginToken loginToken;
         private ProgressDialog progressDialog;
      
         public LoginProcessing(LoginCredentials Credentials) {
                super();
                myLoginCredentials=Credentials;
         }

         protected void onPreExecute (){
             progressDialog = ProgressDialog.show(context, "", "Logging you in Reward World...",true);
         }
        
        @Override
        protected Void doInBackground(Object... arg0) {
            // TODO Auto-generated method stub
             try {
                   loginToken = PersistenceService.getService().login(myLoginCredentials);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            return null;      
        }
        protected void onPostExecute(Void result){
            progressDialog.dismiss();
            if(loginToken!=null){
                if(loginToken.isIsValidLogin()){
                    SaveToken(loginToken.getToken());
                    Intent intent = new Intent(context, HomeScreen.class);
                    startActivity(intent);
                    finish();
                }
                else{

                     ShowLoginFailedDialog(loginToken.getErrorOnFailure().toString());                   
                }
            }else{
                Message("Service Error");
            }
              
        }
        
     }
    

In this LoginProcessing LoginCredentials is the parameters passing to the login function.The LoginProcessing AsyncTask can be called by,

            new LoginProcessing(loginCredentials).execute();


May 07, 2014

SharedPreferences In Android.


SharedPreferences

                  SharedPreferences is one of the storage mechanism in Android. The value we are storing in Shared Preferences is permanent so the value stored will remains there when we close the application. Here the storing of data is done as key value pair. Here we store the data with the help of an editor.  To get the value we have saved we need to call getSharedPreferences() method.

Here I am going to Explain How to save the details Id, Name, Designation, Phone number of an Employee in  SharedPreferences.

Here Am going to create a class EmployeeSession to store the details,


public class EmployeeSession {

      private static final String  SharedPreference_Employee = "Employee_Preferences";
     // Employee_Preferences is the Name of the SharedPreferences.

    private static final String Emp_Id = "EmployeeId";
    private static final String Emp_Name = "EmployeeName";
    private static final String Emp_Designation = "EmployeeDesignation";
    private static final String Emp_Phone = "EmployeePhone";

    private SharedPreferences sharedPref;
    private Editor editor;

    public EmployeeSession(Context context) {
        sharedPref = context.getSharedPreferences(SharedPreference_Employee, Context.MODE_PRIVATE);
        editor = sharedPref.edit();
    }

    public void ResetEmployee() {
       // Function To clear all the Employee Details
        editor.clear();
        editor.commit();
    }

   public void setEmployeeId(Int Id) {
      // Function To save Employee Id
        editor.putInt(Emp_Id, Id);
        editor.commit();
    }

    public Int getEmployeeId() {
       // Function To get Employee Id
        return sharedPref.getInt(Emp_Id, 0); 
    }

    public void setEmployeeName(String Name) {
       // Function To save Employee Name
        editor.putString(Emp_Name, Name);
        editor.commit();
    }

    public String getEmployeeName() {
       // Function To get Employee Name
        return sharedPref.getString(Emp_Name, null);
    }

    public void setEmployeeDesignation(String Designation) {
        // Function To save Employee Designation
        editor.putString(Emp_Designation, Designation);
        editor.commit();
    }

    public String getEmployeeDesignation() {
        // Function To get Employee Designation
        return sharedPref.getString(Emp_Designation, null);
    }

   public void setEmployeePhone(String Phone) {
       // Function To save Employee Phone Number
        editor.putString(Emp_Phone, Phone);
        editor.commit();
    }

    public String getEmployeePhone() {
        // Function To get Employee Phone Number
        return sharedPref.getString(Emp_Phone, null);
    }

}


       In the Above example I am saving only Int and String values. You can Also save Int, String, Boolean, Float, Long values in SharedPreferences. Here is am example of saving and retrieve of values.

Save / Update Valus

  editor.putInt(IntKeyValue, Value);   // Here Value is the Int value to store
  editor.putString(StringKeyValue, Value);  // Here Value is the String value to store
  editor.putBoolean(BooleanKeyValue, Value);   // Here Value is the Booleanvalue to store
  editor.putFloat(FloatKeyValue, Value);  // Here Value is the Float value to store
  editor.putLong(LongKeyValue, Value);    // Here Value is the Long value to store

 editor.commit();    // This method is used to save the changes.

Retrieve Values

  sharedPref.getInt(IntKeyValue, Value);   // Here Value is the default value to return if it is Null
  sharedPref.getString(StringKeyValue, Value);  // Here Value is the default value to return if it is Null
  sharedPref.getBoolean(BooleanKeyValue, Value);  // Here Value is the default value to return if it is Null
  sharedPref.getFloat(FloatKeyValue, Value);  // Here Value is the default value to return if it is Null
  sharedPref.getLong(LongKeyValue, Value);    //  Here Value is the default value to return if it is Null

Delete/ Clear

To delete a particular key you can do like,

editor.remove("KeyName1");   // To delete the Key KeyName1
editor.remove("KeyName2");   // To delete the Key KeyName2
editor.commit();  // To save the changes.


     To clear All the Values in SharedPreferences we can use clear() function. Here is the Example,

editor.clear();
editor.commit(); // To save the changes.


April 29, 2014

How To Get KeyHash, MD5 , SHA1, SHA256 of keystore

Here is the Steps,

WINDOWS

Step1 : We need to download openssl from Google code (64 bit users must download openssl-0.9.8e X64, not the latest version).

Step2 :  Extract it. and create a folder- "OpenSSL" in C:/ and copy the extracted code here.First open a terminal and go to JAVA\bin.

Step3 : Detect keystore file path and go to that directory in command promp (cmd).

Step4 : Type this command in 1 line.
keytool -exportcert -alias androiddebugkey -keystore "C:\path to keystore\keystore_name.keystore" | "C:\OpenSSL\bin\openssl" sha1 -binary |"C:\OpenSSL\bin\openssl" base64

If it is not Working Use This,

keytool -list -v -keystore  C:\path to keystore\keystore_name.keystore

Step5 : Now, it will ask for password, Enter the password (Password of  default keystore will be  android for the default keystore ).


MAC

Step1 :  First open a terminal.

Step2 :  Navigate in the terminal to the directory where your Android debug.keystore is stored.

Step3 : Mostly the default keystore location in MAC will be in “/Users/user_name/.android/” .  Once you are in the keystore directory, run the following command.

Step4 :  keytool -exportcert -alias androiddebugkey -keystore debug.keystore | openssl sha1 -binary | openssl base64

If it is not Working Use This,

keytool -list -v -keystore  C:\path to keystore\keystore_name.keystore


 Here  debug.keystore is the keystore name. Replace this name with your keystore name.

Step5 : When it prompts you for a password then press Enter. (Password of  default keystore will be  android for the default keystore ).



March 19, 2014

How to play embeded youtube video on webview


                   In this blog i am going to explain how to play embeded Youtube video on webview. am loading the video file in  an iframe. While Loading the html page my webview is loading like,

Here is my HTML Page:  

<html>
<head> </head>
<body>
<iframe width="560" height="315" class="youtube-player" type="text/html" src="http://www.youtube.com/embed/YfQW6cpRHlo" frameborder="0" allowfullscreen>
</iframe>
</body>
</html>


Here the embeded video link is "http://www.youtube.com/embed/YfQW6cpRHlo". In this link "YfQW6cpRHlo" is the Id of Video file. If you want to play another video you just replace the video id on this link.

Android Code


activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"/>
</LinearLayout>


 MainActivity.Java

Here "http://example.com/shidhin/test.html" is my webpage Link.You Can replace it by your Own Link.

import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

public class MainActivity extends Activity {

    private TextView textView;
    private WebView webView;
    private ProgressDialog progressDialog;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
      
        textView = (TextView) findViewById(R.id.textView1);
        webView = (WebView) findViewById(R.id.webView1);
        

        progressDialog = ProgressDialog.show(MainActivity.this, "", "Loading...",true);
      
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setPluginState(PluginState.ON);
        webView.getSettings().setAllowFileAccess(true);
      
        webView.loadUrl("http://example.com/shidhin/test.html");
        webView.setWebChromeClient(new WebChromeClient() {
        });
            
        webView.setWebViewClient(new WebViewClient() {
                 public boolean shouldOverrideUrlLoading(WebView view, String url) {
                     return false;
                }
                public void onPageFinished(WebView view, String url) {
                   progressDialog.dismiss();
                   //Toast.makeText(context, "Page Load Finished", Toast.LENGTH_SHORT).show();
                }
          });       
    }

}


AndroidManifest.xml


                    Here I have added   android:hardwareAccelerated="true" On Application tag.

 <application
        android:allowBackup="true"
        android:hardwareAccelerated="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >


Also Dont Forgot to Add Permissions on the Manifest file. We need Internet Permission to get the Internet Connection.

<uses-permission android:name="android.permission.INTERNET" />