Monday, 16 April 2012

SAMPLE NEW APP IN ANDROID - BASIC STEPS

Conference Dialing


/********************* ConferenceDialing Manifest *****************/

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

<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.CALL_PRIVILEGED" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".ConferenceDialingActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".DialerInput"
android:label="DIALER INPUT" ></activity>
<activity android:name=".ViewDetailsActivity"
android:label="DIALER INPUT" ></activity>
</application>

</manifest>

/******************* ConferenceDialingActivity **********************/
package com.confdial.android;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ConferenceDialingActivity extends Activity implements OnClickListener{
Button btn_start;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_start = (Button) findViewById(R.id.btn_start);
btn_start.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
Intent intent = new Intent(ConferenceDialingActivity.this, DialerInput.class);
startActivity(intent);
}
}



/******************* DialerInput.java **********************/

package com.confdial.android;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
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;

public class DialerInput extends Activity implements OnClickListener {
EditText c_name;
EditText c_number;
Button btn_save;

Cursor cursor;
ContactDataSource datasource;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.input);
datasource = new ContactDataSource(this);
//datasource.open();
c_name = (EditText) findViewById(R.id.c_name);
c_number = (EditText) findViewById(R.id.c_number);
btn_save = (Button) findViewById(R.id.btn_save);
btn_save.setOnClickListener(this);

// datasource.createTable();
}

@Override
public void onClick(View v) {
String numbers = c_number.getText().toString();

String split = "-";
String[] numberArr = numbers.split(split);
String user_name = c_name.getText().toString();
String[] contacts = new String[numberArr.length / 2];
String[] delayTime = new String[numberArr.length / 2];
int j = 0;
for (int i = 0; i < numberArr.length; i++) {
if (i % 2 == 0) {
contacts[j] = numberArr[i];

} else {
delayTime[j] = numberArr[i];
Log.d("\n********************** " + contacts[j] , " **** " + delayTime[j] + " *** " + user_name);
datasource.createContact(user_name, Double.parseDouble(contacts[j]),
Integer.parseInt(delayTime[j]));
j++;
}
}
/*for (int i = 0; i < contact.length; i++) {
System.out.println("\n" + contact[i]);
System.out.println("\t" + delayTime[i]);
}*/
Log.d("\n************************** COUNT == ", "" + datasource.count());
Intent intent = new Intent(DialerInput.this, ViewDetailsActivity.class);
startActivity(intent);
}

@Override
protected void onPause() {
datasource.close();
super.onPause();
}

@Override
protected void onResume() {
datasource.open();
super.onResume();
}
}

/******************* DBHelper.java **********************/

package com.confdial.android;

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

public class DBHelper extends SQLiteOpenHelper {
static final String DB_NAME = "ConferenceDailing.db";
private static final int DB_VERSION = 1;
public static class ContactTable {
static final String TABLE_NAME = "details";
static final String _ID = "_id";
static final String NAME = "name";
static final String CONTACTS = "contacts";
static final String DELAY_TIME = "delay_time";
public static final String CREATE_TABLE = "create table "
+ ContactTable.TABLE_NAME + "( " + _ID
+ " integer primary key autoincrement, " + NAME
+ " text not null," + CONTACTS
+ " double ," + DELAY_TIME
+ " integer );";
}

public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(String.format(
"CREATE TABLE %s ( %s INTEGER PRIMARY KEY AUTOINCREMENT, %s TEXT, %s double, %s integer )",
ContactTable.TABLE_NAME, ContactTable._ID, ContactTable.NAME,
ContactTable.CONTACTS, ContactTable.DELAY_TIME));

}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + ContactTable.TABLE_NAME);
}
}

/******************* ContactDataSource.java **********************/
package com.confdial.android;

