Few moment with Android


1. Android Core Building Blocks                                                

An android component is simply a piece of code that has a well defined life cycle e.g. Activity, Receiver, Service etc.

(i) Activity : An activity is a class that represents a single screen. It is like a Frame in AWT.

(ii) View: A view is the UI element such as button, label, text field etc. Anything that you see is a view.

(iii) Intent ::

Intent is used to invoke components. It is mainly used to:

  • Start the service
  • Launch an activity
  • Display a web page
  • Display a list of contacts
  • Broadcast a message
  • Dial a phone call etc.

For example, you may write the following code to view the webpage.

// Implicit Intent by specifying a URI

Intent i = new Intent(Intent.ACTION_VIEW,

Uri.parse(http://www.example.com”));

// Starts Implicit Activity

startActivity(i);

// Explicit Intent

  1. Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
  2.  startActivity(i);

(iv) Service: Service is a background process that can run for a long time.

There are two types of services local and remote. Local service is accessed from within the application whereas remote service is accessed remotely from other applications running on the same device.

(v) Content Provider : Content Providers are used to share data between the applications.

(vi) Fragment : Fragments are like parts of activity. An activity can display one or more fragments on the screen at the same time.

(vi) AndroidManifest.xml : The AndroidManifest.xml file contains information of your package, including components of the application such as activities, services, broadcast receivers, content providers etc.

It performs some other tasks also:

  • It is responsible to protect the application to access any protected parts by providing the permissions.
  • It also declares the android api that the application is going to use.
  • It lists the instrumentation classes. The instrumentation classes provides profiling and other informations. These informations are removed just before the application is published etc.

This is the required xml file for all the android application and located inside the root directory.

(vii) Android R.java file : Android R.java is an auto-generated file by aapt (Android Asset Packaging Tool) that contains resource IDs for all the resources of res/ directory.

If you create any component in the activity_main.xml file, id for the corresponding component is automatically created in this file. This id can be used in the activity source file to perform any action on the component.

(viii) Android Hide Title Bar Example : The requestWindowFeature(Window.FEATURE_NO_TITLE) method of Activity must be called to hide the title. But, it must be coded before the setContentView method.

  1.    @Override
  2.     protected void onCreate(Bundle savedInstanceState) {
  3.         super.onCreate(savedInstanceState);
  4.         requestWindowFeature(Window.FEATURE_NO_TITLE);//will hide the title not the title bar
  5.         setContentView(R.layout.activity_main);
  6.     }
  7. }

The setFlags() method of Window class is used to display content in full screen mode. You need to pass theWindowManager.LayoutParams.FLAG_FULLSCREEN constant in the setFlags method.

  1. @Override  
  2. protected void onCreate(Bundle savedInstanceState) {
  3.     super.onCreate(savedInstanceState);
  4.     requestWindowFeature(Window.FEATURE_NO_TITLE);
  5.     //code that displays the content in full screen mode  
  6.     this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
  7.                 WindowManager.LayoutParams.FLAG_FULLSCREEN);//int flag, int mask
  8.     setContentView(R.layout.activity_main);
  9. }

(ix) ArrayAdapter : A concrete BaseAdapter that is backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource.

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

To use something other than TextViews for the array display, for instance, ImageViews, or to have some of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the type of view you want.

(x) Android Activity Lifecycle : Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. The android Activity is the subclass of ContextThemeWrapper class.

An activity is the single screen in android. It is like window or frame of Java.

By the help of activity, you can place all your UI components or widgets in a single screen.

The 7 lifecycle method of Activity describes how activity will behave at different states.

Let’s see the 7 lifecycle methods of android activity.

Method

Description

onCreate

called when activity is first created.

onStart

called when activity is becoming visible to the user.

onResume

called when activity will start interacting with the user.

onPause

called when activity is not visible to the user.

onStop

called when activity is no longer visible to the user.

onRestart

called after your activity is stopped, prior to start.

onDestroy

called before the activity is destroyed.

  1. package com.example.activitylifecycle;

  2. import android.os.Bundle;

  3. import android.app.Activity;

  4. import android.util.Log;

  5. import android.view.Menu;

  6. public class MainActivity extends Activity {

  7.     @Override

  8.     protected void onCreate(Bundle savedInstanceState) {

  9.         super.onCreate(savedInstanceState);

  10.         setContentView(R.layout.activity_main);

  11.         Log.d(“lifecycle”,“onCreate invoked”);  

  12.     }

  13.     @Override

  14.     protected void onStart() {

  15.         super.onStart();

  16.          Log.d(“lifecycle”,“onStart invoked”);  

  17.     }

  18.     @Override

  19.     protected void onResume() {

  20.         super.onResume();

  21.          Log.d(“lifecycle”,“onResume invoked”);  

  22.     }

  23.     @Override

  24.     protected void onPause() {

  25.         super.onPause();

  26.          Log.d(“lifecycle”,“onPause invoked”);  

  27.     }

  28.     @Override

  29.     protected void onStop() {

  30.         super.onStop();

  31.          Log.d(“lifecycle”,“onStop invoked”);  

  32.     }

  33.        @Override

  34.     protected void onRestart() {

  35.         super.onRestart();

  36.          Log.d(“lifecycle”,“onRestart invoked”);  

  37.     }

  38.     @Override

  39.     protected void onDestroy() {

  40.         super.onDestroy();

  41.          Log.d(“lifecycle”,“onDestroy invoked”);  

  42.     }

  43. }

2) Who is the founder of Android?

Andy Rubin.

3) What are the code names of android?

  1. Aestro
  2. Blender
  3. Cupcake
  4. Donut
  5. Eclair
  6. Froyo
  7. Gingerbread
  8. Honycomb
  9. Ice Cream Sandwitch
  10. Jelly Bean
  11. Kitkat

4) What are the advantages of android?

Open-source: It means no licence, distribution and development fee.

Platform-independent: It supports windows, mac and linux platforms.

Supports various technologies: It supports camera, bluetooth, wifi, speech, EDGE etc. technologies.

Highly optimized Virtual Machine: Android uses highly optimized virtual machine for mobile devices, called DVM (Dalvik Virtual Machine).

5) Does android support other language than java?

Yes, android app can be developed in C/C++ also using android NDK (Native Development Kit). It makes the performance faster. It should be used with android SDK.

6) What are the core building blocks of android?

The core building blocks of android are:

  • Activity
  • View
  • Intent
  • Service
  • Content Provider
  • Fragment etc.

7) What is the name of database used in android?

