Monday 31 August 2015

Android Json Parsing

Hello Guys,

Today I explain about Json Parsing in Android. Before i start about json parsing all of you need to know about Json.

I mean to say What is Json and Why we use Json in Android?

Let's start with

Question: What Is Json?

Answer: JSON is nothing but Java Script Object Notation. Its a light weight method for data interchange.

JSON is a very easy form for read and write data.

Question: Why we use JSON?

Answer: As i said in first question's answer, JSON is mainly used for data interchanging. We can simply said that its used in Android for get the required data from server and sometime save the data into server.

So if you want to communicate with another database like MySQL and so on from your android application then JSON is an easy method to use for it.

Let's start its parsing.

For Json Parsing you must need Internet Permission.

Then after you need to connect your application to server for data communication using AsyncTask.

Here I display its sample code.

Sample Code:

File: activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/bg">

    <TextView
        android:id="@+id/text_pickup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pickup Point:"
        android:layout_marginTop="20dp"
        android:paddingLeft="15dp"
        android:typeface="serif"
        android:textStyle="bold"
        android:textColor="#FFBF00"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/edit_pickup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="3dp"
        android:background="@drawable/box"
        android:paddingLeft="6dp">

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/text_dropoff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Dropoff Point:"
        android:layout_marginTop="10dp"
        android:paddingLeft="15dp"
        android:typeface="serif"
        android:textStyle="bold"
        android:textColor="#FFBF00"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/edit_dropoff"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="3dp"
        android:background="@drawable/box"
        android:paddingLeft="6dp"/>
    
    <TextView
        android:id="@+id/text_dist"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Total Distance:"
        android:layout_marginTop="10dp"
        android:paddingLeft="15dp"
        android:typeface="serif"
        android:textStyle="bold"
        android:textColor="#FFBF00"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/edit_dist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="3dp"
        android:focusable="false"
        android:background="@drawable/box"
        android:paddingLeft="6dp"/>
    
    <TextView
        android:id="@+id/text_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Total Time:"
        android:layout_marginTop="10dp"
        android:paddingLeft="15dp"
        android:typeface="serif"
        android:textStyle="bold"
        android:textColor="#FFBF00"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/edit_time"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="3dp"
        android:focusable="false"
        android:background="@drawable/box"
        android:paddingLeft="6dp"/>

    <Button
        android:id="@+id/btn_click"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="Click Me...!"
        android:layout_gravity="center"
        android:layout_marginTop="40dp"
        android:typeface="serif"
        android:textStyle="bold"
        android:background="#FFBF00"/>
    
</LinearLayout>

File: MainActivity.java

package com.sneha.jsonparsingapp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

@SuppressWarnings("deprecation")
public class MainActivity extends Activity
{
EditText et_pickup, et_dropoff, et_distance, et_time;

Button b_click;

ProgressDialog progDialog;

String time, distance;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

et_pickup = (EditText)findViewById(R.id.edit_pickup);
et_dropoff = (EditText)findViewById(R.id.edit_dropoff);
et_distance = (EditText)findViewById(R.id.edit_dist);
et_time = (EditText)findViewById(R.id.edit_time);

b_click = (Button)findViewById(R.id.btn_click);

b_click.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub

if(et_pickup.getText().toString().length() == 0)
{
Toast.makeText(getApplicationContext(), "Please Enter Your Pickup Point",                                        Toast.LENGTH_LONG).show();
}
else if(et_dropoff.getText().toString().length() == 0)
{
Toast.makeText(getApplicationContext(), "Please Enter Your Dropoff                                                   Point", Toast.LENGTH_LONG).show();
}
else
{
// Call url with user define values

String url = "http://maps.googleapis.com/maps/api/directions/json?origin="                                           + et_pickup.getText().toString().replace(" ", "%20") + 
        "&destination=" + et_dropoff.getText().toString().replace(" ", "%20")                                                   +"&sensor=false&units=imperial";

// Create a class for parsing url
GetJson gs = new GetJson(url);
                gs.execute();
       
                Log.i("LOG_URL", "URL Is: "+url);
       
               progDialog = new ProgressDialog(MainActivity.this);
               progDialog.setMessage("Please Wait.....");
               progDialog.setCancelable(false);
               progDialog.show();
}
}
});
}

