How to load a spinner with values from SQlite Database in android?

Here is a simple example showing how to load a database values in a spinner in android.

Spinner from SQLite

OK we will start.

This is the layout for the spinner row.
spinner_row.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation     =      "vertical"
    android:id="@+id/tv"
    android:layout_margin="10dp">   
</TextView>

This is the layout for the interface.

activity_main.xml

<LinearLayout 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"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textStyle="bold"
        android:text="Load DB values into Spinner"
         >
    </TextView>

    <Spinner
        android:id="@+id/spinner1"
        android:layout_below="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

</LinearLayout>

Now this is the MainActivity.java file that uses the spinner and the database.

package com.coderzheaven.loadspinnerfromdb;

import   java  .util  .ArrayList;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {

	SQLiteDatabase mydb;
	private   static String DBNAME = "PERSONS.db";
	private static String TABLE = "MY_TABLE";

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

		createTable();
		insertIntoTable();

		ArrayList<String> my_array = new ArrayList<String>();
		my_array = getTableValues();

		Spinner My_spinner = (Spinner) findViewById(R.id.spinner1);
		ArrayAdapter my_Adapter = new ArrayAdapter(this, R.layout.spinner_row,
				my_array);
		My_spinner.setAdapter(my_Adapter);
	}

	// CREATE TABLE IF NOT EXISTS
	public void createTable() {
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			mydb.execSQL("CREATE TABLE IF  NOT EXISTS " + TABLE
					+ " (ID INTEGER PRIMARY KEY, NAME TEXT, PLACE TEXT);");
			mydb.close();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error in creating table",
					Toast.LENGTH_LONG);
		}
	}

	// THIS FUNCTION INSERTS DATA TO THE DATABASE
	public void insertIntoTable() {
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('CODERZHEAVEN','GREAT INDIA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('ANTHONY','USA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('SHUING','JAPAN')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('JAMES','INDIA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('SOORYA','INDIA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('MALIK','INDIA')");
			mydb.close();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(),
					"Error in inserting into table", Toast.LENGTH_LONG);
		}
	}

	// THIS FUNCTION SHOWS DATA FROM THE DATABASE
	public ArrayList<String> getTableValues() {

		ArrayList<String> my_array = new ArrayList<String>();
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			Cursor allrows = mydb.rawQuery("SELECT * FROM " + TABLE, null);
			System.out.println("COUNT : " + allrows.getCount());

			if (allrows.moveToFirst()) {
				do {

					String ID = allrows.getString(0);
					String NAME = allrows.getString(1);
					String PLACE = allrows.getString(2);
					my_array.add(NAME);

				} while (allrows.moveToNext());
			}
			allrows.close();
			mydb.close();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error encountered.",
					Toast.LENGTH_LONG);
		}
		return my_array;
	}

}

Join the Forum discussion on this post

Note : Please remove the “span” tags from the post when you copy it.

Download the complete source code for this example from here.

Creating a custom Sliding GalleryView with Paging in android

This is a simple example showing A sliding Gallery in android. This example shows a sliding gallery with a paging Control and a changing page text which also indicate the page change.

Create a new project named “SlidingGallery” and copy this code into “SlidingGalleryDemo.java“.
My Activity name is “SlidingGalleryDemo.java” here.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class SlidingGalleryDemo extends Activity {
	
	Gallery ga;
	int width, height;
	LinearLayout linear;
	LinearLayout layout;
	Integer[] pics = {
			R.drawable.android_1,
			R.drawable.android_2,
    		R.drawable.android_3,
    		R.drawable.android_4,
    		R.drawable.android_5   
    };
	ImageView paging;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	 super.onCreate(savedInstanceState);
	     setContentView(R.layout.threemenu);
	     
	     layout = (LinearLayout) findViewById(R.id.imageLayout1);
	        
	     DisplayMetrics displaymetrics = new DisplayMetrics();
	     getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
	     width = displaymetrics.heightPixels;
	     height = displaymetrics.widthPixels;
			
	     for(int i=0; i<pics.length; i++)
         {
          	paging = new ImageView(this);
        	paging.setId(i);
        	paging.setBackgroundResource(R.drawable.unsel);
        	layout.addView(paging);
         }
	     
	     ga = (Gallery)findViewById(R.id.thisgallery);
	     ga.setAdapter(new ImageAdapter(this));
	     
	     ga.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) 
				{					
					System.out.println("SELECTED : " + arg2);
				}	        	
	        });
    }

    public class ImageAdapter extends BaseAdapter {

    	private Context ctx;
    	int imageBackground;
    	int pre=-1;
    	public ImageAdapter(Context c) {
			ctx = c;
		}

		public int getCount() {
    		
    		return pics.length;
    	}

    	public View getView(int arg0, View convertView, ViewGroup arg2) {

		     ImageView iv;
		     LinearLayout layoutnew = new LinearLayout(getApplicationContext());            
		     layoutnew.setOrientation(LinearLayout.VERTICAL);
		        
             if (convertView == null) 
             {
            	iv = new ImageView(ctx);
            	iv.setImageResource(pics[arg0]);
     			iv.setScaleType(ImageView.ScaleType.FIT_XY);
     			int temp =(int) (height/1.7f);
     			int temp_y = (int) ((3*temp)/2.0f);
     			iv.setLayoutParams(new Gallery.LayoutParams(temp,temp_y));
     			iv.setBackgroundResource(imageBackground);
             }
             else
             {
            	iv = (ImageView) convertView;
             }
             TextView tv = new TextView(ctx);
 			 tv.setText("Page " + (arg0+1));
 			 tv.setTextColor(0xFFFFFFFF);
 			 tv.setPadding(0, 15, 0, 0);
 		     tv.setTextSize(18);
 			 tv.setGravity(Gravity.CENTER); 
			 layoutnew.addView(iv);
			 layoutnew.addView(tv);
    		
    		return layoutnew;
    	}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			if(pre !=-1)
    		{
    			ImageView img = (ImageView) findViewById(pre);
    			img.setBackgroundResource(R.drawable.unsel);
    		}
    		ImageView img1 = (ImageView) findViewById(position);
    		img1.setBackgroundResource(R.drawable.sel);
    		this.pre = position;
    		return position;
		}
    }
}

Now create a new class and name it “GalleryCustom.java” which extends “Gallery” and copy this code into it.

package com.coderzheaven.pack;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Gallery;

public class GalleryCustom extends Gallery {

    public GalleryCustom(Context ctx, AttributeSet attrSet) 
    {
        super(ctx,attrSet);
    }

    @SuppressWarnings("unused")
	private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2)
    { 
           return e2.getX() > e1.getX(); 
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY){
      return true;  
    }
}

Now we will create the layout for the page. Copy this code to the main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:keepScreenOn="true"  
    android:background="@drawable/Hotpink">
    
    <LinearLayout 
	    android:layout_width="fill_parent"
	    android:id="@+id/imageLayout1"
	    android:layout_marginBottom="5dip"
	    android:layout_alignParentBottom="true"
	    android:gravity="center_horizontal|center_vertical"
	    android:orientation="horizontal"
	    android:layout_height="wrap_content">  
	 </LinearLayout>
	 
	<LinearLayout 
	    android:layout_width="fill_parent"
	    android:id="@+id/imageLayout"
	    android:gravity="center"
	    android:layout_alignParentTop="true"
	    android:layout_above="@+id/imageLayout"
	    android:layout_height="fill_parent" >
    
		<com.coderzheaven.pack.GalleryCustom
		    android:id="@+id/thisgallery"
		    android:spacing="60dip"
		    android:layout_width="fill_parent"
		    android:layout_height="wrap_content" />
		    
    </LinearLayout>
    
