Friday, May 20, 2011

Using JSON in Android



              JSON (JavaScript Object Notation):

                        JSON is a light weight one, which help us to interchange data in a simple manner.

            JSON is built on two structures:


1.     A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.

For Instance in Java we refer it is an Object.

2.     An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

For Instance in Java we refer it as array.


Rules for creating a JSON string:

A JSON string contains either an array of values, or an object (an associative array of name/value pairs).

An array is surrounded by square brackets, [ and ], and contains a comma-separated list of values.

An object is surrounded by curly brackets, { and }, and contains a comma-separated list of name/value pairs.

A name/value pair consists of a field name (in double quotes), followed by a colon (:), followed by the field value.

A value in an array or object can be:

A number (integer or floating point)

A string (in double quotes)

A boolean (true or false)

Another array (surrounded by square brackets, [ and ])

Another object (surrounded by curly brackets, { and })

The value null

  
Example of a JSON:


Starting point of JSON object so we used curly brackets


{" data ":
{ 
     "Book Title": “C world",
     “Book Author ": “Dennis Retchie”,
     "address":
“_comment”: “another JSON Object...",
    {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": "10021"
     },
     "phoneNumber":
“_comment”: “Starting of JSON Array...",
     [
         {
           "type": "home",
           "number": "212 555-1234"
         },
         {
           "type": "fax",
           "number": "646 555-4567"
         }
     ]
 } }

Let us fetch the Value from JSON in Android

Step 1: Create JSONObject as shown I below

private JSONObject myJSONObject=new JSONObject(),myJSONfetchdata;

            Step 2: Initialize it as I Shown Below

                        myJSONfetchdata = myJSONObject.getJSONObject(“data”);

            Step 3: Fetch the Values as I Shown Below

                        String mybooktitle   =  myJSONfetchdata.getString("Book Title");

                        String mybookauthor= myJSONfetchdata.getString("Book Author ");

                        JSONObject address =myJSONfetchdata. getJSONObject ("address");

                        String streetAddress  =address.getString("streetAddress");

                        String city  = address.getString("city");

                        String state = address.getString("state");

                        String postalCode  = address.getString("postalCode");

                        JSONArray phoneNumber =  myJSONfetchdata.getJSONArray(“phoneNumber”);

                        String[] type  =  new String[phoneNumber.length()];

                         String[]  number  = new String[phoneNumber.length()];

                        for(int z=0;z< phoneNumber.length();z++)
                         {
                                    type [z]   =  phoneNumber.getString("type ");
                                    number [z] = phoneNumber.getString("number");
                          }




Tuesday, May 10, 2011

How to Fetch Phone contacts and Show it in AutoComplete TextView in Android ?

  Step 1. Create Autocomplete in a xml file as i shown below

<AutoCompleteTextView android:paddingTop="15dp"
android:id="@+id/txtPhoneNo"
android:focusableInTouchMode="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"/>

Step 2. Add the following permission in your Android Mainfeast file for accessing contacts

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

Step 3. Create an Activity and maps the autocompletetextview component in your Java Code

public class MyContacts extends Activity {

AutoCompleteTextView txtPhoneNo;


public ArrayList<String> c_Name = new ArrayList<String>();
public ArrayList<String> c_Number = new ArrayList<String>();
String[] name_Val=null;
String[] phone_Val=null;

@Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
txtPhoneNo = (AutoCompleteTextView) findViewById(R.id.txtPhoneNo);

}

Step 4: Use ContentReslover to fetch the contacts, if you are running it in Android 1.6 or before version use people class for fetching contacts and add that contacts in an Array List as i shown below

ContentResolver cr1 = getContentResolver();

String[] projection = new String[] { People._ID,People.NAME,People.NUMBER };

Uri phone_contacts = People.CONTENT_URI;

Cursor managedCursor = cr1.query(phone_contacts, projection, null, null, People.NAME + " ASC");

if (managedCursor.moveToFirst()) {

String contactname;
String cphoneNumber;
int nameColumn = managedCursor.getColumnIndex(People.NAME);
int phoneColumn = managedCursor.getColumnIndex(People.NUMBER);
Log.d("int Name",Integer.toString(nameColumn));
Log.d("int Number",Integer.toString(phoneColumn));


do {
// Get the field values
contactname = managedCursor.getString(nameColumn);
cphoneNumber = managedCursor.getString(phoneColumn);
if((contactname != " " || contactname != null) && (cphoneNumber!= " " ||cphoneNumber!= null))
{

c_Name.add(contactname);
c_Number.add(cphoneNumber);
}


} while (managedCursor.moveToNext());

}


// Donot use People class if your using android1.6 above

Uri contacts = Uri.parse("content://icc/adn");

Cursor managedCursor1 =cr.query(contacts, null, null, null, null);

if (managedCursor1.moveToFirst()) {

String contactname;
String cphoneNumber;

int nameColumn = managedCursor1.getColumnIndex("name");
int phoneColumn = managedCursor1.getColumnIndex("number");

Log.d("int Name",Integer.toString(nameColumn));
Log.d("int Number",Integer.toString(phoneColumn));


do {
// Get the field values
contactname = managedCursor1.getString(nameColumn);
cphoneNumber = managedCursor1.getString(phoneColumn);
if((contactname != " " || contactname != null) && (cphoneNumber!= " " ||cphoneNumber!= null))
{

c_Name.add(contactname);
c_Number.add(cphoneNumber);
}

} while (managedCursor1.moveToNext());

}


Step 5: Now convert the ArrayList to Array and set that Array to AutoComplete as i Shown Below

name_Val = (String[]) c_Name.toArray(new String[c_Name.size()]);
phone_Val= (String[]) c_Number.toArray(new String[c_Name.size()]); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, name_Val);
txtPhoneNo.setAdapter(adapter);

Notification in Android Using AlarmManager, BoradCastReceiver & Services

    Our aim is to show notification message to user in a specific time.     Say For example , I have planned to show Notification ...