Monday 18 March 2013

XML Parsing in Android

XML Parsing is quite easy in Andriod with the help of Parser Class

public class AndroidXMLParsingActivity extends Activity{




    // All static variables
    static final String URL = "http://api.androidhive.info/pizza/?format=xml";
    // XML node keys
    static final String KEY_ITEM = "item"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_NAME = "name";
    static final String KEY_COST = "cost";
    static final String KEY_DESC = "description";

    ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String,String>>();

    private ListAdapter adapter;
    private XMLParser parser;
    private String xml;
    private Document doc;
    ProgressBar pb;
   
   
   
   



    //background running code here

    public class backgroundLoadListView extends    AsyncTask<Void, Void, Void> {

        @Override
        protected void onPostExecute(Void result) {
       
            pb.setVisibility(View.GONE);
                       
            NodeList nl = doc.getElementsByTagName(KEY_ITEM);
            // looping through all item nodes <item>
            for (int i = 0; i < nl.getLength(); i++) {
                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();
                Element e = (Element) nl.item(i);
                // adding each child node to HashMap key => value

                map.put(KEY_ID, "ID id:" +parser.getValue( e, KEY_ID));
                map.put(KEY_NAME, "Name" + parser.getValue( e, KEY_NAME));
                map.put(KEY_COST, "Rs." + parser.getValue( e, KEY_COST));
                map.put(KEY_DESC, "Desc:  "+ parser.getValue( e, KEY_DESC));



                // adding HashList to ArrayList
                menuItems.add(map);

            }
            getXML();

        }
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
           
           
            pb.setVisibility(View.VISIBLE);
           
           
//             builder = new AlertDialog.Builder(this);
//            builder.setMessage("Dowmloading?").setPositiveButton("Yes", dialogClickListener)
//                .setNegativeButton("No", dialogClickListener).show();

        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            parser = new XMLParser();
            xml = parser.getXmlFromUrl(URL);
            doc = parser.getDomElement(xml);
            return null;
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pb= (ProgressBar)findViewById(R.id.progressBar1);


        backgroundLoadListView obj = new backgroundLoadListView();
        obj.execute();



    }


    public void getXML(){
        //    setListAdapter(adapter);
        adapter = new SimpleAdapter(this, menuItems,
                R.layout.liststyle,
                new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
                R.id.name, R.id.description, R.id.cost });



        // selecting single ListView item
        ListView lv = (ListView)findViewById(R.id.listView1);
        lv.setAdapter(adapter);
        // listening to single listitem click
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
                String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
                String description = ((TextView) view.findViewById(R.id.description)).getText().toString();

                Toast.makeText(getApplicationContext(), ""+name, Toast.LENGTH_SHORT).show();

            }
        });
    }
}


Parsing Class :- XMLParser.java

public class XMLParser {

    public String getXmlFromUrl(String url) {
        String xml = null;

        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return xml;
    }

    public Document getDomElement(String xml){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is);

        } catch (ParserConfigurationException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (SAXException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (IOException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        }

        return doc;
    }

    public String getValue(Element item, String str) {
        NodeList n = item.getElementsByTagName(str);
        return this.getElementValue(n.item(0));
    }

    public final String getElementValue( Node elem ) {
        Node child;
        if( elem != null){
            if (elem.hasChildNodes()){
                for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                    if( child.getNodeType() == Node.TEXT_NODE  ){
                        return child.getNodeValue();
                    }
                }
            }
        }
        return "";
    }

}










Resource File :- liststyle.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:padding="5dp"
    android:background="#00ffee" >
        
    <ImageView
        android:id="@+id/productimage"
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:background="#11ddcc"
   />
    <LinearLayout
        android:id="@+id/layoutvertical"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:orientation="vertical"
        android:background="#0011FF"
        android:paddingLeft="5dp"
        android:layout_marginLeft="5dp"
        >      
    <TextView
        android:id="@+id/name"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:textColor="#ffffff"
       
        />
    <TextView
        android:id="@+id/description"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:textColor="#ffffff"
       
        />
    <TextView
        android:id="@+id/cost"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:textColor="#ffffff"
        />     
       
    </LinearLayout>
   
   