SQLite: An opensource and lightweight relational database for mobile devices.

8) What is AAPT?

AAPT is an acronym for android asset packaging tool. It handles the packaging process.

9) What is ADB?

ADB stands for Android Debug Bridge. It is a command line tool that is used to communicate with the emulator instance.

10) What is NDK?

NDK stands for Native Development Kit. By using NDK, you can develop a part of app using native language such as C/C++ to boost the performance.

Expert Level Question                                                                                                          

1. What is the relationship between the life cycle of an AsyncTask and an Activity? What problems can this result in? How can these problems be avoided?

Answer:: An AsyncTask is not tied to the life cycle of the Activity that contains it. So, for example, if you start an AsyncTask inside an Activity and the user rotates the device, the Activity will be destroyed (and a new Activity instance will be created) but the AsyncTask will not die but instead goes on living until it completes.

Then, when the AsyncTask does complete, rather than updating the UI of the new Activity, it updates the former instance of the Activity (i.e., the one in which it was created but that is not displayed anymore!). This can lead to an Exception (of the type java.lang.IllegalArgumentException: View not attached to window manager if you use, for instance, findViewById to retrieve a view inside the Activity).

There’s also the potential for this to result in a memory leak since the AsyncTask maintains a reference to the Activty, which prevents the Activity from being garbage collected as long as the AsyncTask remains alive.

For these reasons, using AsyncTasks for long-running background tasks is generally a bad idea . Rather, for long-runningbackground tasks, a different mechanism (such as a service) should be employed.

2. There are four Java classes related to the use of sensors on the Android platform. List them and explain the purpose of each.

Answer :: The four Java classes related to the use of sensors on the Android platform areL

  • Sensor: Provides methods to identify which capabilities are available for a specific sensor.
  • SensorManager: Provides methods for registering sensor event listeners and calibrating sensors.
  • SensorEvent: Provides raw sensor data, including information regarding accuracy.
  • SensorEventListener: Interface that defines callback methods that will receive sensor event notifications.

3.What is DDMS? Describe some of its capabilities.

Answer : DDMS is the Dalvik Debug Monitor Server that ships with Android. It provides a wide array of debugging features including:

  • port-forwarding services
  • screen capture
  • thread and heap information
  • network traffic tracking
  • incoming call and SMS spoofing
  • simulating network state, speed, and latency
  • location data spoofing

4. What is Dalvik Virtual Machine?

The name of Android’s virtual machine. The Dalvik VM is an interpreter-only virtual machine that executes files in the Dalvik Executable (.dex) format, a format that is optimized for efficient storage and memory-mappable execution. The virtual machine is register-based, and it can run classes compiled by a Java language compiler that have been transformed into its native format using the included “dx” tool. The VM runs on top of Posix-compliant operating systems, which it relies on for underlying functionality (such as threading and low level memory management). The Dalvik core class library is intended to provide a familiar development base for those used to programming with Java Standard Edition, but it is geared specifically to the needs of a small mobile device.

5. What is Android Runtime?

Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language. Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included “dx” tool.

6. What is the Open Handset Alliance?

The OHA is a consortium of 84 technology and mobile companies that have joined hands to accelerate innovation in mobile technology and at the same time offer the end users a better, cost-effective and richer mobile experience. Members of this include Google, HTC, Sony, Dell, Intel, Motorola, Qualcomm, Texas Instruments, Samsung, LG, T-Mobile, Nvidia. The OHA was started on 5 November 2007 by Google and 34 other companies. Android is the main software of the alliance.

7. What is the difference between Service and Thread?

Service is like an Activity but has no interface. Probably if you want to fetch the weather for example you won’t create a blank activity for it, for this you will use a Service. It is also known as Background Service because it performs tasks in background. A Thread is a concurrent unit of execution. You need to know that you cannot update UI from a Thread. You need to use a Handler for this.

8.What is the importance of XML-based layouts?

The use of XML-based layouts provides a consistent and somewhat standard means of setting GUI definition format. In common practice, layout details are placed in XML files while other items are placed in source files.

9. What are the steps in creating a bounded service through AIDL.

1. create the .aidl file, which defines the programming interface

2. implement the interface, which involves extending the inner abstract Stub class as well as implanting its methods.

3. expose the interface, which involves implementing the service to the clients.

10. What data types are supported by AIDL?

AIDL has support for the following data types:

string

charSequence

List

Map

all native Java data types like int, long, char and Boolean

11.What is the difference between a regular bitmap and a nine-patch image?

In general, a Nine-patch image allows resizing that can be used as background or other image size requirements for the target device. The Nine-patch refers to the way you can resize the image: 4 corners that are unscaled, 4 edges that are scaled in 1 axis, and the middle one that can be scaled into both axes.

Advertisements

Android : Page Swiping using ViewPager


 

As a follow up on my last Fragments post, I thought it would be useful to include another Honeycomb feature which is the View Pager that implements for page swiping UI pattern.

In this example, I’ve re-used the Fragment implements from the Tabs post.

Requirements

To implement a Tabbed, using fragments on devices running Android 2.1 or higher, you’ll need to include the Android Compatibility library.  In my example, I’m using Compatibility library v4

Step-by-step

  1. Define the ViewPager layout
  2. Define the FragmentActivity container for the PageViewer
  3. Define the PagerAdapter

The Code

The ViewPager layout

The ViewPager layout (viewpager_layout.xml) simply declares the ViewPager class from the v4 compatibility library.

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical"
  >
  <android.support.v4.view.ViewPager
    android:id="@+android:id/viewpager"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />
</LinearLayout>

Defining the FragmentActivty

Our main FragmentActivity is going to host the ViewPager layout viewpager_layout.xml and initialise theViewPager with an adapter that managers the fragments that are displayed when the user swipes between pages.  In my implementation, I simply instantiate the Fragments upfront and supply them in a list to the

constructor of the PagerAdapter PagerAdaptor.java.

As I mentioned in the intro, I reused the fragment implementations from my previous Fragment post where fragment 1 is Red, fragment 2 is Green and fragment 3 is Blue. After all, the design goal of Fragments is code/UI reuse.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
 *
 */
package com.andy.fragments.viewpager;
 
import java.util.List;
import java.util.Vector;
 
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
 
import com.andy.R;
import com.andy.fragments.tabs.Tab1Fragment;
import com.andy.fragments.tabs.Tab2Fragment;
import com.andy.fragments.tabs.Tab3Fragment;
 
/**
 * The <code>ViewPagerFragmentActivity</code> class is the fragment activity hosting the ViewPager
 * @author mwho
 */
