Android Title 1
Quas molestias excepturi
THIS IS FEATURED POST 2 TITLE
Impedit quo minus id
THIS IS FEATURED POST 3 TITLE
Voluptates repudiandae kon
THIS IS FEATURED POST 4 TITLE
Mauris euismod rhoncus tortor

ViewFlipper Touch Animation in Android


Chaunri | 8:54 PM | ,

To begin the android develompent you need tree important thins: The Android Sdk (you can download it here), A Project Editor (i suggest eclipse) and the Android eclipse plugin.
When you have the environment ready you can start with this tutorial.
When you open for the first time the Android SDK you need to create a virtual device, I suggest to create a common device using as Target the Android 1.6 Api Level 4 and then you need to add the hardware features that you need in your environment, for example: SD Card Support, Accellerometer, Camera Support etc. if you need help to start up an android virtual device follow this link.

Start the Ecplise Project

Follow these simple step to create an Android Project in eclipse:
  1. Select File > New > Project.
  2. Select Android > Android Project, and click Next.
  3. Select the contents for the project:
    • Enter a Project Name. This will be the name of the folder where your project is created.
    • Under Contents, select Create new project in workspace. Select your project workspace location.
    • Under Target, select an Android target to be used as the project's Build Target. The Build Target specifies which Android platform you'd like your application built against. Unless you know that you'll be using new APIs introduced in the latest SDK, you should select a target with the lowest platform version possible, such as Android 1.6.
      Note: You can change your the Build Target for your project at any time: Right-click the project in the Package Explorer, select Properties, select Android and then check the desired Project Target.
    • Under Properties, fill in all necessary fields.
      • Enter an Application name. This is the human-readable title for your application — the name that will appear on the Android device.
      • Enter a Package name. This is the package namespace (following the same rules as for packages in the Java programming language) where all your source code will reside.
      • Select Create Activity (optional, of course, but common) and enter a name for your main Activity class.
      • Enter a Min SDK Version. This is an integer that indicates the minimum API Level required to properly run your application. Entering this here automatically sets the minSdkVersion attribute in the <uses-sdk> of your Android Manifest file. If you're unsure of the appropriate API Level to use, copy the API Level listed for the Build Target you selected in the Target tab.
  4. Click Finish.
when you are ready the ADT creates for you the following folders and files:
  • src/: Includes any Activity Java file. All other Java files for your application go here.
  • <Android Version>: Includes the android.jar file that your application will build against. This is determined by the build target that you have chosen in the New Project Wizard
  • gen/: This contains the Java files generated by ADT, such as your R.java file and interfaces created from AIDL files (this is an automatic class)..
  • assets/: This is empty. You can use it to store raw asset files.
  • res/: A folder for your application resources, such as drawable files, layout files, string values, etc.
  • AndroidManifest.xml: The Android Manifest for your project.
  • default.properties: This file contains project settings, such as the build target. This files is integral to the project, as such, it should be maintained in a Source Revision Control system. It should never be edited manually — to edit project properties, right-click the project folder and select "Properties".
In this tutorial we use only two folder: src/ and res/, now start with the sample solution to the common problem

How to Slide Two (or more) Layout like the News & Weather by Touch Event

Now that you are ready with Android, one of the first things we try to in Android development is to emulate the graphics effect that have the best applications. So, one of the animations/events mostly used and highly effective is the sliding window from one activity to another by using the fing. To do this we need a little bit of java code and some tips in our XML layout.

Begin from the XML Layout File

Open from res/layout/ the main.xml (or some other layout file) and put this lines:
<ViewFlipper
    android:layout_margin="6dip"
    android:id="@+id/layoutswitcher"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TextView
            android:layout_height="wrap_content"
            android:id="@+id/firstpanel"
            android:paddingTop="10dip"
            android:text="my first panel"
            android:layout_width="fill_parent"
            android:layout_weight="1"
            android:textStyle="bold" >
        </TextView>
    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TextView
            android:layout_height="wrap_content"
            android:id="@+id/secondpanel"
            android:paddingTop="10dip"
            android:text="my second panel"
            android:layout_width="fill_parent"
            android:layout_weight="1"
            android:textStyle="bold" >
        </TextView>
    </LinearLayout>
</ViewFlipper>
As you can see, I add one ViewFlipper, two LinearLayout and for each inner layout a simpletextview, this first step is ncessary to create a proper switching layout, after you can customize as you want the style of the two inner layout and if you want add a toolbar to switch around the inner layout.

Second step: Java Code (Switch Layout by Touch) 

Now open your main class from src/<yout package name> and in the begin of the class declare these two variables:
    private ViewFlipper vf;  
    private float oldTouchValue;