</LinearLayout>


activity_mail.xml
<RelativeLayout 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" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
>
    </ListView>

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="184dp"
        android:layout_marginLeft="125dp"
       
         />
       

</RelativeLayout>
Don't Forget to add Permission for internet in the Manifest File
XML Source

Here is the output

Tuesday 12 March 2013

What is SQLite & its Architecture?

SQLite is an open Source Database which is embedded into android. SQLite support standard relational database feature like SQL syntax, transactions and prepared statements. It requires very  little memory at runtime(250 KByte).

SQLite Architecture

the package android.database contain all general classes for working with databases android.database.sqlite contain the SQLite specific classes.

SQLite Open Helper :- To create and upgrade a database in your Android application you usually subclass SQLite OpenHelper. In the constructor of your subclass you call the super() method of SQLIteOpenHelper, specifying the database name and the current address version.

onCreate() is called by the framework, if the database does not exits.

onUpgrade() is called , if the database version is increased in your application code, This method allow you to upgrade the database schema.

Both methods receive an SQLite Database object as parameter which represents the database.

SQLiteOpenHelper provides the methods getReadableDatabase(0 and getWriteableDatabase(0 to get access to an SQLiteDatabase object either in read or write mode.

The Database tables should use the Identifier _id for the primary key of the table. It is the best practice to create a separate class per table.The class define static onCreate(0 and onUpgrade() method.

SQLite Database :- is a base class for working with a SQLite database in Android and provides method to open, query , update and close the database.

SQLiteDatabase provides the insert(), update() and delete() methods. It provide the exeeSQL() method , which allows to execute SQL statement directly.

The object contain values allows to define Key/values . The "Key" represent the table column identifier and the "value" represents the content for the table record in this column. Content values are used for inserts and updates of database queries.

Queries can be created via the rawQuery() and query() methods via the SQLiteQuerybuilder class.

rawQuery() directly accepts an SQLite select statement as input.

query() provides a structures interface for specifying the sql query,

SQLiteQueryBuilder is a convenience  class that helps to build SQL queries.

Paramaters od the query() method.

String dbName :- The table name to compile the query object against.

String [ ] columnName :- A list of which table columns to return. Passing "null" will return all accounts.

String whereClause :- where clause , i.e. filter for the selection of data , null will select all data.

String [ ] selectionArgs :- you may include ?s in the "where Clause". These placeholder wil get replaced by the values from the selectionArgs array.

String [ ] groupBy :- A filter declaring how to group rows , null will cause the rows to not be grouped.

String [ ] having :- Filters for the groups , null means no ordering.

String [ ] orderBy :- table columns which will be used to order the data, null means no ordering.

if a condition is not required you can pass null. For. Ex for the groupBy clause














Monday 11 March 2013

What is Android? Basic Compoments of Android and Intent.

Android :- is a stack of software for mobile device which includes an operating system, middleware and some more key application. The application executes within its own process and its own instance of dalvik virtual machine.Many virtual machine run efficiently by a DVM device. DVM executes Java languages byte code which later transform into .dex format files.


Basic Components of Android Application

1.) Service :- like network operations.

2.)  Intent : - to perform inter-communication between activities and services.

3.) Resource Externalization :- such as strings and graphics.

4.)  Notification Signaling user :- light, sound, icon , notification , dialog etc

5.)  Content Provide :- They share data between application.

What is Intent?

A class which describes what a caller is dersireto do, The Caller will send this intent to Android's intent resolver , which find the most suitable activity for the intent .Ex Opening a PDF document is an intent.

Intent are asynchronous message which allow Android components to request functionality from other components of teh android system. Intent can be used to signal to the Android system that a certain event has occured.

Intent are send to the android system via a method call e.g. via the startActivity() method you can start activities. Depending upon how the intent was constructed the android system will run a receiver determination and determine possible components which can be started.

An intent can contain data.This data can be used by the receiver component. For e.g. you application can start a browser component via intent. As data it may send the URL to teh browser component which thisbrowser should open and display.