import org.apache.http.impl.cookie.BasicDomainHandler;
import com.confdial.android.DBHelper.ContactTable;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class ContactDataSource {

private SQLiteDatabase db;
private DBHelper dbHelper;

public ContactDataSource(Context context) {
dbHelper = new DBHelper(context);
}

public void open() throws SQLException {
db = dbHelper.getWritableDatabase();
Log.d("/nDATABASE OPENED************", "OPENED");
}

public void close() {
dbHelper.close();
Log.d("/nDATABASE CLOSED************", "CLOSED");
}

public void createContact(String name, double contacts, int delay_time) {
ContentValues val = new ContentValues();
val.put("name", name);
val.put("contacts", contacts);
val.put("delay_time", delay_time);
try {
db.insert(ContactTable.TABLE_NAME, null, val);
Log.v("\nINSERT IN Employee table", "Inserted a row..\n");
} catch (SQLException e) {
Log.e(DBHelper.DB_NAME, e.toString());
}
}

public void createTable() {
db.execSQL(DBHelper.ContactTable.CREATE_TABLE);
}

public Cursor getAllContacts(Activity activity) {
String[] from = { ContactTable._ID, ContactTable.NAME,
ContactTable.CONTACTS, ContactTable.DELAY_TIME };
String order = ContactTable._ID;
Cursor cursor = db.query(ContactTable.TABLE_NAME, from, null, null,
null, null, order);
activity.startManagingCursor(cursor);
return cursor;
}
public int count() {
return (int) DatabaseUtils.queryNumEntries(db,
DBHelper.ContactTable.TABLE_NAME);
}
}

/******************* ViewDetailsActivity.java **********************/

package com.confdial.android;

import com.confdial.android.DBHelper.ContactTable;

import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;

public class ViewDetailsActivity extends ListActivity{
Cursor cursor;
ContactDataSource datasource;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
datasource = new ContactDataSource(this);
datasource.open();

cursor = datasource.getAllContacts(this);
String contact = ContactTable.CONTACTS;
String[] from = new String[] { ContactTable.NAME , contact, ContactTable.DELAY_TIME };
int[] to = new int[] { R.id.name, R.id.contacts , R.id.d_time};
ListAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.list_item, cursor,
from, to);
Log.d("\n ************ VIEW ************** ", ContactTable.CONTACTS + "********** " + contact );
setListAdapter(mAdapter);
}
@Override
protected void onPause() {
datasource.close();
super.onPause();
}

@Override
protected void onResume() {
datasource.open();
super.onResume();
}
}

/******************* gradient_box.xml **********************/

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#88dddd"
android:endColor="#44bbcc"
android:angle="45"/>
<padding android:left="7dp"
android:top="7dp"
android:right="7dp"
android:bottom="7dp" />
<corners android:radius="8dp" />
</shape>


/******************* main.xml **********************/

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="220dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:background="@drawable/gradient_box"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="Conference Dialing"
android:textColor="#ffffff"
android:textSize="18sp"
android:textStyle="bold"
android:typeface="monospace" />

<Button
android:id="@+id/btn_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Start.."
android:layout_marginTop="10dp"
/>

</LinearLayout>

/******************* input.xml **********************/

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_gravity="center"
android:background="@drawable/gradient_box"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Name: "
android:textColor="#ffffff"
android:textSize="18sp"
android:textStyle="bold"
android:typeface="monospace" />

<EditText
android:id="@+id/c_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Contact: "
android:textColor="#ffffff"
android:textSize="18sp"
android:textStyle="bold"
android:typeface="monospace" />

<EditText
android:id="@+id/c_number"
android:layout_width="fill_parent"
android:layout_height="100dp" />

<Button
android:id="@+id/btn_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:layout_gravity="center"
android:layout_marginTop="10dp"
/>
</LinearLayout>


/******************* list_item.xml **********************/

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" >
</TextView>

<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/contacts"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" >
</TextView>

<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/d_time"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" >
</TextView>

</LinearLayout>






Monday, 9 April 2012

XML parsing in Android


SAX PARSING


SAX is an abbreviation for “Simple API for XML”, and it is a very powerful tool for reading XML.


Advantages 
1. low memory footprint.
2. They parse each line of XML data at a time and consequently do not need to load the entire XML document into memory prior to making the data accessible.
3. This is a significant boost to performance, and this really becomes visible when working with large XML documents.

Disadvantages 
1. You must define an event-driven API that will respond to each element as it is received.
2. This can become time consuming to build, but if you are willing to spend a little extra time to get it right, the outcome will be worthwhile.