The first Variable (VF) is needed to constrol the ViewFlipper and the second one is needed to the touch event, now attach the viewflipper to the class :
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ....
  vf = (ViewFlipper) findViewById(R.id.switchlayout);
     }
Now we have a declared viewflipper and can proceed to the last step of this simple tutorial.

The Touch Event

One of the most important feature of this new mobile phone is the Touch Screen system and like iPhone apps or other touching device the user prefer to switch among the activies by their fingers. In Android develpment to attach a touch event you can do two things "implement the touchlistener" or declare am onTouchEvent by overriding the main method.
In this sample we use the second case, take a look of the following code and then to the explaination:
    @Override
    public boolean onTouchEvent(MotionEvent touchevent) {
        switch (touchevent.getAction())
        {
            case MotionEvent.ACTION_DOWN:
            {
                oldTouchValue = touchevent.getX();
                break;
            }
            case MotionEvent.ACTION_UP:
            {
                if(this.searchOk==false) return false;
                float currentX = touchevent.getX();
                if (oldTouchValue < currentX)
                {
                    vf.setInAnimation(AnimationHelper.inFromLeftAnimation());
                    vf.setOutAnimation(AnimationHelper.outToRightAnimation());
                    vf.showNext();
                }
                if (oldTouchValue > currentX)
                {
                    vf.setInAnimation(AnimationHelper.inFromRightAnimation());
                    vf.setOutAnimation(AnimationHelper.outToLeftAnimation());
                    vf.showPrevious();
                }
            break;
            }
        }
        return false;
    }
As you can see, when the user touch for the first time the device a fill the float variable (oldTouchValue) with the X position of his finger, then when the user release his finger I check the new position of the event to decide if the user want to go next or previous ( oldTouchValue < currentX, oldTouchValue > currentX). To change the layout the code is the same but I use different animation if the user want to go next or previous, for more explaining about the animation and the AnimationHelper I put this sample code:
 //for the previous movement
 public static Animation inFromRightAnimation() {

     Animation inFromRight = new TranslateAnimation(
     Animation.RELATIVE_TO_PARENT,  +1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
     Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
     );
     inFromRight.setDuration(350);
     inFromRight.setInterpolator(new AccelerateInterpolator());
     return inFromRight;
     }
    public static Animation outToLeftAnimation() {
     Animation outtoLeft = new TranslateAnimation(
      Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  -1.0f,
      Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
     );
     outtoLeft.setDuration(350);
     outtoLeft.setInterpolator(new AccelerateInterpolator());
     return outtoLeft;
     }    
    // for the next movement
    public static Animation inFromLeftAnimation() {
     Animation inFromLeft = new TranslateAnimation(
     Animation.RELATIVE_TO_PARENT,  -1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
     Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
     );
     inFromLeft.setDuration(350);
     inFromLeft.setInterpolator(new AccelerateInterpolator());
     return inFromLeft;
     }
    public static Animation outToRightAnimation() {
     Animation outtoRight = new TranslateAnimation(
      Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  +1.0f,
      Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
     );
     outtoRight.setDuration(350);
     outtoRight.setInterpolator(new AccelerateInterpolator());
     return outtoRight;
     }
You can decide to put these method in a static class (like me) or to declare they in your class.

Sources:- http://www.codeproject.com/Articles/69008/Android-ViewFlipper-Touch-Animation-like-News-Weat

Building a Simple User Interface


Chaunri | 8:50 PM | ,

The graphical user interface for an Android app is built using a hierarchy of View and ViewGroup objects. View objects are usually UI widgets such as buttons or text fields and ViewGroup objects are invisible view containers that define how the child views are laid out, such as in a grid or a vertical list.
Android provides an XML vocabulary that corresponds to the subclasses of View and ViewGroup so you can define your UI in XML using a hierarchy of UI elements.

Figure 1. Illustration of how ViewGroup objects form branches in the layout and contain other View objects.
In this lesson, you'll create a layout in XML that includes a text field and a button. In the following lesson, you'll respond when the button is pressed by sending the content of the text field to another activity.

Create a Linear Layout


Open the activity_main.xml file from the res/layout/ directory.
Note: In Eclipse, when you open a layout file, you’re first shown the Graphical Layout editor. This is an editor that helps you build layouts using WYSIWYG tools. For this lesson, you’re going to work directly with the XML, so click the activity_main.xml tab at the bottom of the screen to open the XML editor.
The BlankActivity template you used to start this project creates the activity_main.xml file with a RelativeLayout root view and a TextView child view.
First, delete the <TextView> element and change the <RelativeLayout> element to <LinearLayout>. Then add the android:orientation attribute and set it to "horizontal". The result looks like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
</LinearLayout>
LinearLayout is a view group (a subclass of ViewGroup) that lays out child views in either a vertical or horizontal orientation, as specified by the android:orientation attribute. Each child of a LinearLayout appears on the screen in the order in which it appears in the XML.
The other two attributes, android:layout_width and android:layout_height, are required for all views in order to specify their size.
Because the LinearLayout is the root view in the layout, it should fill the entire screen area that's available to the app by setting the width and height to "match_parent". This value declares that the view should expand its width or height to match the width or height of the parent view.
For more information about layout properties, see the Layout guide.