// Implement the class with AsyncTask for Parsing
private class GetJson extends AsyncTask<Object, Object, Object>
  {
  private String url;
private InputStream is1;
private String res;

  // Constructor
public GetJson(String url)
  {
  this.url = url;
  }
 
// Code performing long running operation goes in this method.
// For Example: When onClick method is executed on click of button, it calls 
// execute method which accepts parameters and automatically calls 
//doInBackground method with the parameters passed.

@SuppressWarnings("deprecation")
@Override
protected Object doInBackground(Object... params) 
{
try
               {
              HttpClient httpclient1 = new DefaultHttpClient();
              HttpPost httppost1 = new HttpPost(url);
              HttpResponse response1 = httpclient1.execute(httppost1);
              HttpEntity entity1 = response1.getEntity();
              is1 = entity1.getContent();
              } 
              catch(Exception e) 
             {
           Log.e("log_tag", "Error in http conection"+e.toString());
             }

     try 
            {
     BufferedReader reader1 = new BufferedReader(new InputStreamReader(is1,"iso-                                8859-1"),8);
                        StringBuilder sb1 = new StringBuilder();
                        String line1 = null;
           
                        while ( (line1 = reader1.readLine() ) != null) 
                       {
                      sb1.append(line1 + "\n"); 
                       }
                       is1.close();
                       res=sb1.toString();
                       Log.i("Response from url = ", res);
           }
           catch(Exception e)
          {
        Log.e("log_tag", "Error converting result "+e.toString());
           }
return null;
     }

    // This method is called after doInBackground method completes processing. 
    // Result from doInBackground is passed to this method.

    @Override
     protected void onPostExecute(Object result1) 
     {
super.onPostExecute(result1);
returnresult(res);
      }
  }
 
// This method is display the result of parsejson method.

  private void returnresult(String res) 
  {
Log.i("Result = ", res);
parsejson(res);
}
 
  // This method is used for parsing of user required url with Json Object, Json Array and so on. 
  private void parsejson(String res)
  {
try 
{
JSONObject rootObj = new JSONObject(res);
JSONArray routes = (JSONArray) rootObj.get("routes");

JSONObject firstRoute = (JSONObject) routes.get(0);
JSONArray legs = (JSONArray) firstRoute.getJSONArray("legs");

JSONObject firstLeg = legs.getJSONObject(0);

JSONObject distanceObject = (JSONObject) firstLeg.get("distance");
JSONObject durationObject = (JSONObject) firstLeg.get("duration");

distance =  distanceObject.getString("text");
time = durationObject.getString("text");

Log.i(" Distance = ", distance);
Log.i(" Duration = ", time);

et_distance.setText(distance);
et_time.setText(time);

progDialog.dismiss();
}
catch (JSONException e) 
{
e.printStackTrace();
}
  }
}

Permission: You must have to add Internet permission into your menifest file.

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

Output:


























Just enter Pickup and Drop-off Point and Click on button. You will get following screens.


















































Happy Coding...!!!

Thursday 20 August 2015

Insert, Update and Delete With Sqlite

Hello Guys,

Today I am going to explain about SQLite Database in android.

SQLite is a same like other database. Its specially used for mobile operating system.

SQLite is nothing but a realtional database which contains C programming language. It is used as an internal or local database for mobile os.

SQLite is mostly used in mobile due to Light Weight, Easy to use for storage, SQL Compatible, Serverless features.

If you want to see the database structure and its data into Eclipse then very first you have to download SQLite Manager.

Download SQLite Manager from here: SQLite Manager

After downloading go to your Eclipse folder like following.

E:\Software\eclipse\plugins

Put (Copy & Paste) your jar file into Plugins folder.

Now Restart your eclipse. You can see the SQLite browser on top right side of the File Explorer.

Sample Code:

Step 1: First you have to create a database.

SQLiteDatabase mydb= openOrCreateDatabase ("firstdb.db", SQLiteDatabase. CREATE_IF_NECESSARY, null);

















Step 2: Create a table and its fields.

String CREATE_TABLE="CREATE TABLE IF NOT EXISTS student(id INTEGER PRIMARY KEY AUTOINCREMENT,fname TEXT,lname TEXT,city TEXT,phone INTEGER);";
       
mydb.execSQL(CREATE_TABLE);


















Step 3: Insert Records

mydb.execSQL("insert into student(fname, lname, city, phone) values ('"+txtFnm.getText()+"', '"+txtLnm.getText()+"', '"+txtCity.getText()+"', '"+txtPhn.getText()+"');");



























Step 4: Delete Records

final SQLiteDatabase mydb=openOrCreateDatabase("firstdb.db", SQLiteDatabase. CREATE_IF_NECESSARY, null);

Cursor cur = mydb.query("student",new String[] { "id" }, "id='" + txtId.getText()+ "'", null, null, null, null, null);

if (cur.getCount() > 0)
{
           mydb.delete("student", "id=?",new String[] { txtId.getText().toString() });
          Toast.makeText(getApplicationContext(),"Record removed successfully.", Toast.                                 LENGTH_SHORT) .show();

          startActivity(new Intent(getApplicationContext(),DatabaseActivity.class));
}
else
{
Toast.makeText(getApplicationContext(),"No such Record found.", Toast.                                           LENGTH_SHORT).show();
}


























Step 5: Update Records

mydb.execSQL("update student set fname='"+txtFnm.getText()+"',lname='"+txtLnm.getText() +"',city='"+txtCity.getText()+"',phone='"+txtPhn.getText()+"' where id='"+txtId.getText()+"'");



























Here I update First Name like following.



























Now I click on Update button and record is updated.



























Step 6: Display Records

mydb=openOrCreateDatabase("firstdb.db", SQLiteDatabase.OPEN_READWRITE,null);

