Thursday, May 19, 2011

Android Expandable ListView

A view that shows items in a vertically scrolling two-level list. This differs from the ListView by allowing two levels: groups which can individually be expanded to show its children. The items come from the ExpandableListAdapter associated with this view.

Steps to develop Expandable List :
-> Initialize the Expandable List View
-> Construct the Expandable List Adapter
-> Set the Adapter to Expandable List View


Initialize the Expandable List View
 ExpandableListView explvList;
 explvList = (ExpandableListView)findViewById(R.id.explvList);
Construct the Expandable List Adapter 
    public class ExpLvAdapter extends BaseExpandableListAdapter
    {
        @Override
        public Object getChild(int groupPosition, int childPosition)
        {           
            return childPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition)
        {
           
            return childPosition;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
        {
            TextView tv = null;
            tv = new TextView(Home.this);
            tv.setText("ChildView "+groupPosition);           
            tv.setPadding(30, 0, 0, 0);
            return tv;
        }
        @Override
        public int getChildrenCount(int groupPosition)
        {   
            return children[groupPosition].length;
        }

        @Override
        public Object getGroup(int groupPosition)
        {
            return groupPosition;
        }

        @Override
        public int getGroupCount()
        {
           
            return 2;
        }

        @Override
        public long getGroupId(int groupPosition)
        {
           
            return groupPosition;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                View convertView, ViewGroup parent)
        {
            TextView tv = null;
            tv = new TextView(Home.this);
            tv.setText("GroupView "+groupPosition);           
            tv.setPadding(30, 0, 0, 0);
            return tv;
        }

        @Override
        public boolean hasStableIds()
        {
            return false;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition)
        {
           
            return true;
        }
    }


Set the Adapter to Expandable List View
explvList.setAdapter(new ExpLvAdapter());
Output:

Wednesday, May 18, 2011

Starting an Android Service at Boot time

Always a service is started by us manually that means it was not start by default. If we switch off the mobile then all the running services will stop.

For example if we are running a service. If we reboot the mobile then all the running services are stopped. So we have to run the service again.

By default android broadcasts a intent (android.intent.action.BOOT_COMPLETED)at the time of booting. So we have to receive that and in that we again start a service.

This should be accomplished by using Broad Cast Receiver.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class BootBroadcastReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
Log.i("Receiver Called.", "start the service.");
}
}
We have to add this receiver in the manifast.xml. The code is as follows.
<!-- Reciver -->
<receiver android:name=".BootBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>

Tuesday, May 17, 2011

Android Service

A Service is a Android Class used to run a process in background to avoid Application Not Responding errors.
Example:
Home.java:
package com.sercivedemo.activities;

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 Home extends Activity
{
    Button btnStartService, btnStopservice;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        btnStartService = (Button)findViewById(R.id.btnStartService);
        btnStopservice = (Button)findViewById(R.id.btnStopservice);
       
        btnStartService.setOnClickListener(new OnClickListener()
        {          
            @Override
            public void onClick(View arg0)
            {
                startService(new Intent(Home.this, ServiceEx.class));
            }
        });
       
        btnStopservice.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                stopService(new Intent(Home.this, ServiceEx.class));
            }
        });
    }
}

ServiceEx.java:
package com.sercivedemo.activities;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class ServiceEx extends Service
{   
    Timer objTimer;
    @Override
    public void onCreate()
    {       
        super.onCreate();
        Log.e("Service :", "onCreate()");
       
        //Do the process here
     }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        Log.e("Service :", "onDestroy()");
    }

    @Override
    public void onStart(Intent intent, int startId)
    {
        super.onStart(intent, startId);
        Log.e("Service :", "onStart()");
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }
}
main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
   
    <Button
        android:layout_width="wrap_content"
        android:id="@+id/btnStartService"
        android:text="StartService"
        android:layout_height="wrap_content">
    </Button>
   
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnStopservice"
        android:text="StopService">
    </Button>   
   
</LinearLayout>

Android Launching Camera and attach the image to image view


public void takePhoto()
{
        //Intent to launch camara
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
       
        //Uri creattion to strore images
        mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory()+ "/" +   String.valueOf(System.currentTimeMillis())+ ".jpg"));
                   
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);

        startActivityForResult(intent, 1);

}


protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent)
{
       super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
      
       if(requestCode == 1)
       {
           if(resultCode == RESULT_OK)
           {
                try
               {
                   ivPhoto.setBackgroundResource(0);
                   ivPhoto.setImageBitmap(BitmapFactory.decodeStream(new FileInputStream(new File(mImageCaptureUri.getPath()))));
               }
               catch (FileNotFoundException e)
               {               
                   e.printStackTrace();
               }
           }
           else if(resultCode == RESULT_CANCELED)
           {
               Log.d("Result: ", "Launch Cancelled.");
           }
     }
}

Call takePhoto() in the button click. 

Note: 

In the manifast.xml we have to add permissions.android.permission.WRITE_EXTERNAL_STORAGE

android.hardware.camera

Output:










Monday, May 16, 2011

Pick Image from Gallery set to Image View

package com.pickimagefromgal.activities;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class Home extends Activity
{
    Button btnGal;
    ImageView ivGalImg;
    Bitmap bmp;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        btnGal         =     (Button)findViewById(R.id.btnGallary);
        ivGalImg     =     (ImageView)findViewById(R.id.ivImage);
       
        btnGal.setOnClickListener(new OnClickListener()
        {           
            @Override
            public void onClick(View arg0)
            {
                openGallery();               
            }
        });
    }
   
    private void openGallery()
    {
        Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, 1);
    }
   
  @Override
  protected void onActivityResult(int requestCode, int resultcode, Intent intent)
  {
      super.onActivityResult(requestCode, resultcode, intent);
     
      if (requestCode == 1)
      {
          if (intent != null && resultcode == RESULT_OK)
          {             
             
                Uri selectedImage = intent.getData();
               
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String filePath = cursor.getString(columnIndex);
                cursor.close();
             
                if(bmp != null && !bmp.isRecycled())
                {
                    bmp = null;               
                }
                               
                bmp = BitmapFactory.decodeFile(filePath);
                ivGalImg.setBackgroundResource(0);
                ivGalImg.setImageBitmap(bmp);             
          }
          else
          {
              Log.d("Status:", "Photopicker canceled");           
          }
      }
  }
}

main.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
   
    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/ivImage"
        android:background="@drawable/icon"   
        >
    </ImageView>
   
    <Button
        android:layout_width="wrap_content"
        android:text="Click To Open Gallary"
        android:id="@+id/btnGallary"
        android:layout_height="wrap_content">
    </Button>
   
</LinearLayout>

Manifast: 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.pickimagefromgal.activities"
      android:versionCode="1"
      android:versionName="1.0">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>


    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Home"
                  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>

Out Put:


Tuesday, May 10, 2011

Dom Parsing Example

 parse.xml :

<Books>
    <Book>
        <Name>Cryptography</Name>
        <Author>Harish</Author>
        <Price>$200</Price>
    </Book>
    <Book>
        <Name>Android</Name>
        <Author>Harish</Author>
        <Price>$250</Price>
    </Book>
</Books>
Method to parse xml  using dom :
public HashMap doDomParsing(String strUrl, String strParent, String[] child)
{
       HashMap hmap, hmapchild = null;
       URL url;
       hmap = new HashMap();
       
       try
       {
           //url = new URL(strUrl);
           
           DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
           DocumentBuilder db = dbf.newDocumentBuilder();
          Document doc = db.parse(new InputSource(getClass().getResourceAsStream("/res/raw/parse.xml")));
           
           NodeList nodeList = doc.getElementsByTagName("item");
           for (int i = 0; i < nodeList.getLength(); i++)
           {
               
               Node node = nodeList.item(i);
               NodeList properties = node.getChildNodes();
               
               hmapchild = new HashMap();
               
               for(int j=0 ; j < properties.getLength() ; j++)
               {
                   Node property = properties.item(j);
                   String nodename = property.getNodeName();
                   Log.e("Node NAME", nodename);
                   
                   for(int inew =0 ;inew < child.length ; inew++)
                   {
                       if(nodename.equalsIgnoreCase(child[inew]))
                       {
                           hmapchild.put(nodename, property.getFirstChild().getNodeValue());
                       }
                   }
               }
               hmap.put(i, hmapchild);
           }
       }
       catch (Exception e)
       {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
       
       return  hmap;
}

For this method we have to pass three parameters.
URL
PARENT NODE
CHILDREN

For the above xml we are parsing local file presented at raw folder. so url is empty. 

Parent is Book
child array is {Name, Author, Price}


That's it. It will parse the data store the values in Hash Map and returns that Hash Map.

Monday, May 2, 2011

Passing Intent to Browser

Intent intent = new Intent("android.intent.action.VIEW", Uri.parse(stringurl));
startActivity(intent);