</RelativeLayout>

OK Its done. Now run the project and see the result.

Gallery 1

Gallery 1

Gallery 1

Gallery 1

Gallery 1

Please comment and share this post if you like it.

How to create a Custom Toggle Button in android?

Hello everyone…

In today’s tutorial I will show you how to create a custom toggle button in android. Often in our applications we don’t need a default toggle button, so I will show you how to change that to make a toggle button according to your need.

First I will create a fresh project named “CustomToggleButton” and name the main activity “CustomToggleButtonDemo”.

Now These are the two images that I am using to create the toggle button.

add icon

delete icon

First the layout file main.xml that contains the toggle button.

<?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"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<ToggleButton 
	android:background="@drawable/btn_toggle_bg"
	style="@style/OurThemeName" 
	android:checked="true"
	android:id="@+id/ToggleButton01" 
	android:layout_width="wrap_content" 
	android:layout_height="wrap_content">
</ToggleButton>

</LinearLayout>

This will create a toggle button.

Now we will make an xml that contains the resource definition that applies when the button toggles and the background of the button.
We will make the button background transparent and for toggle action we will create another xml that contains the “on” and “off” resource for the button.

Create a new file inside the drawable folder and name it “btn_toggle_bg.xml” and copy this code to it.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+android:id/background" android:drawable="@android:color/transparent" />
    <item android:id="@+android:id/toggle" android:drawable="@drawable/btn_toggle" />
</layer-list>

Now create another xml inside the drawable folder and name it “btn_toggle.xml” and it contains …

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/add_icon" />
    <item android:state_checked="false" android:drawable="@drawable/delete_icon" />
</selector>

This means that when the button is on(true) the image will be “add_icon.png” and when “off” the image will be “delete_icon.png”.

Now we are going to write a theme that is to be applied to the toggle button that overrides the default android theme.

Create a new file called “themes.xml” inside the strings folder and copy this code to it.

<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Overwrite the ToggleButton style -->
<style name="Widget.Button.Toggle" parent="android:Widget">
    <item name="android:background">@drawable/btn_toggle_bg</item>
    <item name="android:textOn">Add</item>
    <item name="android:textOff">Del</item>
    <item name="android:disabledAlpha">?android:attr/disabledAlpha</item>
</style>

<style name="OurThemeName"  parent="@android:Theme.Black">
    <item name="android:buttonStyleToggle">@style/Widget.Button.Toggle</item>
      <item name="android:textOn"></item>
    <item name="android:textOff"></item>
</style>
</resources>

Please look at the main.xml file where this theme has been applied.

Here

<ToggleButton 
	android:background="@drawable/btn_toggle_bg"
	<strong>style="@style/OurThemeName" </strong>
	android:checked="true"
	android:id="@+id/ToggleButton01" 
	android:layout_width="wrap_content" 
	android:layout_height="wrap_content">
</ToggleButton>

OK now our custom toggle button is ready. Go on and run it.

Custom toggle button

Custom toggle button

Actually we dont need the activity java file because everything can be done in the xml itself.

Download the complete source code from here.

Using Tabbars in ANDROID, A Simple Example……….

This is a simple example showing how to use tabbars in ANDROID.
First create a new project and copy this code to it.

package com.coderzheaven;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

public class tabbar extends TabActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /** TabHost will have Tabs */
        TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);

        /** TabSpec used to create a new tab.
         * By using TabSpec only we can able to setContent to the tab.
         * By using TabSpec setIndicator() we can set name to tab. */

        /** tid1 is firstTabSpec Id. Its used to access outside. */
        TabSpec firstTabSpec = tabHost.newTabSpec("tab_id1");
        TabSpec secondTabSpec = tabHost.newTabSpec("tab_id2");
        TabSpec thirdTabSpec = tabHost.newTabSpec("tab_id3");

        /** TabSpec setIndicator() is used to set name for the tab. */
        /** TabSpec setContent() is used to set content for a particular tab. */
        firstTabSpec.setIndicator("First").setContent(new Intent(this,FirstTab.class));
        secondTabSpec.setIndicator("Second ").setContent(new Intent(this,SecondTab.class));
        thirdTabSpec.setIndicator("Third").setContent(new Intent(this,ThirdTab.class));

        /** Add tabSpec to the TabHost to display. */
        tabHost.addTab(firstTabSpec);
        tabHost.addTab(secondTabSpec);
        tabHost.addTab(thirdTabSpec);

    }
}

Now create three another java files by right clicking the src folder and name it FirstTab.java, SecondTab.java, ThirdTab.java.

Now copy the following code to FirstTab.java.

package com.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class FirstTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* First Tab Content */
		TextView textView = new TextView(this);
		textView.setText("First Tab");
		setContentView(textView);
	}
}

SecondTab.java

package com.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class SecondTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Second Tab Content */
		TextView textView = new TextView(this);
		textView.setText("Second Tab");
		setContentView(textView);

	}
}
 

Now ThirdTab.java.

package com.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ThirdTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Second Tab Content */
		TextView textView = new TextView(this);
		textView.setText("Third Tab");
		setContentView(textView);

	}
}
 

Main.xml file

<?xml version="1.0" encoding="utf-8"?>
<TabHost android:layout_width="fill_parent"
	android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@android:id/tabhost">
	<LinearLayout android:id="@+id/LinearLayout01"
		android:orientation="vertical" android:layout_height="fill_parent"
		android:layout_width="fill_parent">
		<TabWidget android:id="@android:id/tabs"
			android:layout_height="wrap_content" android:layout_width="fill_parent"></TabWidget>
		<FrameLayout android:id="@android:id/tabcontent"
			android:layout_height="fill_parent" android:layout_width="fill_parent"></FrameLayout>
	</LinearLayout>
</TabHost>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="tabbar.pack"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".FirstTab" />
	<activity android:name=".SecondTab" />
    <activity android:name=".ThirdTab" />
        <activity android:name=".tabbar"
                  android:label="TabBar Demo">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
TabBar in ANDROID

TabBar in ANDROID Demo

You can place anything in each tab by setting the contentView or dynamically adding controls.
You can do anything with this tabbar by editing the xml, like placing it below or giving images for each tab etc etc….

Please leave your valuable comments…

Image transition animation in Android

Hello all…

I have shown a lot of examples of animations in android.
Today I will show you how to show an image transition animation between two images. For that you have to create an xml named “expand_collapse.xml” inside the res/drawable folder.

The contents of “expand_collapse.xml” are

<transition xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:drawable="@drawable/android_1" />
      <item android:drawable="@drawable/android_2" />
</transition>

Now in the main.xml place an imageView to show the transition

<?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="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/toggle_image"
    />
</LinearLayout>

Now in the main java file I will show you how to apply this transition.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.widget.ImageView;

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

        Resources res = getApplicationContext().getResources();
        TransitionDrawable transition = (TransitionDrawable) res.getDrawable(R.drawable.expand_collapse);
        ImageView image = (ImageView) findViewById(R.id.toggle_image);
        image.setImageDrawable(transition);

        transition.startTransition(5000);
   }
}