Add a Text Field


To create a user-editable text field, add an <EditText> element inside the <LinearLayout>.
Like every View object, you must define certain XML attributes to specify the EditText object's properties. Here’s how you should declare it inside the <LinearLayout> element:
    <EditText android:id="@+id/edit_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />
About these attributes:
android:id
This provides a unique identifier for the view, which you can use to reference the object from your app code, such as to read and manipulate the object (you'll see this in the next lesson). The at sign (@) is required when you're referring to any resource object from XML. It is followed by the resource type (id in this case), a slash, then the resource name (edit_message).
The plus sign (+) before the resource type is needed only when you're defining a resource ID for the first time. When you compile the app, the SDK tools use the ID name to create a new resource ID in your project's gen/R.java file that refers to the EditText element. Once the resource ID is declared once this way, other references to the ID do not need the plus sign. Using the plus sign is necessary only when specifying a new resource ID and not needed for concrete resources such as strings or layouts. See the sidebox for more information about resource objects.
android:layout_width and android:layout_height
Instead of using specific sizes for the width and height, the "wrap_content" value specifies that the view should be only as big as needed to fit the contents of the view. If you were to instead use "match_parent", then the EditText element would fill the screen, because it would match the size of the parent LinearLayout. For more information, see the Layouts guide.
android:hint
This is a default string to display when the text field is empty. Instead of using a hard-coded string as the value, the "@string/edit_message" value refers to a string resource defined in a separate file. Because this refers to a concrete resource (not just an identifier), it does not need the plus sign. However, because you haven't defined the string resource yet, you’ll see a compiler error at first. You'll fix this in the next section by defining the string.
Note: This string resource has the same name as the element ID: edit_message. However, references to resources are always scoped by the resource type (such as id or string), so using the same name does not cause collisions.

Add String Resources


When you need to add text in the user interface, you should always specify each string as a resource. String resources allow you to manage all UI text in a single location, which makes it easier to find and update text. Externalizing the strings also allows you to localize your app to different languages by providing alternative definitions for each string resource.
By default, your Android project includes a string resource file at res/values/strings.xml. Open this file and delete the <string> element named "hello_world". Then add a new one named "edit_message" and set the value to "Enter a message."
While you’re in this file, also add a "Send" string for the button you’ll soon add, called "button_send".
The result for strings.xml looks like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">My First App</string>
    <string name="edit_message">Enter a message</string>
    <string name="button_send">Send</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
</resources>
For more information about using string resources to localize your app for other languages, see the Supporting Different Devices class.

Add a Button


Now add a <Button> to the layout, immediately following the <EditText> element:
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_send" />
The height and width are set to "wrap_content" so the button is only as big as necessary to fit the button's text. This button doesn't need the android:id attribute, because it won't be referenced from the activity code.

Make the Input Box Fill in the Screen Width


The layout is currently designed so that both the EditText and Button widgets are only as big as necessary to fit their content, as shown in figure 2.
Figure 2. The EditText and Button widgets have their widths set to "wrap_content".
This works fine for the button, but not as well for the text field, because the user might type something longer. So, it would be nice to fill the unused screen width with the text field. You can do this inside a LinearLayout with the weight property, which you can specify using the android:layout_weight attribute.
The weight value is a number that specifies the amount of remaining space each view should consume, relative to the amount consumed by sibling views. This works kind of like the amount of ingredients in a drink recipe: "2 parts vodka, 1 part coffee liqueur" means two-thirds of the drink is vodka. For example, if you give one view a weight of 2 and another one a weight of 1, the sum is 3, so the first view fills 2/3 of the remaining space and the second view fills the rest. If you add a third view and give it a weight of 1, then the first view (with weight of 2) now gets 1/2 the remaining space, while the remaining two each get 1/4.
The default weight for all views is 0, so if you specify any weight value greater than 0 to only one view, then that view fills whatever space remains after all views are given the space they require. So, to fill the remaining space in your layout with the EditText element, give it a weight of 1 and leave the button with no weight.
    <EditText
        android:layout_weight="1"
        ... />
In order to improve the layout efficiency when you specify the weight, you should change the width of the EditText to be zero (0dp). Setting the width to zero improves layout performance because using "wrap_content" as the width requires the system to calculate a width that is ultimately irrelevant because the weight value requires another width calculation to fill the remaining space.
    <EditText
        android:layout_weight="1"
        android:layout_width="0dp"
        ... />
Figure 3 shows the result when you assign all weight to the EditText element.
Figure 3. The EditText widget is given all the layout weight, so fills the remaining space in the LinearLayout.
Here’s how your complete layout file should now look:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <EditText android:id="@+id/edit_message"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_send" />
</LinearLayout>
This layout is applied by the default Activity class that the SDK tools generated when you created the project, so you can now run the app to see the results:
  • In Eclipse, click Run from the toolbar.
  • Or from a command line, change directories to the root of your Android project and execute:
    ant debug
    adb install bin/MyFirstApp-debug.apk
Continue to the next lesson to learn how you can respond to button presses, read content from the text field, start another activity, and more.
Sources:- http://developer.android.com/training/basics/firstapp/building-ui.html

Platform Versions - update sep 4, 2012


Chaunri | 2:12 PM | , ,

This page provides data about the relative number of active devices running a given version of the Android platform. This can help you understand the landscape of device distribution and decide how to prioritize the development of your application features for the devices currently in the hands of users. For information about how to target your application to devices based on platform version, read about API levels.

Current Distribution

The following pie chart and table is based on the number of Android devices that have accessed Google Play within a 14-day period ending on the data collection date noted below.
Version Codename API Distribution
1.5Cupcake 30.2%
1.6Donut 40.4%
2.1Eclair 73.7%
2.2Froyo 814%
2.3 - 2.3.2 Gingerbread 90.3%
2.3.3 - 2.3.7 1057.2%
3.1 Honeycomb 120.5%
3.2 131.6%
4.0 - 4.0.2 Ice Cream Sandwich140.1%
4.0.3 - 4.0.4 1520.8%
4.1 Jelly Bean161.2%
Data collected during a 14-day period ending on September 4, 2012

Historical Distribution

The following stacked line graph provides a history of the relative number of active Android devices running different versions of the Android platform. It also provides a valuable perspective of how many devices your application is compatible with, based on the platform version.
Notice that the platform versions are stacked on top of each other with the oldest active version at the top. This format indicates the total percent of active devices that are compatible with a given version of Android. For example, if you develop your application for the version that is at the very top of the chart, then your application is compatible with 100% of active devices (and all future versions), because all Android APIs are forward compatible. Or, if you develop your application for a version lower on the chart, then it is currently compatible with the percentage of devices indicated on the y-axis, where the line for that version meets the y-axis on the right.
Each dataset in the timeline is based on the number of Android devices that accessed Google Play within a 14-day period ending on the date indicated on the x-axis.
Last historical dataset collected during a 14-day period ending on September 1, 2012

Screen Sizes and Densities


This section provides data about the relative number of active devices that have a particular screen configuration, defined by a combination of screen size and density. To simplify the way that you design your user interfaces for different screen configurations, Android divides the range of actual screen sizes and densities into:
  • A set of four generalized sizes: small, normal, large, and xlarge
  • A set of four generalized densities: ldpi (low), mdpi (medium), hdpi (high), and xhdpi (extra high)
For information about how you can support multiple screen configurations in your application, see Supporting Multiple Screens.
Note: This data is based on the number of Android devices that have accessed Google Play within a 7-day period ending on the data collection date noted below.

ldpi mdpi hdpi xhdpi
small 1.1%
1.7%
normal 0.4% 11.4% 51.9% 22.3%
large 0.1% 2.5%
3.9%
xlarge
4.7%

Data collected during a 7-day period ending on September 4, 2012

Open GL Version


This section provides data about the relative number of active devices that support a particular version of OpenGL ES. Note that support for one particular version of OpenGL ES also implies support for any lower version (for example, support for version 2.0 also implies support for 1.1).
To declare which version of OpenGL ES your application requires, you should use the android:glEsVersion attribute of the <uses-feature> element. You can also use the <supports-gl-texture> element to declare the GL compression formats that your application uses.
Note: This data is based on the number of Android devices that have accessed Google Play within a 7-day period ending on the data collection date noted below.
OpenGL ES Version Distribution
1.1 only 9.2%
2.0 & 1.1 90.8%
Data collected during a 7-day period ending on September 4, 2012

Gallery intent tutorial in Android


Chaunri | 10:33 AM | ,

to start the users gallery application, allow him to select an image, and use the chosen image in our application.
API Level 3 required!
We will start the operation on a buttons onclick event, implemented as follows:

private static Bitmap Image = null;
private static Bitmap rotateImage = null;
private ImageView imageView;
private static final int GALLERY = 1;
public void onClick(View v) {
  imageView.setImageBitmap(null);
  if (Image != null)
    Image.recycle();
  Intent intent = new Intent();
  intent.setType("image/*");
  intent.setAction(Intent.ACTION_GET_CONTENT);
  startActivityForResult(Intent.createChooser(intent, "Select Picture"), GALLERY);
}


n order to avoid out of memory errors, we must recycle the previous image when the user presses the button second times or after that, so the returned bitmap is stored as a member variable, so we still have a reference for it when it is needs to be recycled.
select_picturegellery_app
We process the result in the onActivityResult method, which is called automatically when the gallery is finished.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == GALLERY && resultCode != 0) {
    Uri mImageUri = data.getData();        
    try {
  Image = Media.getBitmap(this.getContentResolver(), mImageUri);
        if (getOrientation(getApplicationContext(), mImageUri) != 0) {
          Matrix matrix = new Matrix();
          matrix.postRotate(getOrientation(getApplicationContext(), mImageUri));
          if (rotateImage != null)
            rotateImage.recycle();
          rotateImage = Bitmap.createBitmap(Image, 0, 0, Image.getWidth(), Image.getHeight(), matrix,true);
          imageView.setImageBitmap(rotateImage);
        } else
          imageView.setImageBitmap(Image);        
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }


The getOrientation method, used above returns the angle the image was taken. So if it was made with a rotated phone we must rotate the image before we can correctly display it in an ImageView. It can me implemented with the help of the Android MediaStore.
public static int getOrientation(Context context, Uri photoUri) {
    Cursor cursor = context.getContentResolver().query(photoUri,
        new String[] { MediaStore.Images.ImageColumns.ORIENTATION },null, null, null);
 
    if (cursor.getCount() != 1) {
      return -1;
    }
    cursor.moveToFirst();
    return cursor.getInt(0);
  }
 
chosen_image
Download code: LINK
 

Google Maps Android API


Chaunri | 12:41 PM | ,

MapView Tutorial

Using the Google Maps library, you can create your own map-viewing Activity. In this tutorial, you'll create a simple map application in two parts. In Part 1, you'll create an app that shows a map the user can pan and zoom. In Part 2, you'll add overlay items that mark points of interest.
This tutorial requires that you have the external Google Maps library installed in your SDK environment. The Maps library is included with the Google APIs add-on, which you can install using the Android SDK and AVD Manager. To learn how, see Installing the Google APIs Add-On.
After installing the Google APIs add-on in your SDK, set your project properties to use the build target called "Google APIs by Google Inc.". See the instructions for setting a build target in Creating and Managing Projects in Eclipse or Creating and Managing Projects on the Command Line, as appropriate for your environment.
You will also need to set up a new AVD that uses the same Google APIs deployment target. See Creating and Managing Virtual Devices for more information.
For reference material, see the Google Maps library documentation.

Part 1: Creating a Map Activity

  1. Start a new project named HelloGoogleMaps.
  2. Because the Maps library is not a part of the standard Android library, you must declare it in the Android Manifest. Open the AndroidManifest.xml file and add the following as a child of the <application> element:
    <uses-library android:name="com.google.android.maps"/>
  3. You also need access to the Internet in order to retrieve map tiles, so you must also request the INTERNET permission. In the manifest file, add the following as a child of the <manifest> element:
    <uses-permission android:name="android.permission.INTERNET"/>
  4. While you're in the manifest, give the map some more space by getting rid of the title bar with the "NoTitleBar" theme:
    <activity android:name=".HelloGoogleMaps" android:label="@string/app_name"
         android:theme="@android:style/Theme.NoTitleBar">
    
  5. Open the res/layout/main.xml file and add a single MapView as the root node:
    <?xml version="1.0" encoding="utf-8"?>
    <com.google.android.maps.MapView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/mapview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:clickable="true"
        android:apiKey="Your Maps API Key goes here"
    />
    
    The android:clickable attribute defines whether you want to allow user-interaction with the map. If this is "false" then touching the map does nothing.
    The android:apiKey attribute holds the Maps API Key for your application, which proves your application and signer certificate has been registered with the Maps service. This is required in order to receive the map data, even while you are developing. Registration to the service is free and it only takes a couple minutes to register your certificate and get a Maps API Key.
    Go now to get a key. For instructions, read Obtaining a Maps API Key. For the purpose of this tutorial, you should register with the SDK debug certificate, as described in Getting the MD5 Fingerprint of the SDK Debug Certificate. Please note that this is only valid while your application is signed with the debug key; once you sign with your private key, you will need a new API key. When you get your key, insert it for the value of android:apiKey.
  6. Now open the HelloGoogleMaps.java file. For this Activity, extend MapActivity instead of android.app.Activity:
    public class HelloGoogleMaps extends MapActivity
    MapActivity is a special sub-class of Activity, provided by the Maps library, which provides important map capabilities.
  7. Inside every MapActivity, the isRouteDisplayed() method is required, so override this method:
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
    
    This method is required for some accounting from the Maps service to see if you're currently displaying any route information. In this case, you're not, so return false.
  8. Now add the standard onCreate() callback method to the class:
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    This loads the layout file created above. In fact, this is now a workable application that will display map tiles and allow the user to pan around the map. But there's no ability to zoom. Fortunately, there's a very simple zoom feature built into the MapView class, which you can include by calling setBuiltInZoomControls(). Do this at the end of the onCreate() method definition:
        MapView mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
    
  9. That's all there is to it. Run the application. Remember, you must have an AVD configured to use the Google APIs target, or be using a development device that includes the Maps library.

Part 2: Adding Overlay Items

So, now you have a map, but in many cases you'll also want to create your own map markers and lay-overs. That's what you'll do now. In order to do so, you must implement the ItemizedOverlay class, which can manage a whole set of Overlay objects (the individual items placed on the map).
  1. Create a new Java class named HelloItemizedOverlay that extends ItemizedOverlay: When using Eclipse, right-click the package name in the Eclipse Package Explorer, and select New > Class. Set the Name field to HelloItemizedOverlay. For Superclass, enter "com.google.android.maps.ItemizedOverlay. Click the checkbox for Constructors from superclass. Click Finish.
  2. First, you need an OverlayItem ArrayList, in which you'll put each of the OverlayItem objects you want on the map. Add this at the top of the HelloItemizedOverlay class:
    private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
  3. Now define the HelloItemizedOverlay constructors. The constructor must define the default marker for each of the OverlayItem objects. In order for the Drawable to actually get drawn, it must have its bounds defined. Most commonly, you want the center-point at the bottom of the image to be the point at which it's attached to the map coordinates. This is handled for you with the boundCenterBottom() method. Wrap this around the defaultMarker, so the super constructor call looks like this:
    public HelloItemizedOverlay(Drawable defaultMarker) {
      super(boundCenterBottom(defaultMarker));
    }
    
  4. In order to add new OverlayItem objects to the ArrayList, you need a new method:
    public void addOverlay(OverlayItem overlay) {
        mOverlays.add(overlay);
        populate();
    }
    Each time you add a new OverlayItem to the ArrayList, you must call populate() for the ItemizedOverlay, which will read each of the OverlayItem objects and prepare them to be drawn.
  5. When the populate() method executes, it will call createItem(int) in the ItemizedOverlay to retrieve each OverlayItem. You must override this method to properly read from the ArrayList and return the OverlayItem from the position specified by the given integer. Your override method should look like this:
    @Override
    protected OverlayItem createItem(int i) {
      return mOverlays.get(i);
    }
    
  6. You must also override the size() method to return the current number of items in the ArrayList:
    @Override
    public int size() {
      return mOverlays.size();
    }
    
  7. Now set up the ability to handle touch events on the overlay items. First, you're going to need a reference to the application Context as a member of this class. So add Context mContext as a class member, then initialize it with a new class constructor:
    public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
      super(boundCenterBottom(defaultMarker));
      mContext = context;
    }
    
    This passes the defaultMarker up to the default constructor to bound its coordinates and then initializes mContext with the given Context.
    Then override the onTap() callback method, which will handle the event when an item is tapped by the user:
    @Override
    protected boolean onTap(int index) {
      OverlayItem item = mOverlays.get(index);
      AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
      dialog.setTitle(item.getTitle());
      dialog.setMessage(item.getSnippet());
      dialog.show();
      return true;
    }
    
    This uses the member android.content.Context to create a new AlertDialog.Builder and uses the tapped OverlayItem's title and snippet for the dialog's title and message text. (You'll see the OverlayItem title and snippet defined when you create it below.)
You're now done with the HelloItemizedOverlay class and can start using it to add items on the map.
Go back to the HelloGoogleMaps class. In the following procedure, you'll create an OverlayItem and add it to an instance of the HelloItemizedOverlay class, then add the HelloItemizedOverlay to the MapView using a GeoPoint to define its coordinates on the map.
  1. First, you need the image for the map overlay. If you don't have one handy, use the Android on the right. Drag this image (or your own) into the res/drawable/ directory of your project.
  2. At the end of your existing onCreate() method, instantiate :
    List<Overlay> mapOverlays = mapView.getOverlays();
    Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
    HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);
    
    All overlay elements on a map are held by the MapView, so when you want to add some, you have to get a list from the getOverlays() method. Then instantiate the Drawable used for the map marker, which was saved in the res/drawable/ directory. The constructor for HelloItemizedOverlay (your custom ItemizedOverlay) takes the Drawable in order to set the default marker for all overlay items.
  3. Now create a GeoPoint that defines the map coordinates for the first overlay item, and pass it to a new {@code OverlayItem}:
    GeoPoint point = new GeoPoint(19240000,-99120000);
    OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");
    
    GeoPoint coordinates are specified in microdegrees (degrees * 1e6). The OverlayItem constructor accepts the GeoPoint location, a string for the item's title, and a string for the item's snippet text, respectively.
  4. All that's left is to add this OverlayItem to your collection in the HelloItemizedOverlay instance, then add the HelloItemizedOverlay to the MapView:
    itemizedoverlay.addOverlay(overlayitem);
    mapOverlays.add(itemizedoverlay);
    
  5. Now run the application.