public class ViewPagerFragmentActivity extends FragmentActivity{
    /** maintains the pager adapter*/
    private PagerAdapter mPagerAdapter;
    /* (non-Javadoc)
     * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.viewpager_layout);
        //initialsie the pager
        this.initialisePaging();
    }
 
    /**
     * Initialise the fragments to be paged
     */
    private void initialisePaging() {
 
        List<Fragment> fragments = new Vector<Fragment>();
        fragments.add(Fragment.instantiate(this, Tab1Fragment.class.getName()));
        fragments.add(Fragment.instantiate(this, Tab2Fragment.class.getName()));
        fragments.add(Fragment.instantiate(this, Tab3Fragment.class.getName()));
        this.mPagerAdapter  = new PagerAdapter(super.getSupportFragmentManager(), fragments);
        //
        ViewPager pager = (ViewPager)super.findViewById(R.id.viewpager);
        pager.setAdapter(this.mPagerAdapter);
    }
}

Defining the PagerAdapter

The PagerAdapter class needs to extend FragmentPagerAdapter.  The most basic requirement for us, is to implement getItem(int position) and getCount().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
 *
 */
package com.andy.fragments.viewpager;
 
import java.util.List;
 
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
 
/**
 * The <code>PagerAdapter</code> serves the fragments when paging.
 * @author mwho
 */
public class PagerAdapter extends FragmentPagerAdapter {
 
    private List<Fragment> fragments;
    /**
     * @param fm
     * @param fragments
     */
    public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        this.fragments = fragments;
    }
    /* (non-Javadoc)
     * @see android.support.v4.app.FragmentPagerAdapter#getItem(int)
     */
    @Override
    public Fragment getItem(int position) {
        return this.fragments.get(position);
    }
 
    /* (non-Javadoc)
     * @see android.support.v4.view.PagerAdapter#getCount()
     */
    @Override
    public int getCount() {
        return this.fragments.size();
    }
}

Here is what it looks like as we page from left-to-right:

Make a Very fast Android emolator


Testing on multiple mobile devices is costly, time consuming and the default Android emulator is notoriously slow. So, what should we do? That’s easy – start using a properly fast Android emulator.
When developing Android applications, you have to keep in mind all the different Android OS versions and various screen sizes and resolutions. The main objective before releasing an application is to find bugs and design imperfections.

Default Android emulator
The great thing about using an emulator for development is that it gives you an opportunity to develop applications without having a real Android device. The default Android emulator comes together with the Android SDK and can be found in the “tools” folder.

So far so good, we have our cake, but can we eat it? The answer comes about 5 minutes after we hit the “Launch” button. Go grab a coffee. Have breakfast. Come back. Wait another 5 minutes. Maybe even more.

Finally – the emulator launches, only to show how slow it actually is.

Boot animation

All these performance problems stem from the fact that it emulates an ARM processor so it can run the actual code of your application. It accomplishes that by providing dynamic binary translation of the device machine code to the OS and processor architecture of your development machine.

Basically, it does a lot of mumbo-jumbo to pretend it’s an ARM processor – when actually it isn’t.

OK, IT’S SLOW. SO WHAT CAN WE DO ABOUT IT?

Well, first, we can help our CPU out by delegating the rendering process to the GPU by checking “Use Host GPU” checkbox in AVD’s edit window. The screen should now look better and be more responsive. That’s because the CPU is not dealing with the tedious work of doing rendering anymore. But, that’s still not fast enough.
Host GPU

We can download Intel Atom (x86) images and, while we’re at it, download Intel x86 Emulator Accelerator (HAXM, for Mac and Windows only). This will enable virtual machine acceleration capabilities of the Intel CPU (for more information check this link).
Now we’re getting somewhere, once this baby starts up, it should run fast and smooth.

x86 and HAXM

You could say that this level of speed should be sufficient. That may be true, but an issue with the Intel x86 images is that you don’t get Google Apps, they only come with ARM images. This is important if you’re testing an app that uses GMaps, or Google Play Services.

So, as we’ve seen, ARM images aren’t fast enough even with hardware acceleration. And emulators don’t have the Play Store. What now?

Genymotion by Genymobile
Genymotion is a new, fast Android emulator developed by the French company Genymobile. It’s based on the open-source project AndroVM, and the first beta version was released back in June.

It runs on all major platforms (Mac, Windows, Linux). For now it’s freely available, but there is also going to be a paid version.

According to AndroVM blog, the free version will be feature-rich, and the paid version will be intended for large companies needing a higher level of collaboration on Genymotion.

HOW TO USE IT?

Genymotion relies on Oracle VirtualBox to work (version 4.1 or above). So…

Download and install VirtualBox. For Windows users it’s not necessary to install VirtualBox separately, because it is available from the Genymotion site, bundled with the Genymotion emulator.

Go to Genymotion website and sign up. You’ll receive a validation mail, so just click on the validation link to proceed.

Download and install the Genymotion emulator (the current version is 1.1.0).

Start Genymotion. You might need to configure path to your Android SDK location in Genymotion settings (probably if you’ve installed SDK in a non default location). Since this is a first start, there are no devices. Click on “Add” and download new device. To see available devices, write your credentials in the pop-up dialog and click “Connect”.

Select the device and click “Start”.

It starts quickly and is insanely fast! It’s a little awkward to start the emulator separately, but Genymotion provides Eclipse and Android Studio integration through plugins, also available on Genymotion website. To use the plugin, you have to provide a path to Genymotion installation and Android SDK, as well.

Eclipse plugin

OK, IT’S FAST. IS THAT IT?

Well, for me, the sheer speed of Genymotion is what got me using it in the first place. Which is kind of funny, because in the first version you couldn’t even rotate the device.

But, alongside the speed bump, it also provides GPS, compass and battery control via some good-looking widgets.

Battery

Battery control widget

GPS

The GPS widget even provides GMaps for selecting mock locations, which is really nice for testing location based apps.

DEVICE ANGLE CONTROL AND PLAY STORE

Through the Genymotion shell it’s also possible to control the device’s angle (accelerometer), but it would be cool to control it using a widget, something like the Windows phone emulator does.

Accelerometer

Genymotion devices with Google Apps also come with the Play Store preinstalled. This comes in handy if you want to test an app from the Play Store quickly.

MULTIPLE SCREEN SIZES

Multiple screen sizes are one of Android developer’s worst nightmares. There is a huge number of different screen configurations of Android devices.

Android multiple screen sizes