How to remove a view in your xml layout file using program?

Hello everyone,
this is a simple example showing how to remove a view in android that is created using your xml file.

This is the xml file that contains a TextView

<?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"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="CoderzHeaven"
    android:id="@+id/tv"
    />
</LinearLayout>

Here is the java code for removing this view

package pack.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

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

        View tv= (View)findViewById(R.id.tv);
        ((LinearLayout)tv.getParent()).removeView(tv);
    }
}

After running this program you will not see the TextView that was in your layout file.
Please leave your valuable comments on this post.

ANDROID Tabbars Example……..

This is a simple example showing how to use tabbars in ANDROID.
First create a new project and copy this code to it.

package com.coderzheaven;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

public class tabbar extends TabActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /** TabHost will have Tabs */
        TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);

        /** TabSpec used to create a new tab.
         * By using TabSpec only we can able to setContent to the tab.
         * By using TabSpec setIndicator() we can set name to tab. */

        /** tid1 is firstTabSpec Id. Its used to access outside. */
        TabSpec firstTabSpec = tabHost.newTabSpec("tab_id1");
        TabSpec secondTabSpec = tabHost.newTabSpec("tab_id2");
        TabSpec thirdTabSpec = tabHost.newTabSpec("tab_id3");

        /** TabSpec setIndicator() is used to set name for the tab. */
        /** TabSpec setContent() is used to set content for a particular tab. */
        firstTabSpec.setIndicator("First").setContent(new Intent(this,FirstTab.class));
        secondTabSpec.setIndicator("Second ").setContent(new Intent(this,SecondTab.class));
        thirdTabSpec.setIndicator("Third").setContent(new Intent(this,ThirdTab.class));

        /** Add tabSpec to the TabHost to display. */
        tabHost.addTab(firstTabSpec);
        tabHost.addTab(secondTabSpec);
        tabHost.addTab(thirdTabSpec);

    }
}

Now create three another java files by right clicking the src folder and name it FirstTab.java, SecondTab.java, ThirdTab.java.

Now copy the following code to FirstTab.java.

package com.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class FirstTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* First Tab Content */
		TextView textView = new TextView(this);
		textView.setText("First Tab");
		setContentView(textView);
	}
}

SecondTab.java

package com.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class SecondTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Second Tab Content */
		TextView textView = new TextView(this);
		textView.setText("Second Tab");
		setContentView(textView);

	}
}

Now ThirdTab.java.

package com.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ThirdTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Second Tab Content */
		TextView textView = new TextView(this);
		textView.setText("Third Tab");
		setContentView(textView);

	}
}

Main.xml file

<?xml version="1.0" encoding="utf-8"?>
<TabHost android:layout_width="fill_parent"
	android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@android:id/tabhost">
	<LinearLayout android:id="@+id/LinearLayout01"
		android:orientation="vertical" android:layout_height="fill_parent"
		android:layout_width="fill_parent">
		<TabWidget android:id="@android:id/tabs"
			android:layout_height="wrap_content" android:layout_width="fill_parent"></TabWidget>
		<FrameLayout android:id="@android:id/tabcontent"
			android:layout_height="fill_parent" android:layout_width="fill_parent"></FrameLayout>
	</LinearLayout>
</TabHost>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.coderzheaven"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".FirstTab" />
	<activity android:name=".SecondTab" />
    <activity android:name=".ThirdTab" />
        <activity android:name=".tabbar"
                  android:label="TabBar Demo">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

You can place anything in each tab by setting the contentView or dynamically adding controls.
You can do anything with this tabbar by editing the xml, like placing it below or giving images for each tab etc etc….

Please leave your valuable comments…

Using Tabbars in ANDROID, A Simple illustration……….

This is a simple example showing how to use tabbars in ANDROID.
First create a new project and copy this code to it.

package com.coderzheaven;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

public class tabbar extends TabActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /** TabHost will have Tabs */
        TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);

        /** TabSpec used to create a new tab.
         * By using TabSpec only we can able to setContent to the tab.
         * By using TabSpec setIndicator() we can set name to tab. */

        /** tid1 is firstTabSpec Id. Its used to access outside. */
        TabSpec firstTabSpec = tabHost.newTabSpec("tab_id1");
        TabSpec secondTabSpec = tabHost.newTabSpec("tab_id2");
        TabSpec thirdTabSpec = tabHost.newTabSpec("tab_id3");

        /** TabSpec setIndicator() is used to set name for the tab. */
        /** TabSpec setContent() is used to set content for a particular tab. */
        firstTabSpec.setIndicator("First").setContent(new Intent(this,FirstTab.class));
        secondTabSpec.setIndicator("Second ").setContent(new Intent(this,SecondTab.class));
        thirdTabSpec.setIndicator("Third").setContent(new Intent(this,ThirdTab.class));

        /** Add tabSpec to the TabHost to display. */
        tabHost.addTab(firstTabSpec);
        tabHost.addTab(secondTabSpec);
        tabHost.addTab(thirdTabSpec);

    }
}

Now create three another java files by right clicking the src folder and name it FirstTab.java, SecondTab.java, ThirdTab.java.

Now copy the following code to FirstTab.java.

package com.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class FirstTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* First Tab Content */
		TextView textView = new TextView(this);
		textView.setText("First Tab");
		setContentView(textView);
	}
}

SecondTab.java

package com.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class SecondTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Second Tab Content */
		TextView textView = new TextView(this);
		textView.setText("Second Tab");
		setContentView(textView);

	}
}
 

Now ThirdTab.java.

package com.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ThirdTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Second Tab Content */
		TextView textView = new TextView(this);
		textView.setText("Third Tab");
		setContentView(textView);

	}
}
 

Main.xml file

<?xml version="1.0" encoding="utf-8"?>
<TabHost android:layout_width="fill_parent"
	android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@android:id/tabhost">
	<LinearLayout android:id="@+id/LinearLayout01"
		android:orientation="vertical" android:layout_height="fill_parent"
		android:layout_width="fill_parent">
		<TabWidget android:id="@android:id/tabs"
			android:layout_height="wrap_content" android:layout_width="fill_parent"></TabWidget>
		<FrameLayout android:id="@android:id/tabcontent"
			android:layout_height="fill_parent" android:layout_width="fill_parent"></FrameLayout>
	</LinearLayout>
</TabHost>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="tabbar.pack"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".FirstTab" />
	<activity android:name=".SecondTab" />
    <activity android:name=".ThirdTab" />
        <activity android:name=".tabbar"
                  android:label="TabBar Demo">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

You can place anything in each tab by setting the contentView or dynamically adding controls.
You can do anything with this tabbar by editing the xml, like placing it below or giving images for each tab etc etc….

Please leave your valuable comments…

Using Tabbars in ANDROID, A Simple Example……….

This is a simple example showing how to use tabbars in ANDROID.
First create a new project and copy this code to it.

package com.coderzheaven;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