You should see the following:
When you tap the overlay item, you'll see the dialog appear.
Because the ItemizedOverlay class uses an java.util.ArrayList for all of the OverlayItem objects, it's easy to add more. Try adding another one. Before the addOverlay() method is called, add these lines:
GeoPoint point2 = new GeoPoint(35410000, 139460000);
OverlayItem overlayitem2 = new OverlayItem(point2, "Sekai, konichiwa!", "I'm in Japan!");
Run the application again. (You probably need to move the map to find the new overlay item.)

Source:- https://developers.google.com/maps/documentation/android/hello-mapview

System requirements fro Android Application Development


Chaunri | 12:20 PM | ,

Operating Systems

  • Windows XP (32-bit), Vista (32- or 64-bit), or Windows 7 (32- or 64-bit)
  • Mac OS X 10.5.8 or later (x86 only)
  • Linux (tested on Ubuntu Linux, Lucid Lynx)
    • GNU C Library (glibc) 2.7 or later is required.
    • On Ubuntu Linux, version 8.04 or later is required.
    • 64-bit distributions must be capable of running 32-bit applications.



Eclipse IDE

  • Eclipse 3.6.2 (Helios) or greater
    Note: Eclipse 3.5 (Galileo) is no longer supported with the latest version of ADT.
  • Eclipse JDT plugin (included in most Eclipse IDE packages)
  • JDK 6 (JRE alone is not sufficient)
  • Android Development Tools plugin (recommended)
  • Not compatible with Gnu Compiler for Java (gcj)

