Pages

Monday, February 8, 2016

Android Services


Android Service is used for long-running processes that do not require user interaction, such as calling a web service and parsing response. Or processes that need to be running even if the application that started the service is not on the foreground such as playing mp3 files in a music player.

we need to distinguish between A Service and a Thread or an AsyncTask: Threads or Async task perform their tasks in a background thread thus they do not block the main thread, while a service performs its work in the main thread. so if a service is performing an intensive task such as calling a web service, it may block the main thread until it finishes. So for intensive tasks a service should run its work in a background thread.

A service runs in the same process of the application and keeps running until stopped by itself, stopped by the user or killed by the system if it needs memory.

Creating a service:

to create a service we create a class that extends android.app.Service and it would be like this:
public class DemoService extends Service {

@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}

}
next we need to define our service in our AndroidManifest.xml file:
<service android_name="DemoService"></service>
The service life cycle has the following events
  • onCreate(): called when the service is created.
  • onStart(): Called when the service starts by a call to startService(Intent intent).
  • onDestroy(): Called as the service is terminates.

Calling a service:

A service can be called from an activity in two ways:
  1. By calling startService(Intent intent).
  2. By binding to the service through an Binder object.

calling startService(Intent intent):

to start a service from an activity using this method, we create an intent and start the service like this:
Intent intent=new Intent(this,DemoService.class);
startService(intent);
the startService(intent) method causes the onStart() method of the service to be called, so the service can execute its work like this:
public class DemoService extends Service {

@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}

@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
doSomething();
}

public void doSomething(){
// do some work
}

}
the service will keep running until it stops itself via stop stopSelf() after finishing work:
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
doSomething();
stopSelf();
}
or it can be stopped from the activity via stopService(Intent intent).

Binding to a service through an Binder object:

As the service runs in the same process of the application the service has only one instance (singleton) instance running. you may want to keep reference to this instance to perform periodical tasks or to call the service methods themselves.

to make the service bind-able we extends Binder class and return an instance of it in the services onBind(Intent intent) method:
public class DemoService extends Service {

private final IBinder binder = new LocalBinder();
@Override
public IBinder onBind(Intent arg0) {
return binder;
}

public class LocalBinder extends Binder {
DemoService getService() {
return DemoService.this;
}
}

@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
doSomething();
stopSelf();
}

public void doSomething(){
// do something
}

}
then we bind the service from our activity by first creating a ServiceConnection object to handle the service connection/disconnection then binding to the service by an intent like this:
public class MainActivity extends Activity {

DemoService mService;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

ServiceConnection serviceConn=new ServiceConnection() {

/**
* service unbound, release from memory
**/
@Override
public void onServiceDisconnected(ComponentName name) {
mService=null;
}

/**
* service is bound, start its work
**/
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService=((LocalBinder)service).getService();
mService.doSomething();

}
};

@Override
protected void onResume() {
super.onResume();
// bind to the service by an intent
Intent intent=new Intent(this,DemoService.class);
// AUTO CREATE: creates the service and gives it an importance so that it wont be killed
// unless any process bound to it (our activity in this case) is killed to
bindService(intent, serviceConn, Context.BIND_AUTO_CREATE);
}

@Override
protected void onDestroy() {
super.onDestroy();
/ unbind the service whena ctivity is destroyed
unbindService(serviceConn);
}
}
notice that we unbind the service in the activitys onDestroy() method to disconnect from the service and stop it from executing any further

and thats was all about Android services, stay tuned for another Android tutorial.
Read More..

WinRAR 5 Latest Full Version Full No Need Crack 32bit 64bit

 

Compress, Encrypt, Package and Backup with only one utility

 

  • WinRAR is a powerful compression tool with many integrated additional functions to help you organize your compressed archives.
  • WinRAR puts you ahead of the crowd when it comes to compression. By consistently creating smaller archives, WinRAR is often faster than the competition. This will save you disk space, transmission costs AND valuable working time as well.
  • WinRAR supports all popular compression formats (RAR, ZIP, CAB, ARJ, LZH, ACE, TAR, GZip, UUE, ISO, BZIP2, Z and 7-Zip).
  • WinRAR is ideal for multimedia files. WinRAR automatically recognizes and selects the best compression method. The special compression algorithm compresses multimedia files, executables and object libraries particularly well.
  • WinRAR allows you to split archives into separate volumes easily, making it possible to save them on several disks for example.
  • WinRAR is also ideal, if you are sending data through the web. Its 256 bit password encryption and its authenticated signature technology will give you the peace of mind you have been looking for.
  • WinRAR is a trial product, meaning you have the chance to thoroughly test it. The program can be used absolutely free of charge for 40 days!
  • WinRAR licenses are valid for all available language and platform versions. If you have purchased several licenses, you can even mix versions to meet your own personal needs.
  • Support .RAR5 extension.