String url = "http://www.google.com";
Intent i = new Intent (Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

Explicit Intents :- Explicit intents explicitly defines the component which should be called by the Android system, by using the Java class as identifier.

Intent i = new Intent(this, ActivityTwo.class);
i.putExtra("value1","This value one for activity two");
iputExtra("value2","This value two for activity two");
startActivity(i);

Implicit Intents :- Emplicit intents specify the action which should be performed and optionally data which provides data for action.

Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://http://www.google.com"));
startActivity(i);

If these intents are send to the android system, it searches for all the components which are registered for the specific action and the Data Type.

Data Transfers :- An implicit intent contains the actions and optionally additional data.The receiveing component can get this information via the getAction() and getData() methods on the Intent object.

Intent Filters :- If an intent is send to the Android system, it will determine suitable application for this intents. If several components have been registered for this type of Intents, Android offers the user the choice to open of them.

This determination is based on IntentFilters. An IntentFilters specifies the type of Intent that an activity, service or broadcast Receiver can respond to. An Intent Filter declare the capabilities of the component .If specifies when an activity or service can do and what an activity or service can do and what tyoe of broadcasts or Receiver can handle. It allows a corresposnding component to receive intents of teh delcared type.

Intent Filters are typically defined via the AndroidManifest.xml file . For the BroadcastReceiver it is also possible to define by them in coding.An IntentFilters is defined by its category , action and data filters. Its can also contain additional metadata.

An android application is delivered in .apk format extension. ".apk file" is compressed Android Manifest xml with extension ".apk". It also include the application code (.dex files), resource files and other files which are compressed into a single .apk file.

Friday 8 March 2013

How to send an MMS Programmatically in Android

To send an MMS in Android , we'll use intent . Here is the code snippet.

Android Layout File

Layout File Name :- activity_main.xml

<RelativeLayout 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"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/et_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="39dp"
        android:layout_marginTop="22dp"
        android:ems="10"
        android:hint="Enter Number"
        android:inputType="number"
        android:singleLine="true" />

       

    <EditText
        android:id="@+id/et_msg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/et_number"
        android:layout_below="@+id/et_number"
        android:layout_marginTop="24dp"
        android:ems="10"
        android:lines="3"
        android:hint="Enter Message Body" />

    <Button
        android:id="@+id/btn_send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/et_msg"
        android:layout_centerVertical="true"
        android:text="Send MMS" />

</RelativeLayout>






*************************** .java File ********************

Class Name:- MainACtivity.java

Package Name:-  com.dummymms

package com.dummymms;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements OnClickListener {
   
    Button btnmms;
    EditText etnum, etmsg;
   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        etnum=(EditText)findViewById(R.id.et_number);
        etmsg=(EditText)findViewById(R.id.et_msg);
        btnmms=(Button)findViewById(R.id.btn_send);
        btnmms.setOnClickListener(this);
    }

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

    @Override
    public void onClick(View v) {
        try {
             //Uri uri = Uri.parse("content://media/external/images/media/1");
           

        //     Uri uri = Uri.parse("file://mnt/sdcard/test.jpg");
           

           
            Uri uri = Uri.parse("file://"+Environment.getExternalStorageDirectory()+"/test.png");
            Intent i = new Intent(Intent.ACTION_SEND);
            i.putExtra("address",etnum.getText().toString());
            i.putExtra("sms_body",etmsg.getText().toString());
            i.putExtra(Intent.EXTRA_STREAM,"file:/"+uri);
            i.setType("image/png");
            startActivity(i);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
       
    }

}






Make sure to add permission in the Manifest File


<uses-permission android:name="android.permission.RECEIVE_MMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />



Download the source code here

Wednesday 27 February 2013

What is Sticky intent?

A normal broadcast Intent is not available anymore after is was send and processed by the system. If you use the sendStickyBroadcast(Intent) method, the Intent is sticky, meaning the Intent you are sending stays around after the broadcast is complete.

You can can retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter) . This works also for a null BroadcastReceiver.

In all other ways, this behaves the same as sendBroadcast(Intent).

The Android system uses sticky broadcast for certain system information. For example the battery status is send as sticky Intent and can get received at any time. The following example demonstrates that.


// Register for the battery changed event
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