public class tabbar extends TabActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /** TabHost will have Tabs */
        TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);

        /** TabSpec used to create a new tab.
         * By using TabSpec only we can able to setContent to the tab.
         * By using TabSpec setIndicator() we can set name to tab. */

        /** tid1 is firstTabSpec Id. Its used to access outside. */
        TabSpec firstTabSpec = tabHost.newTabSpec("tab_id1");
        TabSpec secondTabSpec = tabHost.newTabSpec("tab_id2");
        TabSpec thirdTabSpec = tabHost.newTabSpec("tab_id3");

        /** TabSpec setIndicator() is used to set name for the tab. */
        /** TabSpec setContent() is used to set content for a particular tab. */
        firstTabSpec.setIndicator("First").setContent(new Intent(this,FirstTab.class));
        secondTabSpec.setIndicator("Second ").setContent(new Intent(this,SecondTab.class));
        thirdTabSpec.setIndicator("Third").setContent(new Intent(this,ThirdTab.class));

        /** Add tabSpec to the TabHost to display. */
        tabHost.addTab(firstTabSpec);
        tabHost.addTab(secondTabSpec);
        tabHost.addTab(thirdTabSpec);

    }
}


Now create three another java files by right clicking the src folder and name it FirstTab.java, SecondTab.java, ThirdTab.java.

Now copy the following code to FirstTab.java.

package com.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class FirstTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* First Tab Content */
		TextView textView = new TextView(this);
		textView.setText("First Tab");
		setContentView(textView);
	}
}

SecondTab.java

package com.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class SecondTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Second Tab Content */
		TextView textView = new TextView(this);
		textView.setText("Second Tab");
		setContentView(textView);

	}
}

Now ThirdTab.java.

package com.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ThirdTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Second Tab Content */
		TextView textView = new TextView(this);
		textView.setText("Third Tab");
		setContentView(textView);

	}
}

Main.xml file

<?xml version="1.0" encoding="utf-8"?>
<TabHost android:layout_width="fill_parent"
	android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@android:id/tabhost">
	<LinearLayout android:id="@+id/LinearLayout01"
		android:orientation="vertical" android:layout_height="fill_parent"
		android:layout_width="fill_parent">
		<TabWidget android:id="@android:id/tabs"
			android:layout_height="wrap_content" android:layout_width="fill_parent"></TabWidget>
		<FrameLayout android:id="@android:id/tabcontent"
			android:layout_height="fill_parent" android:layout_width="fill_parent"></FrameLayout>
	</LinearLayout>
</TabHost>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="tabbar.pack"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".FirstTab" />
	<activity android:name=".SecondTab" />
    <activity android:name=".ThirdTab" />
        <activity android:name=".tabbar"
                  android:label="TabBar Demo">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
TabBar in ANDROID

TabBar in ANDROID Demo

You can place anything in each tab by setting the contentView or dynamically adding controls.
You can do anything with this tabbar by editing the xml, like placing it below or giving images for each tab etc etc….

Please leave your valuable comments…

Listening incoming sms message in Android

When a new sms message is received by the device, a Broadcast Receiver is registered. For this

IntentFilter filter = new IntentFilter(SMS_RECEIVED);
registerReceiver(receiver_SMS, filter);

should be included . Also sms are sent in PDU’s(Protocol Description Units) format, which act as an encapsulation.
Inorder to extract from PDU to byte array

messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);

method is used.
When sms comes, the BroadCast listener is activated and sms sender number is showed in a ListView

package com.coderzheaven.pack;

import java.util.ArrayList;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class smsReceiver extends Activity
{
    /** Called when the activity is first created. */
	 public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
	 ListView list;
	 ArrayList<String> messageList;
	 ArrayAdapter< String> adapter;
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        list = (ListView) findViewById(R.id.listView1);

        messageList  = new ArrayList<String>();
        //messageList.add("check");
       adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, messageList);
       list.setAdapter(adapter);

        IntentFilter filter = new IntentFilter(SMS_RECEIVED);
        registerReceiver(receiver_SMS, filter);
    }
    BroadcastReceiver receiver_SMS = new BroadcastReceiver()
    {
		public void onReceive(Context context, Intent intent)
		{
			 if (intent.getAction().equals(SMS_RECEIVED))
			 {
			        Bundle bundle = intent.getExtras();
			        if (bundle != null)
			        {
			          Object[] pdus = (Object[]) bundle.get("pdus");
			          SmsMessage[] messages = new SmsMessage[pdus.length];

			          for (int i = 0; i < pdus.length; i++)
			            messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);

			          for (SmsMessage message : messages)
			          {
			            	 Toast.makeText(smsReceiver.this, "----"+message.getDisplayMessageBody(), Toast.LENGTH_LONG).show();
			            	 receivedMessage(message.getDisplayOriginatingAddress());
			          }
			        }
			      }
		}
	};
	private void receivedMessage(String message)
	{
		messageList.add(message);
		adapter.notifyDataSetChanged();
	}
}

The xml hold a ListView

<?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"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<ListView android:layout_height="fill_parent"
	android:id="@+id/listView1"
	android:layout_width="fill_parent"/>
</LinearLayout>

Also important part is that, for an application to listen an SMS Intent Broadcast should be added

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

This post explains How to get the SMS sent to your emulator within your application

Customizing your button or TextView or another view in ANDROID.

Beautifying our applications is one of the main features of your application’s success.
In ANDROID there are many possible ways to do this.
For eg. We need to have different colors for our buttons, However we can give backgrounds for buttons and all. But we can do many by using our custom xml files, like changing colors on button press and release, transitions etc. This tutorial explains such an example. Extend this example to create your own custom button.

Create a fresh project and copy this code to your main file.

package pack.coderzheaven;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

public class SelectorExample extends Activity {
    private Button b;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b = (Button) findViewById(R.id.Button01);
        b.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				System.out.println("Button clicked!!");
			}
		});

        ImageButton button = (ImageButton) findViewById(R.id.button);
        TransitionDrawable drawable = (TransitionDrawable) button.getDrawable();
        drawable.startTransition(5000);

        Resources res = getResources();
        Drawable shape = res. getDrawable(R.drawable.gradient_box);

        TextView tv = (TextView)findViewById(R.id.textview);
        tv.setBackgroundDrawable(shape);
    }
}

Now the main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android">

	<ImageButton android:id="@+id/button"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:src="@drawable/transition">
	</ImageButton>

	<TextView
		android:id="@+id/textview"
		android:text="CoderzHeaven"
	    android:layout_height="wrap_content"
	    android:layout_width="fill_parent" />
	<Button android:id="@+id/Button01"
		android:background="@drawable/buttonhighlight"
		android:layout_height="50px"
		android:layout_width="fill_parent"
		android:text="CoderzHeaven"	>
	</Button>
</LinearLayout>

Now create an xml file named “gradient_box.xml” in your drawable folder and copy this code to it.
This xml helps you to define the shape for the view for which you are applying this.

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

Now create an xml file named “transition.xml” in your drawable folder and copy this code to it.
This xml file is for applying a transition for your view

<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/on" />
    <item android:drawable="@drawable/off" />
</transition>

Now the AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.selectors"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SelectorExample"
                  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>

Note: Make sure that you have all the images in your drawable folder as shown in the image below.

See the ImageButton transformation in the consequent pictures.


Please leave your comments if you find this post useful!

How to create and delete a directory in SdCard in ANDROID?

Hi all……

This is a simple example to create and delete a directory in ANDROID.
Here the directly is created in the SDCARD. So first create an SDCARD and start the emulator with the SDCARD.

Let’s look at the program.
Use can use this program to create or delete a file in ANDROID also.

package pack.coderzheaven;