Read More..

Download GO Launcher EX Prime 5 09 Build 346 pro Full

Introducing the latest version of GO Launcher EX Prime + key file
Prime Features Unlocked
The official version is published in Google Play

With the HD version of GO Launcher 1.19

One of the interesting features of the Android operating system, it is interesting Personalize. For example, you can use the main menu or Home screen of your Android phone with your taste perfectly matching your makeup. Very high level of applications that allow you to customize your phone can be pointed to the launcher. Launcher full range of tools at your disposal that can help change the graphics and even create dissension in your Android phone. One of the best, and perhaps we can dare say the best launcher for Android smartphones so far produced very popular Launcher GO Launcher EX Prime is now called Go Dev.
GO Launcher EX Prime
By GO Launcher EX Prime features and amenities are provided below:
** Increase Home screen pages
** Option in the menu or applications folder
** Ability to remove the software to prevent the display of icons in the menu
** Exclusive widgets that can use different themes:
** (Task Manager, Contacts, Messages, Calendar, Search, All, Facebook, email, switches, Notes)
** Take advantage of the dock loading dock and also help customize the images in the gallery
** Exclusive lock screen that can use different themes
** Exclusive Software Change font launcher without having to root the phone
** Ability to hide status bar
** Take advantage of the Christmas menu
** Ability to remove applications quickly and easily
** Ability to rotate the screen to the main screen and the menu
** Online using a variety of themes and beautiful
** Ability to remove the icons and rename them
** Set the matrix size of icons in the menu
** 16 different effects to transition between pages
** 15 stunning effects in the menus
** 5 beautiful effect at the time of entry and exit from the application menu.
** Ability to hide the 3rd tab on the top menu
** Ability icons with your favorite pictures
** New user interface on the display theme
** Can Fix widget icon and move the home to prevent unwanted
** Ability to determine the size of icons and widgets on the Home screen and the menu pages
** Display a grid when moving icons
* Ability to change the size of icons in the menu label and the Home Screen Pages
** A quick search in the software by entering the name of the desired software
* Full support for tablet 7 to 10-inch
** Editable applications and folders with icons icon gallery
Add list widgets and apps and themes:
Classic Theme GO Launcher EX 1.7
GO Bookmark Widget 1.3
GO Clock Widget 1.5
GO Contact Widget 1.8
GO Contacts 1.46
GO Contacts EX 2.08
GO Default Search Widget 1.2
GO Launcher EX Notification 2.2
GO Launcher EX UI3.0 theme 2.02
GO Locker 1.65
GO Media Manager 1.1
GO Note Widget 2.0
GO Power Master 3.11
GO Switch Widget 1.61
GO TwiWidget 2.2
Love Theme GO Launcher EX 1.6
Plate Theme 4 GO Launcher EX 2.0
This is a fantastic launcher Android phones we recommend to all holders.
Changes in this version GO Launcher EX Prime 5.09:
What’s New
Please light up all to help us serve you better!
(Improve) New App Drawer, cleaner, more elegant and easier to use.
(New feature) Holding App Icon brings more functions, easy to hide icon and view app info.
(Improve) Improve the usability on folder editing.
(Improve) Bug fixed


Thanks : http://apkhouse.com <<< Visit :)
Read More..

OpenCV Android Programming By Example

Develop vision-aware and intelligent Android applications with the robust OpenCV library

OpenCV Android Programming By Example

About This Book
  • This is the most up-to-date book on OpenCV Android programming on the market at the moment. There is no direct competition for our title.
  • Based on a technology that is increasing in popularity, proven by activity in forums related to this topic.
  • This book uniquely covers applications such as the Panoramic viewer and Automatic Selfie, among others.
Who This Book Is For
If you are an Android developer and want to know how to implement vision-aware applications using OpenCV, then this book is definitely for you.

It would be very helpful if you understand the basics of image processing and computer vision, but no prior experience is required

What You Will Learn
  • Identify and install all the elements needed to start building vision-aware Android applications
  • Explore image representation, colored and gray scale
  • Recognize and apply convolution operations and filtering to deal with noisy data
  • Use different shape analysis techniques
  • Extract and identify interest points in an image
  • Understand and perform object detection
  • Run native computer vision algorithms and gain performance boosts