Other development environments

  • JDK 6 (JRE alone is not sufficient)
  • Apache Ant 1.8 or later
  • Not compatible with Gnu Compiler for Java (gcj)
Note: Some Linux distributions may include JDK 1.4 or Gnu Compiler for Java, both of which are not supported for Android development.

Android SQLite Database Tutorial


Chaunri | 12:06 PM | ,

Android provides several ways to store user and app data. SQLite is one way of storing user data. SQLite is a very light weight database which comes with Android OS. In this tutorial I’ll be discussing how to write classes to handle all SQLite operations.

In this tutorial I am taking an example of storing user contacts in SQLite database. I am using a table called Contacts to store user contacts. This table contains three columns id (INT), name (TEXT), phone_number(TEXT).
Following is the structure of contacts table.
Sqlite contacts table 




Writing Contact Class
Before you go further you need to write your Contact class with all getter and setter methods to maintain single contact as an object.
Contact.java
package com.androidhive.androidsqlite;
public class Contact {
    //private variables
    int _id;
    String _name;
    String _phone_number;
    // Empty constructor
    public Contact(){
    }
    // constructor
    public Contact(int id, String name, String _phone_number){
        this._id = id;
        this._name = name;
        this._phone_number = _phone_number;
    }
    // constructor
    public Contact(String name, String _phone_number){
        this._name = name;
        this._phone_number = _phone_number;
    }
    // getting ID
    public int getID(){
        return this._id;
    }
    // setting id
    public void setID(int id){
        this._id = id;
    }
    // getting name
    public String getName(){
        return this._name;
    }
    // setting name
    public void setName(String name){
        this._name = name;
    }
    // getting phone number
    public String getPhoneNumber(){
        return this._phone_number;
    }
    // setting phone number
    public void setPhoneNumber(String phone_number){
        this._phone_number = phone_number;
    }
}
Writing SQLite Database Handler Class
  We need to write our own class to handle all database CRUD(Create, Read, Update and Delete) operations.