import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class CreateDeleteDIR_Example extends Activity {

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

        t = (TextView)findViewById(R.id.tv);
        b= (Button) findViewById(R.id.Button01);
        File dir = new File("/sdcard/new_dir");
        try{
          if(dir.mkdir()) {
             System.out.println("Directory created");
             t.setText("Directory created");
          } else {
             System.out.println("Directory is not created");
             t.setText("Directory is not created");
          }
        }catch(Exception e){
          e.printStackTrace();
        }

        b.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				File del = new File("/sdcard/new_dir");
				 boolean success = del.delete();
			        if (!success) {
			           System.out.println("Deletion of directory failed!");
			        }
			}
        });

    	/* IF THE DIRECTORY IS NOT EMPTY . USE THIS FUNCTION */
	public static boolean deleteNon_EmptyDir(File dir) {
	    if (dir.isDirectory()) {
	        String[] children = dir.list();
	        for (int i=0; i<children.length; i++) {
	            boolean success = deleteNon_EmptyDir(new File(dir, children[i]));
	            if (!success) {
	                return false;
	            }
	        }
	    }
	    return dir.delete();
	}
}

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"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tv"
    />
<Button
	android:text="Delete Directory"
	android:id="@+id/Button01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>
</LinearLayout>

Now go to File-explorer in the window menu->show View and see the result.

After directory creation.

After directory deletion.

Android frame Animation

A series of frames is drawn one after the other at regular intervals.
For this create a xml which contains ImageView for showing the animation

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=
	"http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:background="#FFFFFF"
   android:gravity="center_vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">


   <ImageView
      android:id="@+id/Image"
       android:layout_gravity="center_horizontal"
      android:layout_width="wrap_content"
      android:background="@drawable/d1"
      android:layout_height="wrap_content"/>

      <Button
      android:id="@+id/startFAButtonId"
      android:layout_width="wrap_content"
      android:layout_gravity="center_horizontal"
      android:layout_height="wrap_content"
      android:text="Start Animation"
      />
</LinearLayout>

The main java file is

package com.coderzheaven.animation;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class Frame extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button b = (Button)this.findViewById(R.id.startFAButtonId);
        b.setOnClickListener(new View.OnClickListener()
        {
			public void onClick(View v)
			{
				animate();
			}
		});

    }
 	   private void animate() {
 	      ImageView imgView = (ImageView)findViewById(R.id.Image);
 	      imgView.setVisibility(ImageView.VISIBLE);
 	      imgView.setBackgroundResource(R.drawable.animation_frame);

 	      AnimationDrawable frameAnimation =  (AnimationDrawable) imgView.getBackground();

 	      if (frameAnimation.isRunning()) {
 	         frameAnimation.stop();
 	      }
 	      else {
 	         frameAnimation.stop();
 	         frameAnimation.start();
 	      }
 	   }
 }

Next the main part, an xml which holds each image and duration in which each image shows.
The xml should be placed inside drawable folder

<?xml version="1.0" encoding="utf-8"?>
<animation-list
	 xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
   <item android:drawable="@drawable/d1" android:duration="50" />
   <item android:drawable="@drawable/d2" android:duration="50" />
   <item android:drawable="@drawable/d3" android:duration="50" />
   <item android:drawable="@drawable/d4" android:duration="50" />
   <item android:drawable="@drawable/d5" android:duration="50" />
</animation-list>

When i click the button the animation will start

Android dialog with ListView

For implementing a ListView, we first create a xml which contains a ListView named list.xml

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

  <ListView
    android:id="@+id/listview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />
</LinearLayout>

Next we create a Dialog Object and inflate the above xml and when the listItem is clicked then a Alert Dialog windows comes
The java file is listed below


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class DialoglistView extends Activity implements OnItemClickListener{
    /** Called when the activity is first created. */
	String[] val = {"sunday","monday","tuesday","thrusday","friday","wednesday","march"};
	ListView list;
	Dialog listDialog;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         showdialog();
    }

    private void showdialog()
    {
    	listDialog = new Dialog(this);
    	listDialog.setTitle("Select Item");
    	 LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    	 View v = li.inflate(R.layout.list, null, false);
    	 listDialog.setContentView(v);
    	 listDialog.setCancelable(true);
         //there are a lot of settings, for dialog, check them all out!

         ListView list1 = (ListView) listDialog.findViewById(R.id.listview);
         list1.setOnItemClickListener(this);
         list1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, val));
         //now that the dialog is set up, it's time to show it
         listDialog.show();
    }

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
	{

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Delete item "+arg2)
		           .setPositiveButton("OK ", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   System.out.println("OK CLICKED");

		           }
		       });
		builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	        	 dialog.dismiss();
	        	 listDialog.cancel();

	           }
	       });

		AlertDialog alert = builder.create();
		alert.setTitle("Information");
		alert.show();
	}
}

The alert window look like this

When the Item is selected then

SQLiteManager plugin for eclipse

When you are working on an Android application that stores data in a SQLite database.There arise many questions like
where does this database file get stored on the filesystem ?
How can we access the database?

I will give solution to all these problems. I created the database from my previous post
about Using SQLite in ANDROID

You can see the sqlite database in eclipse by opening File Explorer .Then

/data/data/package_name/databases

But here we cannot see the tables and table data.
For viewing the table details Eclipse has a plugin. You can download the jar from below.

Download the jar from the sqlite manager from here.

Now put the jar in the folder


eclipse/dropins/


and restart the eclipse and now you can see the sqlitemanager plugin on the top right of the File Explorer window

SQLite

By clicking the icon, sqliteManager Window comes and here we can see the table structure.

SQLite

and then the Browse Data tab shows the whole data
SQLite

Hopefully i think you cleared all doubts about SqliteManager Plugin

Note : If you’re using a plug-in for which no Update Site is available, you can use the “dropins” folder in your Eclipse installation directory.

Plug-ins are typically distributed as .jar files. To add a plug-in to your Eclipse installation, put the plug-in .jar file into the Eclipse “dropins” folder and restart Eclipse. Eclipse should detect the new plug-in and install it for you.

Note : if your SQLiteManager Plugin is not enabled, then check your sqlite db file extension. It should be a “.db” extension.

Please check my another ANDROID BLOG FOR MORE ANDROID CODES AND SAMPLES.

How to use SQLite in ANDROID, A really simple example.

Hello ANDROID Lovers……..

In today’s tutorial I will show you how to deal with SQLite Databases in ANDROID. You know that SQLite are Lightweight databases which is maintained only on the client side. They don’t need a server. The SQLite databases are simply a file wrapped around with some stuff which helps us deal with them like a normal database. And also don’t think they are like other databases like MySQL, Oracle etc, SQLite databases provide basic funtionalities to deal with a database.

Here I will show you how to use simple queries to deal with the SQLite database.
You may have found on the net numerous examples for SQLite in ANDROID using some extra classes which extend SQLiteOpenHelper classes which is pretty difficult to understand
But Don’t worry here I will show you how to deal with these databases like you normally do with your MYSQL Database or Oracle.

Before you need some resources.
1. An image “android.png” or “android.jpg” (which I am using as background for the layout).
OK that’s enough

=====================================================================================================================
Now go on and create a new project and name it “SQLiteExample.java” and drag and copy the following code to it.

SQLiteExample.java