In Detail
Starting from the basics of computer vision and OpenCV, well take you all the way to creating exciting applications. You will discover that, though computer vision is a challenging subject, the ideas and algorithms used are simple and intuitive, and you will appreciate the abstraction layer that OpenCV uses to do the heavy lifting for you. Packed with many examples, the book will help you understand the main data structures used within OpenCV, and how you can use them to gain performance boosts. Next we will discuss and use several image processing algorithms such as histogram equalization, filters, and color space conversion. You then will learn about image gradients and how they are used in many shape analysis techniques such as edge detection, Hough Line Transform, and Hough Circle Transform. In addition to using shape analysis to find things in images, you will learn how to describe objects in images in a more robust way using different feature detectors and descriptors.

By the end of this book, you will be able to make intelligent decisions using the famous Adaboost learning algorithm.

Style and approach
An easy-to-follow tutorial packed with hands-on examples. Each topic is explained and placed in context, and the book supplies full details of the concepts used for added proficiency.

Read More..

KIM KARDASHIAN HOLLYWOOD 2 8 Mod Unlimited Cash Star Android Obb Download

KIM KARDASHIAN HOLLYWOOD 2.8 Apk Mod Data Files Download

KIM KARDASHIAN HOLLYWOOD 2.8 Apk Mod Data Files Download iAndroGames 

Note: Download All The Parts Provided and extract any of them, it will automatically extract all the parts. Install .apk File And place data folder in SDcard/Android/obb/ and Start playing. Mod comes with infinite cash, stars, rom points, prof points, antiban, Max levels.

DOWNLOAD LINKS

 

Download From PlayStore
Click Here For APK+Data Files Download
Read More..

Building Android Content Providers

Content providers are the way that Android applications can share info between each other. an application can ask for info from another application using content providers.

In this post were going to create a content provider to access data from our previous Employees simple application from the SQLite post.

to remind you the database has two tables Employees and Dept

remember that any content provider must provide the following:
  1. A URi from which we can run queries.
  2. MIME type corresponding to the content.
  3. Insert() method.
  4. Update() methd.
  5. Delete() method.

Creating the content type:

first we will create a new class, I will call it EmployeesContentProvider and choose its super class to be ContentProvider. the class initially will be like this:
package mina.android.DatabaseDemo;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

public class EmployeesContentProvider extends ContentProvider {
DatabaseHelper db;
public static final Uri CONTENT_URI=Uri.parse("content://employees");
@Override
public int delete(Uri arg0, String arg1, String[] arg2) {
// TODO Auto-generated method stub
return 0;
}

@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}

@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
return null;
}

@Override
public boolean onCreate() {
// TODO Auto-generated method stub
return false;
}

@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// TODO Auto-generated method stub
return null;
}

@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}

}


we added a member of type DatabaseHelper db to hold a reference to our database.
also we added a static URi object that represents the URi of our content provider.
it has all the abstract methods implementations of the ContentProvider class. so lets check each method

onCreate() method:

the onCreate() method is the first method invoked when the content provider is created (similar to the Activitys onCreate() method). here you can load your database or check for files you may read/write to them.
the method return a Boolean. it should be true if everything is ok, otherwise it should be false.
in our case we will just reference our SQLite database:
@Override
public boolean onCreate() {
// TODO Auto-generated method stub
db=new DatabaseHelper(this.getContext());
if(db==null)
return false;
else
return true;
}

query() method:

the query() method is the method that gets invoked when a content provider data is requested by a URi.

but first lets talk a little about content providers URI.
the content provider URi has the following format:
content://Authority/[(n) path]/[instance indentifier]
explanation:
  • the URI starts with content:// scheme.
  • the authority is a unique identifier for the content provider.
  • the authority can be followed by one or more paths (optional) refer to data paths within the content.
  • there can be an instance identifier that refers to a specific data instance.
for example we can have a URi like this content://Employees/Marketing//11.
this URi has Employees as the authority, Marketing as a data path and 11 as an instance (employee) identifier.

back to our query method, we have the following parameters:
  1. Uri: the URi requested.
  2. String [] projection: representing the columns (projection) to be retrieved.
  3. String[] selection: the columns to be included in the WHERE clause.
  4. String[] selectionArgs: the values of the selection columns.
  5. String sortOrder: the ORDER BY statement.