1. Create a new project by going to File ⇒ New Android Project.
2. Once the project is created, create a new class in your project src directory and name it as DatabaseHandler.java ( Right Click on src/package ⇒ New ⇒ Class)
3. Now extend your DatabaseHandler.java class from SQLiteOpenHelper.
public class DatabaseHandler extends SQLiteOpenHelper {
4. After extending your class from SQLiteOpenHelper you need to override two methods onCreate() and onUpgrage()
onCreate() – These is where we need to write create table statements. This is called when database is created.
onUpgrade() – This method is called when database is upgraded like modifying the table structure, adding constraints to database etc.,
public class DatabaseHandler extends SQLiteOpenHelper {
    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "contactsManager";
    // Contacts table name
    private static final String TABLE_CONTACTS = "contacts";
    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NO = "phone_number";
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                + KEY_PH_NO + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
        // Create tables again
        onCreate(db);
    }
⇒All CRUD Operations (Create, Read, Update and Delete)
Now we need to write methods for handling all database read and write operations. Here we are implementing following methods for our contacts table.
// Adding new contact
public void addContact(Contact contact) {}
// Getting single contact
public Contact getContact(int id) {}
// Getting All Contacts
public List<Contact> getAllContacts() {}
// Getting contacts Count
public int getContactsCount() {}
// Updating single contact
public int updateContact(Contact contact) {}
// Deleting single contact
public void deleteContact(Contact contact) {}
⇒Inserting new Record
The addContact() method accepts Contact object as parameter. We need to build ContentValues parameters using Contact object. Once we inserted data in database we need to close the database connection.
addContact()
    // Adding new contact
public void addContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName()); // Contact Name
    values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone Number
    // Inserting Row
    db.insert(TABLE_CONTACTS, null, values);
    db.close(); // Closing database connection
}
⇒Reading Row(s)
The following method getContact() will read single contact row. It accepts id as parameter and will return the matched row from the database.
getContact()
    // Getting single contact