DOM PARSING

package com.xmlparse.android;

import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

public class XMLParsingActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);

     LinearLayout layout = new LinearLayout(this);
     layout.setOrientation(1);
     TextView name[];
     TextView website[];
     TextView category[];

     try {
          URL url = new URL("http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
          DocumentBuilder db = dbf.newDocumentBuilder();
          Document doc = db.parse(new InputSource(url.openStream()));
          doc.getDocumentElement().normalize();

          NodeList nodeList = doc.getElementsByTagName("item");
          name = new TextView[nodeList.getLength()];
          website = new TextView[nodeList.getLength()];
          category = new TextView[nodeList.getLength()];

          for (int i = 0; i < nodeList.getLength(); i++) {
               Node node = nodeList.item(i);
               name[i] = new TextView(this);
               website[i] = new TextView(this);
               category[i] = new TextView(this);
               Element fstElmnt = (Element) node;

               NodeList nameList = fstElmnt.getElementsByTagName("name");
               Element nameElement = (Element) nameList.item(0);
               nameList = nameElement.getChildNodes();
               name[i].setText("Name = " + ((Node) nameList.item(0)).getNodeValue());
               
               NodeList websiteList = fstElmnt.getElementsByTagName("website");
               Element websiteElement = (Element) websiteList.item(0);
               websiteList = websiteElement.getChildNodes();
               website[i].setText("Website = " + ((Node)                        websiteList.item(0)).getNodeValue());
               category[i].setText("Website Category = "                websiteElement.getAttribute("category"));
               
               layout.addView(name[i]);
               layout.addView(website[i]);
               layout.addView(category[i]);
          }
     } catch (Exception e) {
          System.out.println("XML Pasing Excpetion = " + e);
     }
     setContentView(layout);
}
}

Thursday, 5 April 2012

JSON in Android



What is JSON? 


JSON (JavaScript Object Notation) is an independent data exchange format.
JSON is a very condense data exchange format.
Android includes the json.org libraries which allow to work easily with JSON files.
In JSON a data structure is a key / value pair.
The key is a string, the value can be a numerical or boolean or an object.
Lists are one or more values surrounded by [] and separated by ",".
An object is a set of key / name pairs which starts with "{" and ends with "}".
Binary values are not supported.
JSON is a subset of the JavaScript Specification (ECME-Script) and is therefore directly in JavaScript.

An example JSON might look like the following.

{
 firstName:'Lars',
 lastName:'Vogel',
 address: {
  street:'Examplestr.',
  number: '31'
 }
}






Difference between Handler and Asynctask in Android


Tuesday, 3 April 2012

Handler in Android


Handler
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.
        Each Handler instance is associated with a single thread and that thread's message queue.
        When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on,
it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

uses for a Handler
 (1) to schedule messages and runnables to be executed as some point in the future;
 (2) to enqueue an action to be performed on a different thread than your own.

Schedule msgs by the methods
1. post(Runnable),
2. postAtTime(Runnable, long),
3. postDelayed(Runnable, long),
4. sendEmptyMessage(int),
5. sendMessage(Message),
6. sendMessageAtTime(Message, long),
7. sendMessageDelayed(Message, long)


Data Storage in Android


DATA STORAGES:
===============

1. Shared Preferences
             Store private primitive data in key-value pairs.
             The data will still be available in the device even if your application is killed.
             Types of data that can be saved are booleans, floats, ints, longs, and strings.
             The stored data can be used in different activity of your application.

2. Internal Storage (files)
            Store private data on the device memory.
            You can save files directly on the device's internal storage.
            By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user).
           When the user uninstalls your application, these files are removed.

3. External Storage (SD card)
            Store public data on the shared external storage.
            Files saved to the external storage are world-readable and can be modified by the user when they enable
            USB mass storage to transfer files on a computer.

4. SQLite Databases
             Store structured data in a private database.
             It is simply stored in a .db file, and accessed and queried through a simple library within the application.
            It is very quick and convenient for smaller applications, like Android apps.
           
5. Network Connection
             Store data on the web with your own network server.

             To do network operations, use classes in the following packages:
                 java.net.*
                 android.net.*