the first step in our query method is to parse the client URi.
we expect the URi to be in one of the following forms:
  1. content://employees/: retrieves all employees.
  2. content://employees/id: retrieves a certain employee by ID.
  3. content://employess/IT: retreives employees of IT Dept.
  4. content://employess/HR: retrieves employees of HR Dept.
  5. content://employees/Sales: retreives employees of sales Dept.
so we will add some constatnt values to our class to refer to the above URis:
//authority and paths
public static final String AUTHORITY="employees";
public static final String ITPATH="IT";
public static final String HRPATH="HR";
public static final String SALESPATH="Sales";


//URiMatcher to match client URis
public static final int ALLEMPLOYEES=1;
public static final int SINGLEEMPLOYEE=2;
public static final int IT=3;
public static final int HR=4;
public static final int SALES=5;
then were going to define a URiMatcher object that matches the client URi
static final UriMatcher matcher=new UriMatcher(UriMatcher.NO_MATCH);
static{
matcher.addURI(AUTHORITY,null,ALLEMPLOYEES);
matcher.addURI(AUTHORITY, ITPATH, IT);
matcher.addURI(AUTHORITY, HRPATH, HR);
matcher.addURI(AUTHORITY, SALESPATH, SALES);
//you can use * as a wild card for any text
matcher.addURI(AUTHORITY, "#", SINGLEEMPLOYEE);
}
the static initializer block loads the URimatcher objects with the values to match when the class initializes.
so lets write our query method:
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder builder=new SQLiteQueryBuilder();

builder.setTables(DatabaseHelper.viewEmps);

String order=null;
Cursor result=null;
if(sortOrder!=null)
order=sortOrder;
int match=matcher.match(uri);
switch(match)
{
case ALLEMPLOYEES:
//content://employees//id
result=builder.query(db.getWritableDatabase(), projection, selection, selectionArgs, null, null, sortOrder);
break;
case SINGLEEMPLOYEE:
//content://employees//id
Listsegments=uri.getPathSegments();
String empID=segments.get(0);
result=db.getEmpByID(empID);

break;
case IT:
//content://employees//IT
result=db.getEmpByDept("IT");
result=builder.query(db.getReadableDatabase(), projection, db.colDeptName+"=?", new String[]{"IT"}, null, null, sortOrder);
break;
case HR:
//content://employees//HR
result=db.getEmpByDept("HR");
result=builder.query(db.getReadableDatabase(), projection, db.colDeptName+"=?", new String[]{"HR"}, null, null, sortOrder);
break;
case SALES:
//content://employees//Sales
result=db.getEmpByDept("Sales");
result=builder.query(db.getReadableDatabase(), projection, db.colDeptName+"=?", new String[]{"Sales"}, null, null, sortOrder);

break;

}

return result;
}

the function just parses the URi and returns the data in a cursor.

Insert() method:
the insert methods inserts a new record to the db;
the insert method has the following form:
public Uri insert(Uri uri, ContentValues values) {

return null;
}
the method has two parameters:
  1. URi uri: the URi of the content provider, we need to check its correct.
  2. ContentValues values: object holding the info of the new item to be inserted.
the method returns the URi of the newly inserted item to be used for further manipulations.
so heres the implentation:
@Override
public Uri insert(Uri uri, ContentValues values) {
int match=matcher.match(uri);
//not the Uri were expecting
long newID=0;
if(match!=1)
throw new IllegalArgumentException("Wrong URi "+uri.toString());
if(values!=null)
{
newID=db.getWritableDatabase().insert(DatabaseHelper.employeeTable, DatabaseHelper.colName, values);
return Uri.withAppendedPath(uri, String.valueOf(newID));

}
else
return null;
}
we first check the Uri if it is not correct, throw an exception.
then check the content values object, if null return null otherwise insert the new item and return the URi with the id of the new item.
the Update() method:
the update method updates existing record(s) and returns the number of updated rows.
a trick rises from the fact that you need to specify whether to update a collection of records or a single record, based on the URi.
the method has the following parameters:
  1. URi uri: the URi of the content provider, we need to check its correct.
  2. ContentValues values: object holding the info of the new item to be inserted.
  3. String Selection : the filter to match the rows to update
  4. String [] selectionArgs : the values of the filter parameters