public Contact getContact(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
            KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();
    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2));
    // return contact
    return contact;
}
getAllContacts() will return all contacts from database in array list format of Contact class type. You need to write a for loop to go through each contact.
getAllContacts()
    // Getting All Contacts
 public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setID(Integer.parseInt(cursor.getString(0)));
            contact.setName(cursor.getString(1));
            contact.setPhoneNumber(cursor.getString(2));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }
    // return contact list
    return contactList;
}
getContactsCount() will return total number of contacts in SQLite database.
getContactsCount()
// Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();
        // return count
        return cursor.getCount();
    }
⇒Updating Record
updateContact() will update single contact in database. This method accepts Contact class object as parameter.
updateContact()
    // Updating single contact
public int updateContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName());
    values.put(KEY_PH_NO, contact.getPhoneNumber());
    // updating row
    return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
}
⇒Deleting Record
deleteContact() will delete single contact from database.
deleteContact()
    // Deleting single contact
public void deleteContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
    db.close();
}
Complete DatabaseHandler.java Code:
DatabaseHandler.java
package com.androidhive.androidsqlite;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "contactsManager";
    // Contacts table name
    private static final String TABLE_CONTACTS = "contacts";
    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NO = "phone_number";
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                + KEY_PH_NO + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
        // Create tables again
        onCreate(db);
    }
    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */
    // Adding new contact
    void addContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName()); // Contact Name
        values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
        // Inserting Row
        db.insert(TABLE_CONTACTS, null, values);
        db.close(); // Closing database connection
    }
    // Getting single contact
    Contact getContact(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();
        Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2));
        // return contact
        return contact;
    }
    // Getting All Contacts
    public List<Contact> getAllContacts() {
        List<Contact> contactList = new ArrayList<Contact>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Contact contact = new Contact();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setName(cursor.getString(1));
                contact.setPhoneNumber(cursor.getString(2));
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }
        // return contact list
        return contactList;
    }
    // Updating single contact
    public int updateContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName());
        values.put(KEY_PH_NO, contact.getPhoneNumber());
        // updating row
        return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
    }
    // Deleting single contact
    public void deleteContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
        db.close();
    }
    // Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();
        // return count
        return cursor.getCount();
    }
}
Usage:
AndroidSQLiteTutorialActivity
<span>package com.androidhive.androidsqlite;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class AndroidSQLiteTutorialActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        DatabaseHandler db = new DatabaseHandler(this);
        /**
         * CRUD Operations
         * */
        // Inserting Contacts
        Log.d("Insert: ", "Inserting ..");
        db.addContact(new Contact("Ravi", "9100000000"));
        db.addContact(new Contact("Srinivas", "<a style="cursor:pointer">9199999999</a>"));
        db.addContact(new Contact("Tommy", "<a style="cursor:pointer">9522222222</a>"));
        db.addContact(new Contact("Karthik", "<a style="cursor:pointer">9533333333</a>"));
        // Reading all contacts
        Log.d("Reading: ", "Reading all contacts..");
        List<Contact> contacts = db.getAllContacts();      
        for (Contact cn : contacts) {
            String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " + cn.getPhoneNumber();
                // Writing Contacts to log
        Log.d("Name: ", log);
    }
    }
}
</span>
Android Log Cat Report:
I am writing output to Log report. You can see your log report by going to Windows ⇒ Show View ⇒ Other.. ⇒ Android ⇒ Log Cat.
Android Log Cat
Android Log Cat
Android Output log report
Tutorials Source:- http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/