Saturday 17 March 2018

Android - Introduction to Room Persistence Library

Sometimes app needs to persist data locally in a structured way. The best example is to cache data which is frequently used, or data which should be accessible even device can not access network. SqLite is the solution for these use cases.

Room Persistence Library makes developer's life easy to integrate sqlite in app. Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.

Today in this tutorial:
  • Introduction of Room
  • How to add Room in the project

Introduction of Room

Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.

There are three vital elements in Room.

Database: Contains the database holder and serves as the main access point for the underlying connection to your app's persisted, relational data.
The class that's annotated with @Database should satisfy the following conditions:
    • Be an abstract class that extends RoomDatabase.
    • Include the list of entities associated with the database within the annotation.
    • Contain an abstract method that has 0 arguments and returns the class that is annotated with @Dao.
At runtime, you can acquire an instance of Database by calling Room.databaseBuilder() or Room.inMemoryDatabaseBuilder().

Entity: Represents a table in the database.

DAO: Contains helper methods to access database and perform operations.

How to add Room in the project

  • Add the google Maven repository 
           To add this in your project open your build.gradle(project level) and add the following code.

allprojects {
    repositories {
        jcenter()
        google()
    }
}
  • Add Architecture Components
          Open your app (module) build.gradle and add the following dependency

 implementation "android.arch.persistence.room:runtime:1.0.0"
 annotationProcessor "android.arch.persistence.room:compiler:1.0.0"

Note: For Kotlin based apps, make sure you use kapt instead of annotationProcessor. You should also add the kotlin-kapt plugin.

Sync your gradle files. 

That's it. Now you are good to go.

I will come up with working demo app using room library in next post. Till then you can look in to SqLite database tutorial. I will replicate this tutorial with Room library in next tutorial. So just go through it and get basic idea about SqLit and demo app.


Saturday 7 September 2013

Android-Populate ListView from SQLite Database (Insert, Update,Delete)

Hello Everyone.. I am going to post this after long time. I created this tutorial before 2 month but today I got time to post here.

Today in this tutorial I will show you:

  1. Create table in SQLite
  2. Insert data into SQLite
  3. Update data into SQLite
  4. Delete data from SQLite
What to do ?
  • In this project I want to create a table in SQLite database. And store first name and last name for a person.
  • Then I can edit/update them by clicking on it.
  • Also, I can delete a person by long press on it.
How to do ?
  • Create one SQLiteOpenHelper class to create table in database.
  •  Create two Activities, one for adding data and second for displaying list of data
  • Create BaseAdapter to bind data in listview
  • Some xml files for layouts
What is Result ?

At the end of this tutorial we will get output as shown in following screenshots.
In this project we can add a person's first name and last name, edit it and delete it.

Special Thanks

Before moving towards coding I want to Thanks to Hiral Kanojiya. She wrote most of the code for this tutorial, I just guide her and then polished the code. Really without her help I could never get time to post this.

Thank You very much Hiral Kanojiya.

Screenshots










//Create table into SQLite Database
DbHelper.java

package com.hk.sqlitedemo;

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

public class DbHelper extends SQLiteOpenHelper {
    static String DATABASE_NAME="userdata";
    public static final String TABLE_NAME="user";
    public static final String KEY_FNAME="fname";
    public static final String KEY_LNAME="lname";
    public static final String KEY_ID="id";
    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
       
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT)";
        db.execSQL(CREATE_TABLE);

    }

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

    }

}


//activity to add recored
AddActivity.java