heres the implementation of the update method:
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int match=matcher.match(uri);
//not the Uri were expecting
int rows=0;
//update single instance
if(match==2)
{
if(values!=null)
{
Listsegments=uri.getPathSegments();
String empID=segments.get(0);
rows=db.getWritableDatabase().update(DatabaseHelper.employeeTable, values,DatabaseHelper.colID+"=?", new String []{empID});

}

}
//update all emps in a certain dept
else if(match==3 ||match==4||match==5)
{
Listsegments=uri.getPathSegments();
String deptName=segments.get(0);
int DeptID=db.GetDeptID(deptName);
rows=db.getWritableDatabase().update(db.employeeTable, values,db.colDept+"=?", new String []{String.valueOf(DeptID)});

}
return rows;
}
the Delete() method:
the delete method has the following parameters:
  1. Uri uri: the URi of the content provider.
  2. String Condition: the condition of the delete statement.
  3. String[] args: the delete condition arguments

so heres the implementation:
@Override
public int delete(Uri uri, String where, String[] args) {

int match=matcher.match(uri);
//expecting the URi to be in the form of
if(match==1)
{
SQLiteDatabase dataBase=db.getWritableDatabase();
return dataBase.delete(db.employeeTable, where, args);
}
else
return 0;
}
we just check for the URi and perform a delete command.
The getType() method:
the last mthod to implement is getType() method which returns the MIME type associated with the URi passed to it.
if the URi is of a group of employees, then the MIME type is a collection type, otherwise its of an instance type
@Override
public String getType(Uri uri) {
int match=matcher.match(uri);
// single employee
if(match==2)
{
return "mina.android.Employee";
}
//collection of employees
else
{
return "mina.android.Employees";
}
}
Modifying the Manifest.xml file:
the last thing we need to do is to add an entry in our applications manifest.xml file to register our class as a content provider class.
so add this entry just below the <application>
<provider android_name="mina.android.DatabaseDemo.EmployeesContentProvider" 
android_authorities="employees"/>

the
when an application requests data through our content provider, Android system will search all the manifest files of all aplications on the device and when it finds such an entry, it will process the request

Testing the content provider:
now suppose you are in another activity and you want to use our activity.
Testing queries:
to make a query to retrieve all employees:
Uri empsUri=Uri.parse("content://employees");
Cursor cursor=getContentResolver().query(empsUri, null, null, null, null);Cursor cursor=getContentResolver().query(empsUri, null, null, null, null);
the cursor should have all the records.
to retrieve a certain employee by ID or all employees in a certain department:
Uri empUri=Uri.parse("content://employees//5");
Uri empDeptUri=Uri.parse("content://employees//Sales");

Inserting:
Uri empsUri=Uri.parse("content://employees");
ContentValues cvs=new ContentValues();
cvs.put("EmployeeName", "Mark Anderson");
cvs.put("Age", 35);
cvs.put("Dept", 1);
// URi of the new inserted item
Uri newEmp=getContentResolver().insert(empsUri, cvs);

Updating:
to update a single employee:
//Uri with the id of the employee
Uri empsUri=Uri.parse("content://employees/8");

Cursor cursor=getContentResolver().query(empsUri, null, null, null, null);
txt.setText(String.valueOf(cursor.getCount()));

ContentValues cvs=new ContentValues();
cvs.put("EmployeeName", "Mina Samy mod");
cvs.put("Age", 35);
cvs.put("Dept", 1);
// number of rows modified
int rowsNumber=getContentResolver().update(empsUri, cvs, "EmployeeID=?", new String[]{"8"});
to update all employees in a certain department
Uri empsUri=Uri.parse("content://employees/Sales");

Cursor cursor=getContentResolver().query(empsUri, null, null, null, null);
txt.setText(String.valueOf(cursor.getCount()));

ContentValues cvs=new ContentValues();
cvs.put("EmployeeName", "mod");
cvs.put("Age", 35);
cvs.put("Dept", 1);
int rowsNumber=getContentResolver().update(empsUri, cvs, "colDept=?", new String[]{"1"});

as a matter of fact, in both cases we dont need to specify the wher clause and the where parameters as they are implicitly specified in the URi. so we just can replace the update statement to be like this:
int rowsNumber=getContentResolver().update(empsUri, cvs, null,null);

Deleting:
I left the delete operation open to any criteria, you can delete a single employee or employees of a certain department or even all employees
Uri empsUri=Uri.parse("content://employees");
// delete employee of id 8
int rowsNumber=getContentResolver().delete(empsUri,"EmployeeID=?",new String[]{"8"});

Final Word:
creating a content provider for a certain type of data can be done in many ways, this example can be implemented in several variations.