Genymotion, as well as the default emulator, offers custom configuration of device’s screen. In the list of available devices, select the device for which you want to change screen configuration and click on the monitor icon on the right side. Then simply select one of the predefined screen resolutions or create your own.

Screen configuration

Final result

Be careful when choosing resolution, because you may end up with something rather strange…

WHERE IT COMES SHORT

The main setback of Genymotion is that it only provides devices with API version 16, 17 and a preview version of Android 4.3 (API 18). If we take a look at Google Dashboard, we’ll see that Gingerbread still holds about 33% of all devices (API 10).

So, for testing on that platform you still need either a default emulator or real device, which kind of defeats the purpose of Genymotion as a testing platform.

And there is no camera, which I don’t miss, but could be really useful.

In the future, we can expect even more features, like taking screenshots or video screen capturing (which would be great for making demonstration videos). An accelerometer widget would be cool, and even a camera would be nice, but we can only wait and see.

Final thoughts
Well, you can never really get rid of real devices, because you’ll always want to test an app on a real device before releasing it. But during development I recommend using a Genymotion emulator. Even though it doesn’t cover all major Android OS versions. It’s fast, stable, the GPS sensor manipulation is awesome and with the device rotation feature added to the 1.1.0 version – it’s truly the way to go.

Also, deploying apps is almost instant and that can save you a lot of time when you’re doing small changes to the app. But you have to watch out since the Genymotion emulator runs faster than real devices themselves, giving you a false impression of the performance of the app.

Always test on a real device!

Develop first Android Game with AndEngine


There are many frameworks you can use to make games on Android – the most popular being libGDX, AndEngine and Cocos2D-X. Each engine has its pros and cons.
Cocos2D-X (which we previously covered in a two-part series here and here) is great for making cross-platform games, but it does bring along a bit of extra complexity.
What if you just want to get a simple game working on Android the quickest and easiest way? This is where AndEngine comes in handy! Its API is very easy to use and it takes hardly any time to learn the ins and outs of the engine.
You’ll put AndEngine to work creating a version of the famous mathematical puzzle the Tower of Hanoi. Before you begin, make sure you’ve read my previous two tutorials on Getting Started with Android (here and here), or have some Android development experience under your belt.
Keep reading to get started with AndEngine!
All About the AndEngines
AndEngine logo
Which do you like better, this or the Cocos2D logo?
First, here’s a brief overview of AndEngine, including what I like and dislike about it.
AndEngine is currently available in two flavors: GLES1 and GLES2. As you might have gathered from the name, the GLES1 version supports OpenGL ES 1.x. Almost 99% of Android devices can run a game built using this version.
GLES2, as you might guess, supports OpenGL ES 2.0. This branch is actively being worked on, and nearly 93% of current Android devices can run a game that’s been made with this branch.
AndEngine Pros:
It has a complete 2-D scene graph, with a very easy-to-use API.
It works really well with the Android activity lifecycle.
It has a number of extensions that can be added as plugins.
It’s free :]
AndEngine Cons:
The biggest problem I’ve faced while using AndEngine is that the API is undocumented. This can increase the development time, as you sometimes need to go through the engine source code to figure things out. Don’t worry though – I’ve got you covered in this tutorial! :]
Getting Started
Now that you know a bit more about AndEngine, it’s time to download the source code and set up the environment.
Note: Since AndEngine is hosted on GitHub, you could always clone the git repository for AndEngine to get the source code for the project. However, this requires that you have git installed on your machine and that you are able to work on the command line.
Open up your browser and go to the AndEngine github page. You should see a link on the page to download the repository as a ZIP file. Use that to download a copy of the AndEngine project. Or, you should be able to use this link to download the file directly.
Extract the downloaded ZIP file to a convenient location on your hard drive.
Now that you’ve got the source code for the game engine, if you want, you can also download the code for additional AndEngine extensions. In this tutorial, you will not be using any of the extensions but you will need all of them in place if you wanted to try out the AndEngine sample project, which is also available on GitHub.
The sample project is a great way to learn the different ways to use AndEngine and you can always get the latest sample project and the extensions by downloading each of them from GitHub, setting up the projects, and building the sample. However, that is probably beyond the scope of this tutorial and so we’ll leave that to you to figure out, if you’re interested :] You can find it all at https://github.com/nicolasgramlich.
Setting Up the Environment
Before you start coding, there are a few things you should know about AndEngine:
OpenGL ES 2.0: The currently developed version of AndEngine is the GLES 2.0 version. This version requires OpenGL ES 2.0 support in order to function. So you need to make sure that your device (or emulator) supports OpenGL ES 2.0. If you are using the emulator to test, then you need graphics acceleration support and this is there only in the latest SDK Tools version. As of this tutorial, the latest SDK Tools version available is revision 19. Make sure that you have at least this version installed. To upgrade, please follow the instructions given here.
Android 4.0.3: You also need Android SDK Platform API 15, Revision 3 or higher in order to test OpenGL ES 2.0 based code on the emulator. So make sure that you’ve upgraded to at least Android 4.0.3, which is API 15. You emulator used for testing AndEngine code should be using Android 4.0.3.
Emulator: If you are using the emulator to test AndEngine code, you need a virtual device which has GPU emulation enabled and is running at least Android 4.0.3. So check your virtual device configuration and edit it if your device is not set up appropriately.
Andengine3
With that done, it’s time to start Eclipse, the IDE usually used for Android development. So go ahead an start Eclipse.
The version of AndEngine that you downloaded from GitHub already contains an Eclipse project file. You can simply import that by going to File->Import … That should open the following dialog:
Andengine1
Select “Existing Projects into Workspace” from the dialog and click “Next”. A new dialog should open where you must specify the location of the AndEngine project. It looks something like this:
Andengine2
Click the “Browse” button and browse to the folder where you extracted the AndEngine source ZIP file. The existing project should be detected and show up automatically in the dialog. Click “Finish”. And you should have the project imported into your Eclipse workspace – it’s that simple :]
If by some chance the extracted source is missing the Eclipse project information, you can create a new project by going to File->New->Project. A window like the one shown in the image below will open. Select Android Project and click Next.

Give the project a name: I suggest sticking with “AndEngine.” Select the “Create project from existing source” option. Next click the browse button, go to the location of the AndEngine source code and select Open. Once you’ve found the right location, press Finish. This will create a new project called AndEngine that you can view in the project navigator.

Your AndEngine project is now ready. This way, you can add your AndEngine project as a library to your tutorial project and the AndEngine library will be compiled in as part of your tutorial project.
The Tower of Hanoi
Time to start making your first Android game!! The game for this tutorial will be a simple version of the Tower of Hanoi puzzle. The finished project will look like this:

The objective of the Tower of Hanoi is to move all the rings over to the third rod, while only moving one ring at a time and without placing a larger ring on top of a smaller one.
Start by creating a new project. Open Eclipse and go to File->New and select Project, then select Android Project. Fill out all the details. I used the project name “TowerOfHanoi” and the package name “com.tutorial.towerofhanoi.” Feel free to use any name you wish, though it will be easier to stay in sync with the tutorial if you follow the same naming conventions.
Next add AndEngine as a library to your project. Right-click on the project and select Properties. Select Android in the left panel of the pop-up window. You should see a window like the one below:

From here you can add the engine as a library to the project. Click the Add button to add the AndEngine project. Once this is done, click Apply and then Okay.
Start Your AndEngine
Now you can begin coding. Open the src directory for the project via the Eclipse project navigator. If you drill down, (and if you used the suggested names) you should find a Java file called “TowerOfHanoiActivity.java”. (If you opted to name the first activity created something else, then find that file.) Open this file.
In Android development, an Activity is a single focused thing which interacts with the user. For instance, when you start an app, you can have a login activity which allows the user to login using their authentication credentials. And if the user doesn’t have a login, you might provide a second registration activity which will allow them to create a login.
The first file created by the project is also an Activity. And the first thing to do in our project is to change the class that this Activity extends. Instead of extending the Activity class, you want to make it extend a class called SimpleBaseGameActivity. And it’s fairly simple to do that, but in order to refer to the SimpleBaseGameActivity class, we need to add a few import statements for it. So we add that first to the top of the file under the existing import line:
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.engine.options.EngineOptions;
import org.andengine.entity.scene.Scene;
Note: Technically, you don’t have to always add the import statements first. You can always add your code in, look for the red underlines beneath classes, let the Eclipse code-fix tell you what import is needed and let it add the imports for you. But this might get a little bit confusing when you’re not sure which import to add when you get a several different choices. So in this tutorial, we’ll always add the imports first.
Now, just change the class definition line, similar to the following:
public class TowerOfHanoiActivity extends Activity {
To something like this:
public class TowerOfHanoiActivity extends SimpleBaseGameActivity {
The SimpleBaseActivity class provides additional callbacks and contains the code to make AndEngine work with the Activity life cycle. Each callback that it provides is used for a specific purpose. As soon as you extend this class, you’ll have to override three functions. Here is a brief description of each of those functions:
onCreateEngineOptions: This function is where you create an instance of the engine. Every activity that the game uses will have its own instance of the engine that will run within the activity lifecycle.
onCreateResources: This is the function where you’ll load all the resources that the activity requires into the the VRAM.
onCreateScene: This function is called after the above two callbacks are executed. This is where you create the scene for your game and use all the textures that you previously loaded into memory.
We will first add some empty placeholders for the above callbacks so that we have some skeleton code. Replace the existing contents of our TowerOfHanoiActivity class with the following (if you started with an automatically created Activity, you should have an onCreate method implementation):
@Override
public EngineOptions onCreateEngineOptions() {
// TODO Auto-generated method stub
return null;
}

@Override
protected void onCreateResources() {
// TODO Auto-generated method stub
}

@Override
protected Scene onCreateScene() {
// TODO Auto-generated method stub
return null;
}
Next, create a few static variables. These will be private to our class. So add the following code right below the class definition line:
private static int CAMERA_WIDTH = 800;
private static int CAMERA_HEIGHT = 480;
These two static variables define the width and height of the camera that the engine will use. This means that the final dimensions of the game scene will be equal to the camera size and width.
Next, you’re going to write code to initialize an instance of the engine. But that code is going to require several import statements in order to function properly. So first add the following imports to the top of the file below the existing import statements:
import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
Now, add the following code for the onCreateEngineOptions function, replacing the placeholder conent which is in there at the moment:
final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED,
new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
In the above code, you create a new instance of the Camera class. Then we use that camera object to create the EngineOptions object that defines the options with which the engine will be initialized. The parameters that are passed while creating an instance of EngineOptions are:
FullScreen: A boolean variable signifying whether or not the engine instance will use a fullscreen.
ScreenOrientation: Specifies the orientation used while the game is running.
ResolutionPolicy: Defines how the engine will scale the game assets on phones with different screen sizes.
Camera: Defines the width and height of the final game scene.
Take a step back for a moment. As you know, Android runs on a lot of devices with different screen sizes. Keeping this in mind, it becomes very difficult to resize the game scene for each device. AndEngine comes with a unique solution to this problem: it will automatically scale the game assets to fit the screen size of the device.
If you set your CAMERA_WIDTH/CAMERA_HEIGHT to 480×320 and someone runs it on a phone with a 800×480 screen size, your game will be scaled up to 720×480 (1.5x) with a 80px margin (top, bottom, left, or right). Notice that AndEngine keeps the same aspect ratio and scales the game scene to the closest possible value to the actual screen size.
Loading Game Assets to VRAM
Now that you’ve initialized an instance of the engine, you can load all the assets required by the Tower of Hanoi game into memory. First download the game assets here.
Next create a new folder within the assets folder already present in your project. To do this, right-click on the assets folder and select New->Folder, name the folder “gfx” and copy all the downloaded assets to that folder.
To load these assets, we’re going to add the onCreateResources method. But as you might guess, our new code references several other classes for which we need to add imports. So add the following at the top of the file below the rest of the import statements:
import org.andengine.opengl.texture.ITexture;
import org.andengine.opengl.texture.bitmap.BitmapTexture;
import org.andengine.util.adt.io.in.IInputStreamOpener;
import org.andengine.util.debug.Debug;

import java.io.IOException;
import java.io.InputStream;
Now, replace the placeholder content in onCreateResources with the following:
try {
// 1 – Set up bitmap textures
ITexture backgroundTexture = new BitmapTexture(this.getTextureManager(), new IInputStreamOpener() {
@Override
public InputStream open() throws IOException {
return getAssets().open(“gfx/background.png”);
}
});
ITexture towerTexture = new BitmapTexture(this.getTextureManager(), new IInputStreamOpener() {
@Override
public InputStream open() throws IOException {
return getAssets().open(“gfx/tower.png”);
}
});
ITexture ring1 = new BitmapTexture(this.getTextureManager(), new IInputStreamOpener() {
@Override
public InputStream open() throws IOException {
return getAssets().open(“gfx/ring1.png”);
}
});
ITexture ring2 = new BitmapTexture(this.getTextureManager(), new IInputStreamOpener() {
@Override
public InputStream open() throws IOException {
return getAssets().open(“gfx/ring2.png”);
}
});
ITexture ring3 = new BitmapTexture(this.getTextureManager(), new IInputStreamOpener() {
@Override
public InputStream open() throws IOException {
return getAssets().open(“gfx/ring3.png”);
}
});
// 2 – Load bitmap textures into VRAM
backgroundTexture.load();
towerTexture.load();
ring1.load();
ring2.load();
ring3.load();
} catch (IOException e) {
Debug.e(e);
}
In the above code, you first create an ITexture object. ITexture is an interface. An object of this type is initialized to a BitmapTexture object, which, you guessed it, is used to to load a bitmap into VRAM. The above code creates ITexture objects for all the assets you downloaded, and loads them into VRAM by calling the load method on each object.
Now that you have all your assets loaded, you need to extract TextureRegions from your textures. Think of a texture as a giant canvas that has to have width and height values which are a power of 2 (a requirement of OpenGL ES). A TextureRegion, on the other hand, is a part or a region of a texture that does not have to have dimensions which are a power of 2.
Note: Instead of creating textures for each of your assets, you could have loaded all the assets into one texture and extracted the individual assets as TextureRegions. Doing this is out of scope for this tutorial, but I may cover it in detail in a future tutorial.
As you might guess, we have to add a few new import statements first:
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.TextureRegionFactory;
Now, to hold the TextureRegions, add private variables to our class (again, at the top of the file, below the previous private variables):
private ITextureRegion mBackgroundTextureRegion, mTowerTextureRegion, mRing1, mRing2, mRing3;
Finally, add these lines of code to onCreateResources, right after the end of section #2 where you load the bitmap textures into VRAM:
// 3 – Set up texture regions
this.mBackgroundTextureRegion = TextureRegionFactory.extractFromTexture(backgroundTexture);
this.mTowerTextureRegion = TextureRegionFactory.extractFromTexture(towerTexture);
this.mRing1 = TextureRegionFactory.extractFromTexture(ring1);
this.mRing2 = TextureRegionFactory.extractFromTexture(ring2);
this.mRing3 = TextureRegionFactory.extractFromTexture(ring3);
The above code initializes your TextureRegions using the textures that you already loaded into VRAM.
Creating the Game Scene
It’s finally time to create the game scene! Of course, we need another new import:
import org.andengine.entity.sprite.Sprite;
Next, replace the placeholder content in onCreateScene with the following:
// 1 – Create new scene
final Scene scene = new Scene();
Sprite backgroundSprite = new Sprite(0, 0, this.mBackgroundTextureRegion, getVertexBufferObjectManager());
scene.attachChild(backgroundSprite);
return scene;
The above code first creates a Scene object. Next you create a sprite called backgroundSprite and attach the sprite to the scene. Notice that this method requires you to return the scene object. Think of a scene as a container with a number of layers, and each layer can have many sprites (TextureRegions) placed within it.
When creating a Sprite object, you pass four parameters. Here’s a brief description of each parameter:
xCoordinate: Defines the X-position of the sprite. The AndEngine coordinate system considers the top-left point as the origin.
yCoordinate: Defines the Y-position of the sprite.
TextureRegion: Defines what part of the texture the sprite will use to draw itself.
VertexBufferObjectManager: Think of a vertex buffer as an array holding the coordinates of a texture. These coordinates are passed to the OpenGL ES pipeline and ultimately define what will be drawn. A VertexBufferObjectManager holds all the vertices of all the textures that need to be drawn on the scene.
Compile and run the application. You should see something like this:

Nice, we’re starting to see something! However, this platform does look a little bit desert-ed (groan) ;]
The Three Towers
It’s time to add the sprites for the towers and rings – the final step before getting things moving with the game logic. Start by adding three private variables to the class. Declare the variables as follows:
private Sprite mTower1, mTower2, mTower3;
Next add the following lines of code to onCreateScene, right before the final return statement:
// 2 – Add the towers
mTower1 = new Sprite(192, 63, this.mTowerTextureRegion, getVertexBufferObjectManager());
mTower2 = new Sprite(400, 63, this.mTowerTextureRegion, getVertexBufferObjectManager());
mTower3 = new Sprite(604, 63, this.mTowerTextureRegion, getVertexBufferObjectManager());
scene.attachChild(mTower1);
scene.attachChild(mTower2);
scene.attachChild(mTower3);
You’ve defined three sprites, each using the TextureRegion of the tower that you loaded in onCreateResources.Then you added these sprites to your scene. That’s all there is to it!
Compile and run. You should now see the three towers placed in their proper positions.

And One Ring to Bind Them
Let’s talk a little about the game logic before you create your rings. Think of the towers as three stacks (I mean the data structure) – you can only remove the top-most element, and when you add an element it will always be on top. You’ll use these stacks when you write the game logic code.
To create the rings, we need to first make a custom class that will extend Sprite. You do this because every ring needs to know which stack it belongs to.
Right-click on the folder containing TowerOfHanoiActivity.java and select New->Class. You should see a dialog which you should fill in similar to the following:
Andengine4
Note that you probably would have “Source folder” and “Package” filled in automatically. All you’d need to do is type in the “Name” and click “Browse…” next to “Superclass” to find the Sprite class from AndEngine. That should create a Java file called “Ring.java.” Place the following code within the class implementation (after the public class line and before the closing curly brace):
private int mWeight;
private Stack mStack; //this represents the stack that this ring belongs to
private Sprite mTower;

public Ring(int weight, float pX, float pY, ITextureRegion pTextureRegion, VertexBufferObjectManager pVertexBufferObjectManager) {
super(pX, pY, pTextureRegion, pVertexBufferObjectManager);
this.mWeight = weight;
}

public int getmWeight() {
return mWeight;
}

public Stack getmStack() {
return mStack;
}

public void setmStack(Stack mStack) {
this.mStack = mStack;
}

public Sprite getmTower() {
return mTower;
}

public void setmTower(Sprite mTower) {
this.mTower = mTower;
}
Most of the code here is pretty straightforward. The object has three private variables. One is used to keep track of the weight of the tower; this is an integer value, i.e., the higher the value, the bigger the ring. The other two variables are used to store the stack that the ring belongs to and the tower on which it is currently placed.
You’ll also need to add the following import statements to the top of the file:
import java.util.Stack;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
Now that we have the Ring class, to create and add the rings, add the following lines of code to onCreateScene, right before the return statement:
// 3 – Create the rings
Ring ring1 = new Ring(1, 139, 174, this.mRing1, getVertexBufferObjectManager());
Ring ring2 = new Ring(2, 118, 212, this.mRing2, getVertexBufferObjectManager());
Ring ring3 = new Ring(3, 97, 255, this.mRing3, getVertexBufferObjectManager());
scene.attachChild(ring1);
scene.attachChild(ring2);
scene.attachChild(ring3);
Compile and run to test.
Andengine5
You’ll notice that the rings are now on the first tower but you can’t move the rings. That’s because we haven’t worked out the game logic for placing and moving the rings. So that’s what you’ll do next :]
Game Logic
Ready to bring your Tower of Hanoi puzzle to life? As mentioned before, as the foundation of the game logic, you’re going to create three stacks, each representing a tower. Start by adding the following import for the Stack class to TowerOfHanoiActivity.java:
import java.util.Stack;
Next, declare the stack variables below the other private variables:
private Stack mStack1, mStack2, mStack3;
You’ll initialize these variables in onCreateResources. Add the following lines of code after the end of section #3:
// 4 – Create the stacks
this.mStack1 = new Stack();
this.mStack2 = new Stack();
this.mStack3 = new Stack();
When the game starts, all three rings should be in the first stack. Put the following code in onCreateScene right before the return statement:
// 4 – Add all rings to stack one
this.mStack1.add(ring3);
this.mStack1.add(ring2);
this.mStack1.add(ring1);
// 5 – Initialize starting position for each ring
ring1.setmStack(mStack1);
ring2.setmStack(mStack1);
ring3.setmStack(mStack1);
ring1.setmTower(mTower1);
ring2.setmTower(mTower1);
ring3.setmTower(mTower1);
// 6 – Add touch handlers
scene.registerTouchArea(ring1);
scene.registerTouchArea(ring2);
scene.registerTouchArea(ring3);
scene.setTouchAreaBindingOnActionDownEnabled(true);
In the above code, you do the following:
Added the rings to the first stack.
Set the stack variable of each ring as the first stack and the tower variable as the first tower.
To handle touch and movement of the rings, you registered each ring as a touchable area.
Enabled touch binding.
Now, you need to override the onAreaTouch method of the Sprite class. This is where you’ll add logic to move the rings. But that code in turn will require a method which checks whether a ring collided with a tower. You’ll write that code later, but you need to add an empty method place holder for collision detection as follows (you can add this to the end of the class):
private void checkForCollisionsWithTowers(Ring ring) {
}
You also need to add the following import in order for the ring movement code to be able to identify the relevant classes:
import org.andengine.input.touch.TouchEvent;
Now, replace the first three lines of section #3 in onCreateScene (where you defined the rings) with the following:
Ring ring1 = new Ring(1, 139, 174, this.mRing1, getVertexBufferObjectManager()) {
@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) {
if (((Ring) this.getmStack().peek()).getmWeight() != this.getmWeight())
return false;
this.setPosition(pSceneTouchEvent.getX() – this.getWidth() / 2,
pSceneTouchEvent.getY() – this.getHeight() / 2);
if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP) {
checkForCollisionsWithTowers(this);
}
return true;
}
};
Ring ring2 = new Ring(2, 118, 212, this.mRing2, getVertexBufferObjectManager()) {
@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) {
if (((Ring) this.getmStack().peek()).getmWeight() != this.getmWeight())
return false;
this.setPosition(pSceneTouchEvent.getX() – this.getWidth() / 2,
pSceneTouchEvent.getY() – this.getHeight() / 2);
if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP) {
checkForCollisionsWithTowers(this);
}
return true;
}
};
Ring ring3 = new Ring(3, 97, 255, this.mRing3, getVertexBufferObjectManager()) {
@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) {
if (((Ring) this.getmStack().peek()).getmWeight() != this.getmWeight())
return false;
this.setPosition(pSceneTouchEvent.getX() – this.getWidth() / 2,
pSceneTouchEvent.getY() – this.getHeight() / 2);
if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP) {
checkForCollisionsWithTowers(this);
}
return true;
}
};
Notice that onAreaTouched returns a boolean value. When it returns true, the touch is consumed, otherwise it is passed down to other layers until someone consumes it. So the first thing you do in this method is check if the weight of the current ring is not equal to the weight of the first ring in the stack. If it is, that means this ring is the first element of the stack and so you can proceed to move it, otherwise you let the touch go since you can’t move this ring.
You also check in onAreaTouched if the type of touch is an ACTION_UP event, triggered when the finger is lifted. If it is, you call checkForCollisionsWithTowers whose primary purpose is to check if the ring has collided with (or rather, is touching) a tower. As you may recall, you added a placeholder for checkForCollisionsWithTowers already. Let’s fill the function in now.
Replace the placeholder method for checkForCollisionsWithTowers with the following:
private void checkForCollisionsWithTowers(Ring ring) {
Stack stack = null;
Sprite tower = null;
if (ring.collidesWith(mTower1) && (mStack1.size() == 0 ||
ring.getmWeight() < ((Ring) mStack1.peek()).getmWeight())) {
stack = mStack1;
tower = mTower1;
} else if (ring.collidesWith(mTower2) && (mStack2.size() == 0 ||
ring.getmWeight() < ((Ring) mStack2.peek()).getmWeight())) {
stack = mStack2;
tower = mTower2;
} else if (ring.collidesWith(mTower3) && (mStack3.size() == 0 ||
ring.getmWeight() 0) {
ring.setPosition(tower.getX() + tower.getWidth()/2 –
ring.getWidth()/2, ((Ring) stack.peek()).getY() –
ring.getHeight());
}
stack.add(ring);
ring.setmStack(stack);
ring.setmTower(tower);
}
The above code checks whether the given ring is touching a tower, if it is, whether it can be moved to that tower, and if yes, places the ring appropriately.
Build and run, and you should have a completely functional Tower of Hanoi game! There are only three rings, but that means you should be able to beat the game in no time. 😛
Where to Go From Here?
Here is the complete source code of the project.
There are a number of things left to be done, but these are easy enough to accomplish. So I’m going to leave them as an exercise for you :] Possible additions include:
Detecting when all the rings have been moved to the third tower and showing a Game Over pop-up.
Counting and displaying the total number of moves.
Calculating and displaying the minimum number of moves required. (Hint: with three rings, the puzzle can be solved in seven moves.)
Allowing the user to increase the difficulty by adding more rings. Legend has it that there is a temple where the priests are working on a version of this puzzle with 64 rings! I don’t suggest you create a version of this game with that many rings, unless you want to spend 580 billion years solving it!
Try your hand at these improvements and let me know how you fare in the forums!