package com.hk.sqlitedemo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class AddActivity extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_first,edit_last;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String id,fname,lname;
private boolean isUpdate;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_activity);
       
        btn_save=(Button)findViewById(R.id.save_btn);
        edit_first=(EditText)findViewById(R.id.frst_editTxt);
        edit_last=(EditText)findViewById(R.id.last_editTxt);
        
       isUpdate=getIntent().getExtras().getBoolean("update");
        if(isUpdate)
        {
            id=getIntent().getExtras().getString("ID");
            fname=getIntent().getExtras().getString("Fname");
            lname=getIntent().getExtras().getString("Lname");
            edit_first.setText(fname);
            edit_last.setText(lname);
           
        }
        
         btn_save.setOnClickListener(this);
        
         mHelper=new DbHelper(this);
       
    }

    // saveButton click event
    public void onClick(View v) {
        fname=edit_first.getText().toString().trim();
        lname=edit_last.getText().toString().trim();
        if(fname.length()>0 && lname.length()>0)
        {
            saveData();
        }
        else
        {
            AlertDialog.Builder alertBuilder=new AlertDialog.Builder(AddActivity.this);
            alertBuilder.setTitle("Invalid Data");
            alertBuilder.setMessage("Please, Enter valid data");
            alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
               
                public void onClick(DialogInterface dialog, int which) {
                       dialog.cancel();
                   
                }
            });
            alertBuilder.create().show();
        }
       
    }

    /**
     * save data into SQLite
     */
    private void saveData(){
        dataBase=mHelper.getWritableDatabase();
        ContentValues values=new ContentValues();
       
        values.put(DbHelper.KEY_FNAME,fname);
        values.put(DbHelper.KEY_LNAME,lname );
       
        System.out.println("");
        if(isUpdate)
        {   
            //update database with new data
            dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
        }
        else
        {
            //insert data into database
            dataBase.insert(DbHelper.TABLE_NAME, null, values);
        }
        //close database
        dataBase.close();
        finish();
       
       
    }

}

//activity to display record in list
DisplayActivity.java

package com.hk.sqlitedemo;

import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class DisplayActivity extends Activity {

    private DbHelper mHelper;
    private SQLiteDatabase dataBase;

    private ArrayList<String> userId = new ArrayList<String>();
    private ArrayList<String> user_fName = new ArrayList<String>();
    private ArrayList<String> user_lName = new ArrayList<String>();

    private ListView userList;
    private AlertDialog.Builder build;

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

        userList = (ListView) findViewById(R.id.List);

        mHelper = new DbHelper(this);
       
        //add new record
        findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                Intent i = new Intent(getApplicationContext(), AddActivity.class);
                i.putExtra("update", false);
                startActivity(i);

            }
        });
       
        //click to update data
        userList.setOnItemClickListener(new OnItemClickListener() {

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

                Intent i = new Intent(getApplicationContext(), AddActivity.class);
                i.putExtra("Fname", user_fName.get(arg2));
                i.putExtra("Lname", user_lName.get(arg2));
                i.putExtra("ID", userId.get(arg2));
                i.putExtra("update", true);
                startActivity(i);

            }
        });
       
        //long click to delete data
        userList.setOnItemLongClickListener(new OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {

                build = new AlertDialog.Builder(DisplayActivity.this);
                build.setTitle("Delete " + user_fName.get(arg2) + " " + user_lName.get(arg2));
                build.setMessage("Do you want to delete ?");
                build.setPositiveButton("Yes",new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {

                                Toast.makeText( getApplicationContext(),
                                        user_fName.get(arg2) + " "
                                                + user_lName.get(arg2)
                                                + " is deleted.", 3000).show();

                                dataBase.delete(
                                        DbHelper.TABLE_NAME,
                                        DbHelper.KEY_ID + "="
                                                + userId.get(arg2), null);
                                displayData();
                                dialog.cancel();
                            }
                        });

                build.setNegativeButton("No", new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                            }
                        });
                AlertDialog alert = build.create();
                alert.show();

                return true;
            }
        });
    }

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

    /**
     * displays data from SQLite
     */
    private void displayData() {
        dataBase = mHelper.getWritableDatabase();
        Cursor mCursor = dataBase.rawQuery("SELECT * FROM " + DbHelper.TABLE_NAME, null);

        userId.clear();
        user_fName.clear();
        user_lName.clear();
        if (mCursor.moveToFirst()) {
            do {
                userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
                user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
                user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));

            } while (mCursor.moveToNext());
        }
        DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName);
        userList.setAdapter(disadpt);
        mCursor.close();
    }

   

}

//adapter to load data into list
DisplayAdapter.java