another thing is that you need to create a strongly typed class for you data model to be used by clients accessing your content. in this example when I tested the query i wrote the column names of the database as strings like this: "EmployeeID" and "EmployeeName".
this is not ideal in a production release of an application. I should created a class library that holds all the info about the database to be used by other client applications.

you can download the source code for this example from here.
Read More..

Gallery View Android Developer Tutorial

Continuing on the Views, I have taken up the Gallery View that helps in showing Images as in a gallery. As per the android documentation, this is the definition: “A Gallery is a View commonly used to display items in a horizontally scrolling list that locks the current selection at the center.”


For this the layout xml in this case, the main.xml will have a ‘Gallery’ element as shown below:

<Gallery
    android_id="@+id/Gallery01"
    android_layout_width="fill_parent"
    android_layout_height="wrap_content"></Gallery>
<ImageView android_id="@+id/ImageView01"
    android_layout_width="wrap_content"
    android_layout_height="wrap_content"></ImageView>

It also has an ImageView element which is used to show the selected Image in a larger ImageView. Here is how it would look when executed.

Now, I create a GalleryView Activity. To view a set of images of Antartica, I have created small sized images of antartica and stored them in the res/drawable-ldpi folder starting form antartica1.png to antartica10.png.

I create an array of these resources/images in my activity with the following code:

Integer[] pics = {
R.drawable.antartica1,
R.drawable.antartica2,
R.drawable.antartica3,
R.drawable.antartica4,
R.drawable.antartica5,
R.drawable.antartica6,
R.drawable.antartica7,
R.drawable.antartica8,
R.drawable.antartica9,
R.drawable.antartica10
};

As we have seen with all the other views so far, we need to have an adapter that associates the view with the data. Here the view is Gallery and the data is the above mentioned 10 images. An Adapter plays the role of linking the two as shown below:

Gallery ga = (Gallery)findViewById(R.id.Gallery01);
ga.setAdapter(new ImageAdapter(this));

However, we do not have a readymade implementation of the ImageAdapter. We have to create our own implementation of the same by extending the BaseAdapter class. This is the core of the code in this example. The moment we extend the BaseAdapter, we have to override 4 methods. They are getCount(), getItem(), getItemId() and getView().

Before we go to each of them, let us see the constructor of the ImageAdpater:

public class ImageAdapter extends BaseAdapter {


private Context ctx;
int imageBackground;


public ImageAdapter(Context c) {
    ctx = c;
    TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
    imageBackground = ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
    ta.recycle();
}

}

It takes the context that is passed to the constructor. We need to examine this code a little. First, we can define our own resources or attributes in an XML file. Those attributes can be retrieved through the method obtainStyledAttributes. This is a method on the Context object. The returned value needs to be stored in a TypedArray object. A TypedArray is nothing but a container for an array of values that are returned by obtainStyledAttributes.

So, in my example, I have created an xml file by name attributes.xml in the res/values folder with the following content:

<resources>
     <declare-styleable name="Gallery1">
    <attr name="android:galleryItemBackground"/>
     </declare-styleable>
</resources>

Here Gallery1 is a custom name for a style defined by us. In this style, we are trying to say what should be the background of our images. For that we are using a pre-defined backgournd in R.attr class as galleryItemBackground.

So, this is accessed in the ImageAdapter contructor through the line

ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
ta.recycle();

The number 1 is to say that it is the first element in the attributes.xml file under the styelable Gallery1.

The rest of the over ridden methods are simple:

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


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

@Override
public long getItemId(int arg0) {
    return arg0;
}


@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
    ImageView iv = new ImageView(ctx);
    iv.setImageResource(pics[arg0]);
    iv.setScaleType(ImageView.ScaleType.FIT_XY);
    iv.setLayoutParams(new Gallery.LayoutParams(150,120));
    iv.setBackgroundResource(imageBackground);
    return iv;
}

The getView actually returns a View object when called. Here I have overridden it to return a ImageView object with the selected image inside it alosn with some scale, layout paramaters and the image background set.

Finally in the onCreate() method of the activity I have captured the onClick event on a Gallery item and within that I have toasted a message as well as displayed the image in a bigger manner below the gallery:

ga.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    Toast.makeText(getBaseContext(), "You have selected picture " + (arg2+1) + " of Antartica",
        Toast.LENGTH_SHORT).show();
    imageView.setImageResource(pics[arg2]);
}
});

That is it. You may download the complete code from here.

Read More..