Capture image from camera in Android Application


1. Add in Manifest.xml

uses-feature android:name=”android.hardware.camera”
android:required=”true”

2.Take Picture From Camera

static final int REQUEST_IMAGE_CAPTURE = 1;

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }
}

3. Save or display it ob ImageView.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get(“data”);
        mImageView.setImageBitmap(imageBitmap);
    }
}

Thanks.

Save File or Image on your Android Emulator


Step 1. open window on eclipse.
Step 2. Open Perspective and Select DDMS.
Step 3. Select File Explorer.
Step 4. go to mnt/sdcard and select sdcard.
Step 5.two option available at right side. Put file on Device and Get Device file/ folder.
Step 6 . select put file on device. A pop will be open after that.
Step 7. Select image which you want to put in emulator.
Step 8. Restart Emulator .

BEST OF LUCKScreen shot 2013-08-08 at 6.12.41 PM

List View in Android


Step 1. create a xml file name as “friend_detail.xml” in layout .

Step 2. Add a list View .

Step 3 . Create a class file in src name as FriendDetail.java .

Step4 . Write following Code in OnCreate method.

final ListView listview = (ListView) findViewById(R.id.listView1);

String[] values = new String[] { “Android”, “iPhone”, “WindowsMobile”,

“Blackberry”, “WebOS”, “Ubuntu”, “Windows7”, “Max OS X”,

“Linux”, “OS/2”, “Ubuntu”, “Windows7”, “Max OS X”, “Linux”,

“OS/2”, “Ubuntu”, “Windows7”, “Max OS X”, “Linux”, “OS/2”,

“Android”, “iPhone”, “WindowsMobile” };