package pac.SQLite;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SQLiteExample extends Activity {

	LinearLayout Linear;
	SQLiteDatabase mydb;
	private static String DBNAME = "PERSONS.db";	// THIS IS THE SQLITE DATABASE FILE NAME.
	private static String TABLE = "MY_TABLE";		// THIS IS THE TABLE NAME

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

        Linear  = (LinearLayout)findViewById(R.id.linear);
        Toast.makeText(getApplicationContext(), "Creating table.", Toast.LENGTH_SHORT).show();

        dropTable();		// DROPPING THE TABLE.
        createTable();
        TextView t0 = new TextView(this);
    	t0.setText("This tutorial covers CREATION, INSERTION, UPDATION AND DELETION USING SQLITE DATABASES.                                                Creating table complete........");
    	Linear.addView(t0);
        Toast.makeText(getApplicationContext(), "Creating table complete.", Toast.LENGTH_SHORT).show();
        insertIntoTable();
        TextView t1 = new TextView(this);
    	t1.setText("Insert into table complete........");
    	Linear.addView(t1);
        Toast.makeText(getApplicationContext(), "Insert into table complete", Toast.LENGTH_SHORT).show();
        TextView t2 = new TextView(this);
    	t2.setText("Showing table values............");
    	Linear.addView(t2);
    	showTableValues();
        Toast.makeText(getApplicationContext(), "Showing table values", Toast.LENGTH_SHORT).show();
        updateTable();
        TextView t3 = new TextView(this);
    	t3.setText("Updating table values............");
    	Linear.addView(t3);
        Toast.makeText(getApplicationContext(), "Updating table values", Toast.LENGTH_SHORT).show();
        TextView t4 = new TextView(this);
    	t4.setText("Showing table values after updation..........");
    	Linear.addView(t4);
        Toast.makeText(getApplicationContext(), "Showing table values after updation.", Toast.LENGTH_SHORT).show();
        showTableValues();
        deleteValues();
        TextView t5 = new TextView(this);
    	t5.setText("Deleting table values..........");
    	Linear.addView(t5);
        Toast.makeText(getApplicationContext(), "Deleting table values", Toast.LENGTH_SHORT).show();
        TextView t6 = new TextView(this);
    	t6.setText("Showing table values after deletion.........");
    	Linear.addView(t6);
        Toast.makeText(getApplicationContext(), "Showing table values after deletion.", Toast.LENGTH_SHORT).show();
        showTableValues();
        setColor(t0);
        setColor(t1);
        setColor(t2);
        setColor(t3);
        setColor(t4);
        setColor(t5);
        setColor(t6);
    }
    // THIS FUNCTION SETS COLOR AND PADDING FOR THE TEXTVIEWS 
    public void setColor(TextView t){
    	t.setTextColor(Color.BLACK);
    	t.setPadding(20, 5, 0, 5);
    	t.setTextSize(1, 15);
    }

    // CREATE TABLE IF NOT EXISTS 
    public void createTable(){
    	try{
    	mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
    	mydb.execSQL("CREATE TABLE IF  NOT EXISTS "+ TABLE +" (ID INTEGER PRIMARY KEY, NAME TEXT, PLACE TEXT);");
    	mydb.close();
    	}catch(Exception e){
    		Toast.makeText(getApplicationContext(), "Error in creating table", Toast.LENGTH_LONG);
    	}
    }
    // THIS FUNCTION INSERTS DATA TO THE DATABASE
    public void insertIntoTable(){
    	try{
	    	mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
	    	mydb.execSQL("INSERT INTO " + TABLE + "(NAME, PLACE) VALUES('CODERZHEAVEN','GREAT INDIA')");
	    	mydb.execSQL("INSERT INTO " + TABLE + "(NAME, PLACE) VALUES('ANTHONY','USA')");
	    	mydb.execSQL("INSERT INTO " + TABLE + "(NAME, PLACE) VALUES('SHUING','JAPAN')");
	    	mydb.execSQL("INSERT INTO " + TABLE + "(NAME, PLACE) VALUES('JAMES','INDIA')");
	    	mydb.execSQL("INSERT INTO " + TABLE + "(NAME, PLACE) VALUES('SOORYA','INDIA')");
	    	mydb.execSQL("INSERT INTO " + TABLE + "(NAME, PLACE) VALUES('MALIK','INDIA')");
	    	mydb.close();
	    }catch(Exception e){
			Toast.makeText(getApplicationContext(), "Error in inserting into table", Toast.LENGTH_LONG);
		}
    }
    // THIS FUNCTION SHOWS DATA FROM THE DATABASE 
    public void showTableValues(){
    	try{
	    	mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
	    	Cursor allrows  = mydb.rawQuery("SELECT * FROM "+  TABLE, null);
	    	System.out.println("COUNT : " + allrows.getCount());
	    	Integer cindex = allrows.getColumnIndex("NAME");
	    	Integer cindex1 = allrows.getColumnIndex("PLACE");

	    	TextView t = new TextView(this);
	    	t.setText("========================================");
			//Linear.removeAllViews();
			Linear.addView(t);

			if(allrows.moveToFirst()){
				do{
					LinearLayout id_row   = new LinearLayout(this);
					LinearLayout name_row = new LinearLayout(this);
					LinearLayout place_row= new LinearLayout(this);

					final TextView id_  = new TextView(this);
					final TextView name_ = new TextView(this);
					final TextView place_ = new TextView(this);
					final TextView   sep  = new TextView(this);

					String ID = allrows.getString(0);
			    	String NAME= allrows.getString(1);
			    	String PLACE= allrows.getString(2);

			    	id_.setTextColor(Color.RED);
			    	id_.setPadding(20, 5, 0, 5);
			    	name_.setTextColor(Color.RED);
			    	name_.setPadding(20, 5, 0, 5);
			    	place_.setTextColor(Color.RED);
			    	place_.setPadding(20, 5, 0, 5);

					System.out.println("NAME " + allrows.getString(cindex) + " PLACE : "+ allrows.getString(cindex1));
					System.out.println("ID : "+ ID  + " || NAME " + NAME + "|| PLACE : "+ PLACE);

					id_.setText("ID : " + ID);
					id_row.addView(id_);
					Linear.addView(id_row);
					name_.setText("NAME : "+NAME);
					name_row.addView(name_);
					Linear.addView(name_row);
					place_.setText("PLACE : " + PLACE);
					place_row.addView(place_);
					Linear.addView(place_row);
					sep.setText("---------------------------------------------------------------");
					Linear.addView(sep);
				}
				while(allrows.moveToNext());
			}
			mydb.close();
    	 }catch(Exception e){
 			Toast.makeText(getApplicationContext(), "Error encountered.", Toast.LENGTH_LONG);
 		}
	}
    // THIS FUNCTION UPDATES THE DATABASE ACCORDING TO THE CONDITION 
    public void updateTable(){
    	try{
	    	mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
	    	mydb.execSQL("UPDATE " + TABLE + " SET NAME = 'MAX' WHERE PLACE = 'USA'");
	    	mydb.close();
	    }catch(Exception e){
			Toast.makeText(getApplicationContext(), "Error encountered", Toast.LENGTH_LONG);
		}
    }
    // THIS FUNCTION DELETES VALUES FROM THE DATABASE ACCORDING TO THE CONDITION
    public void deleteValues(){
    	try{
	    	mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
	    	mydb.execSQL("DELETE FROM " + TABLE + " WHERE PLACE = 'USA'");
	    	mydb.close();
	    }catch(Exception e){
			Toast.makeText(getApplicationContext(), "Error encountered while deleting.", Toast.LENGTH_LONG);
		}
    }
    // THIS FUNTION DROPS A TABLE 
    public void dropTable(){
    	try{
	    	mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
	    	mydb.execSQL("DROP TABLE " + TABLE);
	    	mydb.close();
	    }catch(Exception e){
			Toast.makeText(getApplicationContext(), "Error encountered while dropping.", Toast.LENGTH_LONG);
		}
    }
}