Cursor cur=mydb.query("student", new String[]{"id","fname","lname", "city","phone"} ,null,null,null,null,null,null);

printData(cur);

public void printData(Cursor c)
{
StringBuffer str=new StringBuffer();
String rowResults=null;

str.append("\t\t\t*** Student Data Table *** \n" + " \n Results:" +c.getCount() + "\n\n                         Columns: " + c.getColumnCount()+"\n");

// Print column names
String rowHeaders = "\t  ";

for (int i = 0; i < c.getColumnCount(); i++)
{
rowHeaders = rowHeaders.concat(c.getColumnName(i).toUpperCase() + "\t  ");
}
str.append("\n  " + rowHeaders+"\n");

// Print records
c.moveToFirst();
        while (c.isAfterLast() == false)
        {
str.append(rowResults = "\t  ");

for (int i = 0; i < c.getColumnCount(); i++)
{
rowResults = rowResults.concat(c.getString(i) +"\t\t ");
}

str.append("\n"+rowResults);
c.moveToNext();
}
tv.setText(str);
}



























Download Full Source Code: Database Example

Enjoy Coding...!!!

Tuesday 18 August 2015

Get Contacts From Device Phone Directory

Hello Guys,

Here I am going to share an example of Get contacts from your device phone directory.

For getting all contacts from your phone directory you can can simple use of Contact Intent.

Sample Code:

File: PickContactActivity.java

package com.sneha.pickcontact;

import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button; 

public class PickContactActivity extends Activity
{
Button btn_contact;
String name;

private static final int PICK_CONTACT = 0;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_pick_contact);

btn_contact = (Button) findViewById(R.id.button1);

btn_contact.setOnClickListener(new OnClickListener() 
{
@Override
public void onClick(View v) 
{
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_PICK,                                                                                   ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) 
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.pick_contact, menu);
return true;
}

@Override
public void onActivityResult(int reqCode, int resultCode, Intent data) 
{
 super.onActivityResult(reqCode, resultCode, data);

 switch (reqCode) 
 {
    case (PICK_CONTACT) :
    if (resultCode == Activity.RESULT_OK) 
    {
    Uri contactData = data.getData();
    Cursor c =  getContentResolver().query(contactData, null, null, null, null);
    if (c.moveToFirst()) 
    {
    name = c.getString(c.getColumnIndex (ContactsContract. Contacts.                                                       DISPLAY_NAME));
    }
    }
    break;
     }
}
}

File: activity_pick_contact.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/bg"
    android:gravity="center">

    <Button
        android:id="@+id/button1"
        android:layout_width="300dp"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:background="@drawable/contact_btn"/>

</LinearLayout>

File: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sneha.pickcontact"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"/>
    
    <uses-permission android:name="android.permission.READ_CONTACTS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".PickContactActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

You can download background image and contact button from here.

Background Image:





















Contact Button Image:










Output:





















Enjoy Coding...!!!

Read PDF Using Adobe Reader

Hello Guys,

Here I share an example of Read PDF using Adobe Reader. It gives you to bookmark selected page, add comment and do more settings from adobe reader.

Sample Code:

File: MainActivity.java

package com.sneha.pdfreader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends Activity 
{
URLConnection urlConnection = null;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

new Thread(new Runnable() 
{
   public void run() 
   {
    downloadFile();
   }
 }).start();
}

void downloadFile() 
{
// TODO Auto-generated method stub
try{
       URL url = new URL("http://www.tutorialspoint.com/android/android_tutorial.pdf");
       
       //Opening connection of currrent url
       urlConnection = url.openConnection();
       urlConnection.connect();

       String PATH = Environment.getExternalStorageDirectory() + "/MyDownloads/";
       
       final File file = new File(PATH);
       file.mkdirs();
       final File outputFile = new File(file, "android_tutorial.pdf");
       FileOutputStream fos = new FileOutputStream(outputFile);

       InputStream is = url.openStream();
       
       byte[] buffer = new byte[1024];
       
       int len1 = 0;
       
       while ((len1 = is.read(buffer)) != -1) 
       {
        fos.write(buffer, 0, len1);
       }
       
       fos.close();
       is.close();
       
       runOnUiThread(new Runnable() 
       {
                     public void run()
                    {
                         Uri path = Uri.fromFile(outputFile);
                         Log.i("Log_Path", "Path Is: "+path);
                    
                         try 
                        {
                               Intent intent = new Intent(Intent.ACTION_VIEW);
                               intent.setDataAndType(path, "application/pdf");
                               intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                               startActivity(intent);
                               finish();
                        } 
                        catch (ActivityNotFoundException e) 
                       {
                              Toast.makeText(getApplicationContext(),"PDF Reader application is not installed                               in your device",Toast.LENGTH_SHORT).show();
                        }
                    }
               });
   }
   catch (Exception e) 
   {
       // TODO: handle exception
       e.printStackTrace();
   }
}
}

File: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sneha.pdfreader"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"/>
    
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


Output:





















Happy Coding...!!!