package com.hk.sqlitedemo;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class DisplayAdapter extends BaseAdapter {
    private Context mContext;
    private ArrayList<String> id;
    private ArrayList<String> firstName;
    private ArrayList<String> lastName;
   

    public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname) {
        this.mContext = c;

        this.id = id;
        this.firstName = fname;
        this.lastName = lname;
    }

    public int getCount() {
        // TODO Auto-generated method stub
        return id.size();
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    public View getView(int pos, View child, ViewGroup parent) {
        Holder mHolder;
        LayoutInflater layoutInflater;
        if (child == null) {
            layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            child = layoutInflater.inflate(R.layout.listcell, null);
            mHolder = new Holder();
            mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
            mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
            mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
            child.setTag(mHolder);
        } else {
            mHolder = (Holder) child.getTag();
        }
        mHolder.txt_id.setText(id.get(pos));
        mHolder.txt_fName.setText(firstName.get(pos));
        mHolder.txt_lName.setText(lastName.get(pos));

        return child;
    }

    public class Holder {
        TextView txt_id;
        TextView txt_fName;
        TextView txt_lName;
    }

}

You can download source code from Here

Monday 13 May 2013

Android Sliding menu like facebook,gmail,google+,youtube

 Now a days most of the android application uses sliding menu. Many good apps like facebook, gmail,google+,youtube are using this type of menu.

To integrate sliding menu you need to use third party library. If you want to use actionbar in older version of android then sherlock library is also required.

Today I am going to explain how to use these library for sliding menu in your android application.

Output of the project is shown in below screenshot.






 You can download libraries and source code from following links.
      Sherlock Libraray
      Slidingmenu Library
      Project Source



activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Swipe left"
        android:textStyle="bold" />

</RelativeLayout>

menu.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <fragment
        android:id="@+id/frag_menu"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        class="com.ketan.slidingexample.Menufragment" />

</RelativeLayout>

menulist.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:divider="#000"
        android:dividerHeight="1dp"
        android:entries="@array/marray" />

</RelativeLayout>

 MainActivity.java

package com.ketan.slidingexample;

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

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.slidingmenu.lib.SlidingMenu;

public class MainActivity extends SherlockFragmentActivity implements Menufragment.MenuClickInterFace{
    SlidingMenu menu;
    TextView text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text=(TextView)findViewById(R.id.text);
        ActionBar ab = getSupportActionBar();
        ab.setHomeButtonEnabled(true);
        ab.setDisplayHomeAsUpEnabled(true);
        menu = new SlidingMenu(this);
        menu.setMode(SlidingMenu.LEFT);
        menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        menu.setShadowWidthRes(R.dimen.shadow_width);
        menu.setShadowDrawable(R.drawable.shadow);
        menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        menu.setFadeDegree(0.35f);
        menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        menu.setMenu(R.layout.menu);
        menu.setSlidingEnabled(true);
       
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        menu.toggle();
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onListitemClick(String item) {
        // TODO Auto-generated method stub
        text.setText(item);
    }
}


MenuFragment.java

package com.ketan.slidingexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockFragment;

public class Menufragment extends SherlockFragment {
    ListView list;
    MenuClickInterFace mClick;

    interface MenuClickInterFace {
        void onListitemClick(String item);
    }

    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        mClick = (MenuClickInterFace) activity;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        list = (ListView) getView().findViewById(R.id.list);
        list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                String i=(String) arg0.getItemAtPosition(arg2);
                mClick.onListitemClick(i);
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View v = inflater.inflate(R.layout.menulist, container, false);
        return v;
    }

}




Again download libraries and source code from following links and Njoy!!!
      Sherlock Libraray
      Slidingmenu Library
      Project Source

Friday 19 April 2013

Android TabNavigation like google play store app using PagerTabStrip

      Now a days fragments and swipy tabs are very popular. I have searched so much on google for tabs like playsotre app. And finally I have implemented it in one of my app.

       So today I am going to share it with you. It is simple example but I hope it may help you to get started with it.


Here is layout file which contains viewpager for page sliding and pagertabstrip to slide tabs.

activity_main.xml

<android.support.v4.view.ViewPager    
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <!--
    This title strip will display the currently visible page title, as well as the page
    titles for adjacent pages.
    -->

    <android.support.v4.view.PagerTabStrip
        android:id="@+id/pager_title_strip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:background="#676966"
        android:paddingBottom="4dp"
        android:paddingTop="4dp"
        android:textColor="#6CBD57" />

</android.support.v4.view.ViewPager>


Here is java file for main activity. In this tutorial I am using android.support.v4 library.
MainActivity.java