Now the main.xml file

<?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">
	<ScrollView
		android:id="@+id/ScrollView01"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:background="@drawable/android">
			<LinearLayout
				android:id="@+id/linear"
				android:orientation="vertical"
				android:layout_below="@+id/add_record"
				android:layout_width="wrap_content"
				android:layout_height="fill_parent">
			</LinearLayout>
	</ScrollView>
</LinearLayout>

The mainfest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pac.SQLite"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SQLiteExample"
                  android:label="SQLite Example Demo">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

=====================================================================================================================

That’s all you are done go on and run the application.
Scroll Down to see different oprations done on the database.
Well if you want to see the database you can go to the DDMS Perspective and open File-Explorer and under folder “data/data/your-application-package/databases/”, there you will see the database.

However there is a way to see the actual database values like your MYSQL Database.
Check this post to see how its done.
SQLiteManager plugin for eclipse
Happy coding…

Fell free to leave your comments if you have any doubt on this.

if you want to use the android using php and mysql
please check these posts.

1. Android phpMysql connection
2. Android phpmySQL connection redone.

Check some other most popular and useful posts.

http://www.coderzheaven.com/2012/08/21/uploading-downloading-files-popular-posts/

How to get information about all the applications installed in your ANDROID Emulator or Phone? / How to use getPackageManager() in ANDROID ?

Hi all,
In this tutorial I will show you how to get the information about all the applications installed in your ANDROID phone.
What you have to do is create a ANDROID project inside the package pack.GetAllInstalledApplications amd name the java file “GetAllInstalledApplicationsExample.java” and copy the following code into it.

Here the “getPackageManager().getInstalledPackages(0);” gets information about all the packages installed in your ANDROID Phone or emulator.
Now go on and try this.

package pack.GetAllInstalledApplications;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class GetAllInstalledApplicationsExample extends Activity {

	 public  ArrayList<packageInfoStruct> res = new ArrayList<packageInfoStruct>();
	 public ListView list;
	 public String app_labels[];

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

	        getPackages();

	        list = (ListView)findViewById(R.id.ListView01);
			try{
				list.setAdapter(new ArrayAdapter<string>(this,
					android.R.layout.simple_dropdown_item_1line, app_labels));
			}catch(Exception e){
				System.out.println("Err ++> " + e.getMessage());
				Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
			}

	 }
	private ArrayList<packageInfoStruct> getPackages() {
	    ArrayList<packageInfoStruct> apps = getInstalledApps(false);
	    final int max = apps.size();
	    for (int i=0; i < max; i++) {
	        apps.get(i);
	    }
	    return apps;
	}

	private ArrayList<packageInfoStruct> getInstalledApps(boolean getSysPackages) {

	    List<packageInfo> packs = getPackageManager().getInstalledPackages(0);
	    try{
	    	app_labels = new String[packs.size()];
	    }catch(Exception e){
			Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
		}
	    for(int i=0;i < packs.size();i++) {
	        PackageInfo p = packs.get(i);
	        if ((!getSysPackages) && (p.versionName == null)) {
	            continue ;
	        }
	        PackageInfoStruct newInfo = new PackageInfoStruct();
	        newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
	        newInfo.pname = p.packageName;
	        newInfo.versionName = p.versionName;
	        newInfo.versionCode = p.versionCode;
	        newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());
	        res.add(newInfo);

	        app_labels[i] = newInfo.appname;
	    }
	    return res;
	}
}
/* This class is for storing the data for each application */
class PackageInfoStruct {
    String appname = "";
    String pname = "";
    String versionName = "";
    int versionCode = 0;
    Drawable icon;
}

The main.xml file

<?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" >
 <listView android:id="@+id/ListView01"
  android:layout_height="375px"
  android:layout_width="fill_parent">
 </listView>
</linearLayout>

The manifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.GetAllInstalledApplications"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".GetAllInstalledApplicationsExample"
                  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>
Get all installed applications in your ANDROID Phone

Showin all applications installed in your ANDROID Phone or emulator

You can download the source code from here.

Using Gestures in ANDROID,A Simple example.

This is a really simple example illustrating gestures in ANDROID.
You Know that everything you do with your hand inside the phone is a gesture like SingleTap, doubleTap etc.
Here is a quick illustration of this.
For this the activity must implement OnGestureListener. The GestureDetector detects the gestures.
Let’s look at the example.

package pack.GestureSampleThree;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.GestureDetector.OnGestureListener;
import android.widget.LinearLayout;
import android.widget.TextView;

public class GestureSampleThreeExample extends Activity implements OnGestureListener {
	 private LinearLayout main;
	    private TextView viewA;

	    private GestureDetector gestureScanner;

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

	        gestureScanner = new GestureDetector(this);

	        main = new LinearLayout(this);
	        main.setBackgroundColor(Color.GRAY);
	        main.setLayoutParams(new LinearLayout.LayoutParams(320,480));

	        viewA = new TextView(this);
	        viewA.setBackgroundColor(Color.YELLOW);
	        viewA.setTextColor(Color.BLACK);
	        viewA.setTextSize(16);
	        viewA.setLayoutParams(new LinearLayout.LayoutParams(320,80));
	        main.addView(viewA);

	        setContentView(main);
	    }

	    @Override
	    public boolean onTouchEvent(MotionEvent me) {
	        return gestureScanner.onTouchEvent(me);
	    }


	    public boolean onDown(MotionEvent e) {
	        viewA.setText("-" + "DOWN" + "-");
	        return true;
	    }

	    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
	        viewA.setText("-" + "FLING" + "-");
	        return true;
	    }


	    public void onLongPress(MotionEvent e) {
	        viewA.setText("-" + "LONG PRESS" + "-");
	    }


	    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
	        viewA.setText("-" + "SCROLL" + "-");
	        return true;
	    }


	    public void onShowPress(MotionEvent e) {
	        viewA.setText("-" + "SHOW PRESS" + "-");
	    }


	    public boolean onSingleTapUp(MotionEvent e) {
	        viewA.setText("-" + "SINGLE TAP UP" + "-");
	        return true;
	    }
	}

The layout file main.xml for the above code is

<?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"
    >
<textView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
</linearLayout>

The manifest file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.GestureSampleThree"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".GestureSampleThreeExample"
                  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>

A complete example for making your own gesture application in ANDROID is explained in this tutorial

Android TableLayout

In android there are different layouts and we often confuse about which one to use. Even if we select one, it is little complicated.

So this tutorials is to show you about the TableLayout

Here i first created linear Layout in which a Table Layout is added

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
	android:layout_height="fill_parent"
	android:layout_width="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<TableLayout
		android:layout_width="wrap_content"
		android:id="@+id/table"
		android:layout_height="wrap_content">
	<TableRow>
		<EditText
			 android:text=""
			 android:id="@+id/name"
			 android:layout_column="0"
			 android:hint="name"
			 android:layout_width="wrap_content"
			 android:layout_height="wrap_content"
			 android:fadingEdge="vertical|horizontal"/>
	</TableRow>
	<TableRow>
		<Button android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="Save"
			android:layout_column="0"
			android:id="@+id/OkButton"
			android:fadingEdge="horizontal">
		</Button>
		<Button android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="Cancel"
			android:layout_column="1"
			android:id="@+id/cancelButton"
			android:fadingEdge="horizontal">
		</Button>
	</TableRow>

	</TableLayout>