final ArrayList<String> list = new ArrayList<String>();

for (int i = 0; i < values.length; ++i) {

list.add(values[i]);

}

final StableArrayAdapter adapter = new StableArrayAdapter(this,

android.R.layout.simple_list_item_1, list);

listview.setAdapter(adapter);

Step 5. Create a function after onCreate function .

privateclass StableArrayAdapter extends ArrayAdapter<String> {

HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();

public StableArrayAdapter(Context context, int textViewResourceId,

List<String> objects) {

super(context, textViewResourceId, objects);

for (int i = 0; i < objects.size(); ++i) {

mIdMap.put(objects.get(i), i);

}

}

@Override

publiclong getItemId(int position) {

String item = getItem(position);

returnmIdMap.get(item);

}

@Override

publicboolean hasStableIds() {

returntrue;

}

}

Step 6 . Import required Class if any error occure.

Best of Luck.

Image

Move in other Window on Clicking Button In Android


Button login=(Button) findViewById(R.id.checkinView);

/*………………………Go to Check in View………………….*/

login.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {

Intent move = new Intent(mainView.this, CheckInView.class);

move.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

startActivity(move);

}

});

Grid View with Image and Label in Android


Step1.    Create a XML in Layout of type Linear Layout.

Step2. Paste  Following  Code for Image view and Label .