/ Intent is sticky so using null as receiver works fine
// return value contains the status
Intent batteryStatus = this.registerReceiver(null, filter);

// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING
  || status == BatteryManager.BATTERY_STATUS_FULL;

boolean isFull = status == BatteryManager.BATTERY_STATUS_FULL;

// How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC; 

Sticky Broadcast Intents typically require special permissions. 

AIDL - Android Interface Definition Language

 
AIDL – Android Interface Definition Language is an IDL language used to generate code that enables two process on an Android-powered device to talk using inter process communication(IPC). If you have code in one process that needs to call on an object on another process, you would use AIDL to generate code to marshall the parameters.

Implementing IPC using AIDL

To implement an IPC service using AIDL

  1. Create your .aidl file – This file defines an interface that defines the methods and fields available to a client.
  2. Add the .aidl file to your make file. The ADT plugin for eclipse manages this for you. Android includes the compiler called AIDL , in the tools/directory.
  3. Implement your interface methods – The AIDL compiler creates an interface in the java programming language from your AIDL interface. This interface has an inner abstract class named stub that inherits the interface . You must create a class that extends your interface stub and implements the methods you declared in your .aidl file.
  4. Expose your interface to clients – If you're writing a service , you should extend service and override service onBind(intent) to retain an instance of your class that implements your interface.

What is a Service in Android with Demo

 
Service : A Service is a application component that can perform long running operations in background and does not provide a user interface.A service will continue to run in background even if the user switches to another application.

A service can be of two forms:-

  1. Started – A service is started when an application component start it by calling startservice().Once started, a service can run un background indefinitely , even if the component it is destroyed.
  2. Bound – A service is bound when an application component binds to ot by calling bindServices(). A bound service offers a client server interface that allow components to interact with the service, send requests , get results and even do so across process with Inter process Communication(IPC). A bound service runs as long as another application component is bound to it.

Feature of a Service
  1. A facility for the application to tell the system about something it want to be doing in the background.This corresponds to call to Context.startService(), which ask the system to schedule work for the service, to be run until the service or someone else explicitly stop it.
  2. A facility for an application to expose some of the functionality to other application . This corresponds to calls to context.bindService(), which allows a long standing connectivity to be made to the service in order to interact with it.


    To create a application to run in the background of other current activities, one needs to create a Service. The Service can run indefinitely (unbounded) or can run at the lifespan of the calling activity(bounded).

    Please note that a Service has a different lifecycle than activities therefore have different methods. But to begin a service in the application a call to startService() which envokes the service onCreate() method and onStart() beginning running the service. - See more at: http://marakana.com/forums/android/examples/60.html#sthash.1gmztZyv.dpuf
     
    To create a application to run in the background of other current activities, one needs to create a Service. The Service can run indefinitely (unbounded) or can run at the lifespan of the calling activity(bounded).

    Please note that a Service has a different lifecycle than activities therefore have different methods. But to begin a service in the application a call to startService() which envokes the service onCreate() method and onStart() beginning running the service.


    Download the source code here

    Please note that a Service has a different lifecycle than activities therefore have different methods. But to begin a service in the application a call to startService() which envokes the service onCreate() method and onStart() beginning running the service. - See more at: http://marakana.com/forums/android/examples/60.html#sthash.1gmztZyv.dpuf

    To create a application to run in the background of other current activities, one needs to create a Service. The Service can run indefinitely (unbounded) or can run at the lifespan of the calling activity(bounded).

    Please note that a Service has a different lifecycle than activities therefore have different methods. But to begin a service in the application a call to startService() which envokes the service onCreate() method and onStart() beginning running the service. - See more at: http://marakana.com/forums/android/examples/60.html#sthash.1gmztZyv.dpuf

    To create a application to run in the background of other current activities, one needs to create a Service. The Service can run indefinitely (unbounded) or can run at the lifespan of the calling activity(bounded).

    Please note that a Service has a different lifecycle than activities therefore have different methods. But to begin a service in the application a call to startService() which envokes the service onCreate() method and onStart() beginning running the service. - See more at: http://marakana.com/forums/android/examples/60.html#sthash.1gmztZyv.dpuf