</LinearLayout>

Here you can see that the first row ie, the EditText length is limited to 1 column and so it is not looking good. So we can make the EditText span across two column by adding this line to EditText

android:layout_span="2"

Now we can position the TableLayout in the center of the screen by adding this to TableLayout

android:layout_gravity = "center_vertical"

Now we think of aligning this to center horizontal as

android:layout_gravity = "center_horizontal"

But this wont work. This is because of LinearLayout and here the positioning is restricted.
But their is solution “Relative Layout” and positioning is easy by using this layout.

I will cover this in my next Post

Working with SQLite Database in ANDROID.

Below is a straight forward example of how to deal with SQLite database in ANDROID.
Go ahead and copy and paste the following code to your java file.
The example has one database and performs functions like insert delete and listing of values in a textView.

package com.database;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class databaseactivity extends Activity {
    /** Called when the activity is first created. */

    private static String DBNAME = "mydb.db";
    private static String TABLE = "myTable";

    Button butAdd,butdel;
    EditText nam,mail;
    LinearLayout lay;
    TableLayout layout;
    TextView tev,tev1;
    int f=0;
    Integer ind;
   ScrollView sv;
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tev=(TextView)findViewById(R.id.tv);
        tev1=(TextView)findViewById(R.id.tv1);
        layout=(TableLayout)findViewById(R.id.layout);
        lay = (LinearLayout) findViewById(R.id.linear);
        butAdd = (Button) findViewById(R.id.add);
        nam=(EditText)findViewById(R.id.names);
        mail=(EditText)findViewById(R.id.emails);

       SQLiteDatabase mydb;
       mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
       mydb.execSQL("create table if not exists "+TABLE+" (_id integer primary key autoincrement,name text not null,email text not null);");
       mydb.close();
       sv = new ScrollView(this);
       setContentView(sv);
       sv.addView(lay);

       butAdd.setOnClickListener(new View.OnClickListener()
       {
      @Override
      public void onClick(View v)
      {
                  f=0;
                  addTask();
      }
      });
    }

    public void addTask()
    {
                SQLiteDatabase mydb;
                mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
                ContentValues newrow = new ContentValues();
                String a=nam.getText().toString();
                String b=mail.getText().toString();
                if(a.trim().length()!=0 && b.trim().length()!=0)
                {
                                newrow.put("name", nam.getText().toString());
                                newrow.put("email", mail.getText().toString());
                                mydb.insert(TABLE, null, newrow);
                }
                else
                {
                                if(f==0)
                                      Toast.makeText(getApplicationContext(), "Fields cannot be left blank",
                                                                                                               Toast.LENGTH_SHORT).show();
                }
                nam.setText(null);
                mail.setText(null);
                String[] result = new String[]{"_id","name","email"};
                Cursor allrows  = mydb.query(TABLE, result, null, null, null, null, null);
                Integer cindex = allrows.getColumnIndex("name");
                Integer cindex1 = allrows.getColumnIndex("email");
                Integer cindex2 = allrows.getColumnIndex("_id");
                if(allrows.moveToFirst())
                {
                layout.removeAllViews();
                do
                {
                                TableRow row= new TableRow(this);
                                final TextView tv = new TextView(this);
                                final TextView tv1 = new TextView(this);
                                final Button but=new Button(this);
                                but.setText("Delete");
                                final Button butt=new Button(this);
                                butt.setText("Edit");                                ind=Integer.parseInt(allrows.getString(cindex2)) ;
                                but.setId(ind);
                                butt.setId(ind);
                                nam.setId(ind);
                                but.setOnClickListener(new View.OnClickListener() {
                                                public void onClick(View v)
                                                {
                                                                f=1;
                                                                int i=but.getId();
                                                                SQLiteDatabase mydb;
                                                                mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
                                                                mydb.delete(TABLE,"_id="+i, null);
                                                                mydb.close();
                                                                Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_SHORT).show();
                                                                addTask();
                                                }
                                });


                                butt.setOnClickListener(new View.OnClickListener() {
                                                public void onClick(View v)
                                                {
                                                               butt.setText("Save");
                                                               nam.setText(tv.getText());
                                                               mail.setText(tv1.getText());
                                                               butt.setOnClickListener(new View.OnClickListener() {
                                                               public void onClick(View v)   {
                                                                             f=1;
                                                                             int j=but.getId();
                                                                             SQLiteDatabase mydb;
                                                                             mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
;
                                                                             ContentValues newrow1 = new ContentValues();
                                                                             String a=nam.getText().toString();
                                                                             String b=mail.getText().toString();
                                                                             if(a.trim().length()!=0&& b.trim().length()!=0)                                                                                {                                                                                                newrow1.put("name", nam.getText().toString());
                                                                                                  newrow1.put("email", mail.getText().toString());
                                                                                                  mydb.update(TABLE,newrow1, "_id="+j, null);
                                       
                                                                                                  Toast.makeText(getApplicationContext(), "Updated",
                                                                                                                            Toast.LENGTH_SHORT).show();
                                                                                                  nam.setText(null);
                                                                                                  mail.setText(null);
                                                                                                  butt.setText("Edit");
                                                                                                  addTask();
                                                                               }    else                                                                                {
                                                                                         //if(f==0)
                                                                                           Toast.makeText(getApplicationContext(), "Fields cannot be left blank",
                                                                                                                                 Toast.LENGTH_SHORT).show();
                                                                         }                                                                                mydb.close();
                                                                    }
                                                            });
                                                }
                                });
                                tv.setText(allrows.getString(cindex));
                                row.addView(tv);
                                tv1.setText(allrows.getString(cindex1));
                                row.addView(tv1);
                                row.addView(butt);
                                row.addView(but);
                                layout.addView(row);
                }while(allrows.moveToNext());
                }
                else
                {
                                layout.removeAllViews();
                                Toast.makeText(getApplicationContext(), "Table is empty", Toast.LENGTH_SHORT).show();
                }
                mydb.close();
    }
}

In the XML file set up a TableLayout with android:stretchColumns=”0,1″
and other buttons also and proceed.

Please leave your valuable comments.

Custom Toasts in ANDROID.

First, just show an image inside a toast:

package com.Ch.Example.pack;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;


public class Example extends Activity {
    /** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        showToast();
    }
	private void showToast()
	{
		Toast toast = new Toast(getApplicationContext());
		ImageView view = new ImageView(getApplicationContext());
		view.setImageResource(R.drawable.fish1);
		toast.setView(view);
		toast.show();
	}
}

This method just displays a text toast:

Context context = getApplicationContext();
CharSequence text = "hai i am here";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 50, 50);
toast.show();


And this method displays a Toast that contains both an image and text:

CharSequence text = "hai i am here";
Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG);
View textView = toast.getView();
LinearLayout lay = new LinearLayout(getApplicationContext());
lay.setOrientation(LinearLayout.VERTICAL);
ImageView view = new ImageView(getApplicationContext());
view.setImageResource(R.drawable.fish1);
lay.addView(view);
lay.addView(textView);
toast.setView(lay);
toast.show();