package com.example.tabnavigation;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainActivity extends FragmentActivity {

    //create object of FragmentPagerAdapter
    SectionsPagerAdapter mSectionsPagerAdapter;

    //viewpager to display pages
    ViewPager mViewPager;

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

        // Create the adapter that will return a fragment for each of the five
        // primary sections of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(
                getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

    }

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

    /**
     * A  FragmentPagerAdapter that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a DummySectionFragment (defined as a static inner class
            // below) with the page number as its lone argument.
            Fragment fragment = new DummySectionFragment();
            Bundle args = new Bundle();
            args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public int getCount() {
            // Show 5 total pages.
            return 5;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
            case 0:
                return "Section 1";
            case 1:
                return "Section 2";
            case 2:
                return "Section 3";
            case 3:
                return "Section 4";
            case 4:
                return "Section 5";
            }
            return null;
        }
    }

    /**
     * A dummy fragment representing a section of the app, but that simply
     * displays dummy text.
     */
    public static class DummySectionFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        public static final String ARG_SECTION_NUMBER = "section_number";

        public DummySectionFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            // Create a new TextView and set its text to the fragment's section
            // number argument value.
            TextView textView = new TextView(getActivity());
            textView.setGravity(Gravity.CENTER);
            textView.setText(Integer.toString(getArguments().getInt(
                    ARG_SECTION_NUMBER)));
            return textView;
        }
    }

}


Njoy!! Please let me know if you have any query or you have suggestion for me.

Saturday 9 February 2013

Store ArrayList in android SharedPreference

Here I am going to explain how to store arraylist in sharedpreference.
Let's say I have an arraylist as following.

ArrayList<String> myArrayList=new ArrayList<String>();

myArrayList.add("value1");
myArrayList.add("value2");
myArrayList.add("value3");
myArrayList.add("value4");
myArrayList.add("value5");
myArrayList.add("value6");

Store arraylist in sharedpreference

SharedPreference sPrefs=PreferenceManager.getDefaultSharedPreferences(context);
SharedPreference.Editor sEdit=sPrefs.edit();

for(int i=0;i<myArrayList.size();i++)
{
         sEdit.putString("val"+i,myArrayList.get(i);
}
 sEdit.putInt("size",myArrayList.size());
 sEdit.commit();

Retrive arraylist from sharedpreference

I am retriving values in another arraylist

ArrayList<String> myAList=new ArrayList<String>();
int size=sPrefs.getInt("size",0);

for(int j=0;j<size;j++)
{
          myAList.add(sPrefs.getString("val"+j));
}



Thursday 17 January 2013

Android widget-Gallary

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

    <Gallery xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/gallery"
   android:layout_width="fill_parent"
    android:layout_height="wrap_content"
/>
 
    <ImageView
        android:id="@+id/img"
        android:scaleType="fitXY"
     android:layout_width="fill_parent"
    android:layout_height="wrap_content"
/>

</LinearLayout>



GallaryActivity.java



package com.gallery;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
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.AdapterView.OnItemClickListener;

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

private int animalid[] = {
R.drawable.dogs,R.drawable.dolphin,R.drawable.horse,
R.drawable.lion,R.drawable.penguin,R.drawable.tiger,
R.drawable.zebra
};

Gallery gallery;
ImageView img;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
     
        gallery = (Gallery)findViewById(R.id.gallery);
        img = (ImageView)findViewById(R.id.img);
        gallery.setAdapter(new ImageAdapter(this));
     
        gallery.setOnItemClickListener(new OnItemClickListener()
        {
            public void onItemClick(AdapterView parent, View v, int position, long id)
            {
                //Toast.makeText(HelloGallery.this, "" + position, Toast.LENGTH_SHORT).show();
            img.setImageResource(animalid[position]);
            }
        });

     
    }
 
    public class ImageAdapter extends BaseAdapter {
        int mGalleryItemBackground;
        private Context mContext;
     
        public ImageAdapter(Context c) {
            mContext = c;
            TypedArray attr = mContext.obtainStyledAttributes(R.styleable.HelloGallery12);
            mGalleryItemBackground = attr.getResourceId(
                    R.styleable.HelloGallery12_android_galleryItemBackground, 0);
            attr.recycle();
        }

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

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView = new ImageView(mContext);

            imageView.setImageResource(animalid[position]);
            imageView.setLayoutParams(new Gallery.LayoutParams(150, 100));
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setBackgroundResource(mGalleryItemBackground);

            return imageView;
        }
    }
}


output:-




You can download full eclipse project source from Download Page