<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:padding=”5dp”

android:orientation=”vertical” >

<ImageView

android:id=”@+id/grid_item_image”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:layout_marginRight=”10px”

android:src=”@drawable/demo” >

</ImageView>

<TextView

android:id=”@+id/grid_item_label”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:text=”@+id/label”

android:layout_marginLeft=”2dp”

android:layout_marginTop=”5dp”

android:textSize=”10dp” >

</TextView>

</LinearLayout>

you can also create own image view and label but in that case name of these should be same any where .(ex. java code).

Step3. Create a class file in src with name  “ImageAdapter” it will be shown in src as ImageAdapter.java.

Step 4. paste Following code in this file (ImageAdopter.java).

package com.example.looknfeel;

import android.content.Context;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.BaseAdapter;

import android.widget.ImageView;

import android.widget.TextView;

public class ImageAdapter extends BaseAdapter {

private Context context;

private final String[] mobileValues;

public ImageAdapter(Context context, String[] mobileValues) {

this.context = context;

this.mobileValues = mobileValues;

}

public View getView(int position, View convertView, ViewGroup parent) {

LayoutInflater inflater = (LayoutInflater) context

.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View gridView;

if (convertView == null) {

gridView = new View(context);

// get layout from mobile.xml

gridView = inflater.inflate(R.layout.mobile, null);

// set value into textview

TextView textView = (TextView) gridView

.findViewById(R.id.grid_item_label);

textView.setText(mobileValues[position]);

// set image based on selected text

ImageView imageView = (ImageView) gridView

.findViewById(R.id.grid_item_image);

String mobile = mobileValues[position];

imageView.setImageResource(R.drawable.demo);

} else {

gridView = (View) convertView;

}

return gridView;

}

@Override

public int getCount() {

return mobileValues.length;

}

@Override

public Object getItem(int position) {

return null;

}

@Override

public long getItemId(int position) {

return 0;

}

}

*** Replace Package name with your package.

Step 5. create a Xml file of Grid Layout Type.

Step 6. Create a class with name FriendView . and paste following Code  .

package com.example.looknfeel;

import android.app.Activity;

import android.content.Context;

import android.content.Intent;

import android.os.Bundle;

import android.view.LayoutInflater;

import android.view.MotionEvent;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.View.OnFocusChangeListener;

import android.view.View.OnTouchListener;

import android.view.ViewGroup;

import android.widget.AdapterView;

import android.widget.AdapterView.OnItemClickListener;

import android.widget.BaseAdapter;

import android.widget.Button;

import android.widget.GridView;

import android.widget.ImageView;

import android.widget.TextView;

import android.widget.Toast;

public class FriendView extends Activity {

GridView grid_main;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.friendview);// replace friend view by name of grid xml.

GridView gridView = (GridView) findViewById(R.id.grid_view);

final String[] MOBILE_OS = new String[] {

“Android”, “iOS”,”Windows”, “Blackberry” };

// gridView.setAdapter(new ImageAdapter(this,null));

gridView.setAdapter(new ImageAdapter(this, MOBILE_OS));

gridView.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView<?> parent, View v,

int position, long id) {

Intent move = new Intent(FriendView.this, FriendDetail.class);

move.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

startActivity(move);

}

});

}

}

Step 7. change the name of images with with are available in your drawable .

Hope your Grid View with image and label will be created .

Continue reading