Friday, December 18, 2009

Hello, Stack Overflow!

Over the past year, an Android presence has been growing on a relatively new technical Q&A web site called Stack Overflow. The site was designed specifically for programmers, with features like syntax highlighting, tagging, user reputation, and community editing. It's attracted a loyal software developer community, and developers continue to express great praise for this new tool. Well, the Android team has been listening...and we agree.

Today, I'm happy to announce that we're working with Stack Overflow to improve developer support, especially for developers new to Android. In essence, the Android tag on Stack Overflow will become an official Android app development Q&A medium. We encourage you to post your beginner-level technical questions there. It's also important to point out that we don't plan to change the android-developers group, so intermediate and expert users should still feel free to post there.

I think that this will be a great new resource for novice Android developers, and our team is really excited to participate in the growth of the Android developer community on Stack Overflow. I hope to see you all there!

Back and other hard keys: three stories

Android 2.0 introduces new behavior and support for handling hard keys such as BACK and MENU, including some special features to support the virtual hard keys that are appearing on recent devices such as Droid.

This article will give you three stories on these changes: from the most simple to the gory details. Pick the one you prefer.

Story 1: Making things easier for developers

If you were to survey the base applications in the Android platform, you would notice a fairly common pattern: add a little bit of magic to intercept the BACK key and do something different. To do this right, the magic needs to look something like this:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
// do something on back.
return true;
}

return super.onKeyDown(keyCode, event);
}

How to intercept the BACK key in an Activity is also one of the common questions we see developers ask, so as of 2.0 we have a new little API to make this more simple and easier to discover and get right:

@Override
public void onBackPressed() {
// do something on back.
return;
}

If this is all you care about doing, and you're not worried about supporting versions of the platform before 2.0, then you can stop here. Otherwise, read on.

Story 2: Embracing long press

One of the fairly late addition to the Android platform was the use of long press on hard keys to perform alternative actions. In 1.0 this was long press on HOME for the recent apps switcher and long press on CALL for the voice dialer. In 1.1 we introduced long press on SEARCH for voice search, and 1.5 introduced long press on MENU to force the soft keyboard to be displayed as a backwards compatibility feature for applications that were not yet IME-aware.

(As an aside: long press on MENU was only intended for backwards compatibility, and thus has some perhaps surprising behavior in how strongly the soft keyboard stays up when it is used. This is not intended to be a standard way to access the soft keyboards, and all apps written today should have a more standard and visible way to bring up the IME if they need it.)

Unfortunately the evolution of this feature resulted in a less than optimal implementation: all of the long press detection was implemented in the client-side framework's default key handling code, using timed messages. This resulted in a lot of duplication of code and some behavior problems; since the actual event dispatching code had no concept of long presses and all timing for them was done on the main thread of the application, the application could be slow enough to not update within the long press timeout.

In Android 2.0 this all changes, with a real KeyEvent API and callback functions for long presses. These greatly simplify long press handling for applications, and allow them to interact correctly with the framework. For example: you can override Activity.onKeyLongPress() to supply your own action for a long press on one of the hard keys, overriding the default action provided by the framework.

Perhaps most significant for developers is a corresponding change in the semantics of the BACK key. Previously the default key handling executed the action for this key when it was pressed, unlike the other hard keys. In 2.0 the BACK key is now execute on key up. However, for existing apps, the framework will continue to execute the action on key down for compatibility reasons. To enable the new behavior in your app you must set android:targetSdkVersion in your manifest to 5 or greater.

Here is an example of code an Activity subclass can use to implement special actions for a long press and short press of the CALL key:

@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_CALL) {
// a long press of the call key.
// do our work, returning true to consume it. by
// returning true, the framework knows an action has
// been performed on the long press, so will set the
// canceled flag for the following up event.
return true;
}
return super.onKeyLongPress(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_CALL && event.isTracking()
&& !event.isCanceled()) {
// if the call key is being released, AND we are tracking
// it from an initial key down, AND it is not canceled,
// then handle it.
return true;
}
return super.onKeyUp(keyCode, event);
}

Note that the above code assumes we are implementing different behavior for a key that is normally processed by the framework. If you want to implement long presses for another key, you will also need to override onKeyDown to have the framework track it:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_0) {
// this tells the framework to start tracking for
// a long press and eventual key up. it will only
// do so if this is the first down (not a repeat).
event.startTracking();
return true;
}
return super.onKeyDown(keyCode, event);
}

Story 3: Making a mess with virtual keys

Now we come to the story of our original motivation for all of these changes: support for virtual hard keys, as seen on the Droid and other upcoming devices. Instead of physical buttons, these devices have a touch sensor that extends outside of the visible screen, creating an area for the "hard" keys to live as touch sensitive areas. The low-level input system looks for touches on the screen in this area, and turns these into "virtual" hard key events as appropriate.

To applications these basically look like real hard keys, though the generated events will have a new FLAG_VIRTUAL_HARD_KEY bit set to identify them. Regardless of that flag, in nearly all cases an application can handle these "hard" key events in the same way it has always done for real hard keys.

However, these keys introduce some wrinkles in user interaction. Most important is that the keys exist on the same surface as the rest of the user interface, and they can be easily pressed with the same kind of touches. This can become an issue, for example, when the virtual keys are along the bottom of the screen: a common gesture is to swipe up the screen for scrolling, and it can be very easy to accidentally touch a virtual key at the bottom when doing this.

The solution for this in 2.0 is to introduce a concept of a "canceled" key event. We've already seen this in the previous story, where handling a long press would cancel the following up event. In a similar way, moving from a virtual key press on to the screen will cause the virtual key to be canceled when it goes up.

In fact the previous code already takes care of this — by checking isCanceled() on the key up, canceled virtual keys and long presses will be ignored. There are also individual flags for these two cases, but they should rarely be used by applications and always with the understanding that in the future there may be more reasons for a key event to be canceled.

For existing application, where BACK key compatibility is turned on to execute the action on down, there is still the problem of accidentally detecting a back press when intending to perform a swipe. Though there is no solution for this except to update an application to specify it targets SDK version 5 or later, fortunately the back key is generally positioned on a far side of the virtual key area, so the user is much less likely to accidentally hit it than some of the other keys.

Writing an application that works well on pre-2.0 as well as 2.0 and later versions of the platform is also fairly easy for most common cases. For example, here is code that allows you to handle the back key in an activity correctly on all versions of the platform:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
// Take care of calling this method on earlier versions of
// the platform where it doesn't exist.
onBackPressed();
}

return super.onKeyDown(keyCode, event);
}

@Override
public void onBackPressed() {
// This will be called either automatically for you on 2.0
// or later, or by the code above on earlier versions of the
// platform.
return;
}

For the hard core: correctly dispatching events

One final topic that is worth covering is how to correctly handle events in the raw dispatch functions such as onDispatchEvent() or onPreIme(). These require a little more care, since you can't rely on some of the help the framework provides when it calls the higher-level functions such as onKeyDown(). The code below shows how you can intercept the dispatching of the BACK key such that you correctly execute your action when it is release.

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getRepeatCount() == 0) {

// Tell the framework to start tracking this event.
getKeyDispatcherState().startTracking(event, this);
return true;

} else if (event.getAction() == KeyEvent.ACTION_UP) {
getKeyDispatcherState().handleUpEvent(event);
if (event.isTracking() && !event.isCanceled()) {

// DO BACK ACTION HERE
return true;

}
}
return super.dispatchKeyEvent(event);
} else {
return super.dispatchKeyEvent(event);
}
}

The call to getKeyDispatcherState() returns an object that is used to track the current key state in your window. It is generally available on the View class, and an Activity can use any of its views to retrieve the object if needed.

Thursday, December 17, 2009

New resources and sample code on developer.android.com

Hey Android developers—if you've visited the online Android SDK documentation recently, you may have noticed a few changes. That's right, there's a new Resources tab, which was designed to take some of the load off the Developer's Guide. We've moved a number of existing resources to the Resources tab, including tutorials, sample code, and FAQs. We've also formalized a few of our most popular developer blog posts into technical articles; watch for more of these to appear in the future.

In addition, we just released a new batch of sample code, available now as a ZIP file download on the samples index page. And we're working on updating the way in which we distribute official sample code; more on that some other time.

New sample screenshots

The new sample code includes:

  • Multiple Resolutions: a simple example showing how to use resource directory qualifiers to support multiple screen configurations and Android SDK versions.
  • Wiktionary and WiktionarySimple: sample applications that illustrate how to create an interactive home screen widget.
  • Contact Manager: an example on using the new ContactsContract interface to query and manipulate a user's various accounts and contact providers.
  • Bluetooth Chat: a fun little demo that allows two users to have a 1 on 1 chat over Bluetooth. It demonstrates how to discover devices, initiate a connection, and transfer data.
  • API Demos > App > Activity > QuickContactsDemo: a demo showing how to use the android.widget.QuickContactsBadge class, new in Android 2.0.
  • API Demos > App > Activity > SetWallpaper: a demo showing how to use the new android.app.WallpaperManager class to allow users to change the system wallpaper.
  • API Demos > App > Text-To-Speech: a sample using Text-To-Speech (speech synthesis) to make your application talk.
  • NotePad (now with Live Folders): this sample now includes code for creating Live Folders.

We hope these new samples can be a valuable resource for learning some of the newer features in Android 1.6 and 2.0. Let us know in the android-developers Google Group if you have any questions about these new samples or about the new Resources tab.

Thanks for tuning in, and 'til next time, happy coding!

Knowing is half the battle

As a developer, I often wonder which Android platforms my applications should support,especially as the number of Android-powered devices grows. Should my application only focus on the latest version of the platform or should it support older ones as well?

To help with this kind of decision, I am excited to announce the new
device dashboard. It provides information about deployed Android-powered devices that is helpful to developers as they build and update their apps. The dashboard provides the relative distribution of Android platform versions on devices running Android Market.


Android PlatformPercentage of Devices
1.10.3%
1.527.7%
1.654.2%
2.02.9%
2.0.114.8%

The above graph shows the relative number of Android devices that have accessed Android Market during the first 14 days of December 2009.

From a developer's perspective, there are a number of interesting points on this graph:

  • At this point, there's little incentive to make sure a new application is
    backward compatible with Android 1.0 and Android 1.1.
  • Close to 30% of the devices are running Android 1.5. To take advantage of this significant install base, you may consider support for Android 1.5.
  • Starting with Android 1.6, devices can have different screen densities & sizes. There are several devices out there that fall in this category, so make sure to adapt your application to support different screen sizes and take advantage of devices with small, low density (e.g QVGA) and normal, high density (e.g. WVGA) screens. Note that Android Market will not list your application on small screen devices unless its manifest explicitly indicates support for "small" screen sizes. Make sure you properly configure the emulator and test your application on different screen sizes before uploading to Market.
  • A new SDK for Android 2.0.1 was released two weeks ago. All Android 2.0 devices will be updated to 2.0.1 before the end of the year, so if your application uses features specific to Android 2.0, you are encouraged to update it to take advantage of the latest Android 2.0.1 API instead.

In summary, Android 1.5, 1.6, and 2.0.1 are the 3 versions of the platform that are deployed in volume. Our goal is to provide you with the tools and information to make it easy for you to target specific versions of the platform or all the versions that are deployed in volume.

We plan to update the dashboard regularly to reflect deployment of new Android platforms. We also plan to expand the dashboard to include other information like devices per screen size and so on.

Friday, December 11, 2009

Come to Our Virtual Office Hours

Starting this week, we're going to be holding regular IRC office hours for Android app developers in the #android-dev channel on irc.freenode.net. Members of the Android team will be on hand to answer your technical questions. (Note that we will not be able to provide customer support for the phones themselves.)

We've arranged our office hours to accommodate as many different schedules as possible, for folks around the world. We will initially hold two sessions each week:

  • 12/15/09 Tuesday, 9 a.m. to 10 a.m. PST
  • 12/17/09, Thursday 5 p.m. to 6 p.m. PST
  • 12/22/09, Tuesday 9 a.m. to 10 a.m. PST
  • 01/06/10 Wednesday 9 a.m. to 10 a.m. PST
  • 01/07/10 Thursday 5 p.m. to 6 p.m. PST

Check Wikipedia for a helpful list of IRC clients. Alternatively, you could use a web interface such as the one at freenode.net. We will try to answer as many as we can get through in the hour.

We hope to see you there!

Thursday, December 10, 2009

Optimize your layouts



Writing user interface layouts for Android applications is easy, but it can sometimes be difficult to optimize them. Most often, heavy modifications made to existing XML layouts, like shuffling views around or changing the type of a container, lead to inefficiencies that go unnoticed.

Starting with the SDK Tools Revision 3 you can use a tool called layoutopt to automatically detect common problems. This tool is currently only available from the command line and its use is very simple - just open a terminal and launch the layoutopt command with a list of directories or XML files to analyze:


$ layoutopt samples/
samples/compound.xml
7:23 The root-level <FrameLayout/> can be replaced with <merge/>
11:21 This LinearLayout layout or its FrameLayout parent is useless samples/simple.xml
7:7 The root-level <FrameLayout/> can be replaced with <merge/>
samples/too_deep.xml
-1:-1 This layout has too many nested layouts: 13 levels, it should have <= 10!
20:81 This LinearLayout layout or its LinearLayout parent is useless
24:79 This LinearLayout layout or its LinearLayout parent is useless
28:77 This LinearLayout layout or its LinearLayout parent is useless
32:75 This LinearLayout layout or its LinearLayout parent is useless
36:73 This LinearLayout layout or its LinearLayout parent is useless
40:71 This LinearLayout layout or its LinearLayout parent is useless
44:69 This LinearLayout layout or its LinearLayout parent is useless
48:67 This LinearLayout layout or its LinearLayout parent is useless
52:65 This LinearLayout layout or its LinearLayout parent is useless
56:63 This LinearLayout layout or its LinearLayout parent is useless
samples/too_many.xml
7:413 The root-level <FrameLayout/> can be replaced with <merge/>
-1:-1 This layout has too many views: 81 views, it should have <= 80! samples/useless.xml
7:19 The root-level <FrameLayout/> can be replaced with <merge/>
11:17 This LinearLayout layout or its FrameLayout parent is useless
For each analyzed file, the tool will indicate the line numbers of each tag that could potentially be optimized. In some cases, layoutopt will also offer a possible solution.

The current version of layoutopt contains a dozen rules used to analyze your layout files and future versions will contain more. Future plans for this tool also include the ability to create and use your own analysis rules, to automatically modify the layouts with optimized XML, and to use it from within Eclipse and/or a standalone user interface.


Windows users: to start layoutopt, open the file called layoutopt.bat in the tools directory of the SDK and on the last line, replace %jarpath% with -jar %jarpath%.

Monday, December 7, 2009

Sample Android Activity,Service ( 1 )

An activity is the equivalent of a Frame/Window in GUI toolkits. It takes up the entire drawable area of the screen. An activity is what gets bound to the AndroidManifest.xml as the main entry point into an application. For long running tasks, it’s best to use a service that talks to this activity.

Service : Activities are meant to display the UI and get input from the user. Services on the other hand keep running for the duration of the user’s ‘session’ on the device.


Activity Navigation:
This has done by the following two ways.
1. Fire and forget – create an event (Intent) and fire it
2. Async callback – create an event (Intent), fire it, and wait for it’s response in a callback method (of the calling-Activity).

Activity history stack
Please note that Android maintains a history stack of all the Activities that have been spawned in an application’s Linux process. In the sample code above, the calling-Activity simply provides the class name of the sub-Activity. When the sub-Activity finishes, it puts it’s result code and any data back on the stack and finishes itself. Since Android maintains the stack, it knows which calling Activity to pass the result back to. The calling-Activity has an onActivityResult method that handles all the callbacks from the sub-Activities. This is pretty confusing at first, since to keep it all straight we have to use CorrelationIds (more on that below).

Example : User wants to navigate Talk application to Browser Application. Using the Browser application wants to serach some photos and saved his local memory. After that he shares the photo with his friend via email application and finally he will come back to the talk application.

Firstly, as the user is talking to his friend, a specific Talk application is opened, which contains the activity manager. System Creates two processes, the main system process and Talk application process. Moreover, before going to Web Browser application, the system saves a Talk state T in order to remember that process. At this point, as a user holds a talk and opens a web browser, the system creates a new process and new web browser activity is launched in it. Again, the state of the last activity is saved.After that, the user browses the internet, finds his picture in Picasa album and saves it to particular folder. He does not close a web browser, instead he opens a folder to find saved picture. The folder activity is launched in particular process.  At this point, the user finds his saved picture in the folder and he creates a request to open an Email application. The last state F is saved. Now assume that the mobile phone is out of the memory and there is no room to create a new process for Email application. Therefore, Android looks to kill a process. It can not destroy Folder process, as it was used previously and could be reused again, so it kills Web Browser process as it is not useful anymore and locates a new Email process instead. The user opens Email application and sends a picture to his friend via email. Now he wants to go back to the Talk application and to resume a talk to his friend. Because of the previously saved states, this work is done fast and easily. In this example, Email application is popped out and the user sees a previous Folder application.Next, the user goes back to Web Browser application. Unfortunately, web browser
process was killed previously so the system has to kill another process (in our case it is Email application process, which is not used anymore) in order to locate Web Browser process and manage the stack memory. Now the user comes back to the Talk application and resumes his talk with his friend. Because of the saved states, going back procedure is fast and useful, because it remembers previous activities and its views.
This example shows, that it does not matter how many applications and processes are active or how much available memory is left, Android it manages fast and without a user interaction.

Fire and forget
For this method we just calls the child activity and flow the process. we are not getting any return value from the child activity. Here intent is just an event. It can have a target of an activity calss along with some date that's passed in via a Bundle.
refer : http://about-android.blogspot.com/2009/12/passing-data-or-parameter-to-another_02.html


1. Create a two Activity [MainActivity & ChildActivity]

Activity : 1 -  MainActivity
 public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }
}
 
 Activity : 2 - ChildActivity
 public class ChildActivity extends Activity {
     /**
      * @see android.app.Activity#onCreate(Bundle)
      */
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         // TODO Put your code here
     }
 }
 

2.  Define Your Shared collection
    Bundle bundle = new Bundle();
    bundle.putString("sample", "this is the test commands");

3. Call the child Activity from mainactivity with the bundle
    startActivity(new Intent(this, ChildActivity.class).putExtras(bundle));
 
4. Get the Value from MainActivity in ChildActivity
     this.getIntent().getExtras().getString("sample")

5. Toast the Message
    Toast.makeText(this, this.getIntent().getExtras().getString("sample"),
            Toast.LENGTH_LONG).show();



Full Source :MainActivity.java
 
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Bundle bundle = new Bundle();
        bundle.putString("sample", "this is the test commands");
        bundle.putString("sample1", "this is the test commands1");
        startActivity(new Intent(this, ChildActivity.class).putExtras(bundle));
    }
}

-------ChildActivity.java----------
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

public class ChildActivity extends Activity {
    /**
     * @see android.app.Activity#onCreate(Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(this, this.getIntent().getExtras().getString("sample"),
                Toast.LENGTH_LONG).show();
        Toast.makeText(this, this.getIntent().getExtras().getString("sample1"),
                Toast.LENGTH_LONG).show();
    }
}   
 

Async callback, and correlationId
The calling-Activity has to provide a correlationId/request code to the Intent/event, before firing/raising it. This is then used by the sub-Activity to report it’s results back to the calling-Activity when it’s ready. The calling-Activity does not stop when it spawns the sub-Activity.

Please note that this sub-Activity is not "modal", that is, the calling Activity does not block, when startSubActivity() is called. So if you’re thinking that this is like a modal dialog box, where the calling-Activity will wait for the sub-Activity to produce a result, then you have to think of it differently.


1. Create a two Activity [MainActivity & ChildActivity]

Activity : 1 -  MainActivity
 public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }
}
 
 Activity : 2 - ChildActivity
 public class ChildActivity extends Activity {
     /**
      * @see android.app.Activity#onCreate(Bundle)
      */
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         // TODO Put your code here
     }
 }
 

2. Call the child Activity from mainactivity with the bundle
    Intent i = new Intent(this, ChildActivity.class);
    startActivityForResult(i, 1);
 
4. Set the Value from ChildActivity To  MainActivity
    setResult(RESULT_OK, new Intent().putExtra("result", "value from Child Activity"));
    finish();

5. Receive the value from ChildActiivity and Print the Message in onActivityResult Method
    if (resultCode == RESULT_OK) {
        String name = data.getStringExtra("result");
        Toast.makeText(this, "You have chosen the City: " + " " + name,
                Toast.LENGTH_LONG).show();
    }

Source Code

MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Intent i = new Intent(this, ChildActivity.class);
        startActivityForResult(i, 1);
    }
   
    protected void start(Intent intent) {
        this.startActivityForResult(intent, 1);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       
               
        if (resultCode == RESULT_OK) {
            String name = data.getStringExtra("result");
            Toast.makeText(this, "You have chosen the Value: " + " " + name,
                    Toast.LENGTH_LONG).show();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

}

ChildActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class ChildActivity extends Activity {
    /**
     * @see android.app.Activity#onCreate(Bundle)
     */
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(this, "Child Activity", Toast.LENGTH_LONG).show();       
        setResult(RESULT_OK, new Intent().putExtra("result", "value from Child Activity"));
        finish();
    }
}


Thursday, December 3, 2009

Android SDK Updates

Today we are releasing updates to multiple components of the Android SDK:

  • Android 2.0.1, revision 1
  • Android 1.6, revision 2
  • SDK Tools, revision 4

Android 2.0.1 is a minor update to Android 2.0. This update includes several bug fixes and behavior changes, such as application resource selection based on API level and changes to the value of some Bluetooth-related constants. For more detailed information, please see the Android 2.0.1 release notes.

To differentiate its behavior from Android 2.0, the API level of Android 2.0.1 is 6. All Android 2.0 devices will be updated to 2.0.1 before the end of the year, so developers will no longer need to support Android 2.0 at that time. Of course, developers of applications affected by the behavior changes should start compiling and testing their apps immediately.

We are also providing an update to the Android 1.6 SDK component. Revision 2 includes fixes to the compatibility mode for applications that don't support multiple screen sizes, as well as SDK fixes. Please see the Android 1.6, revision 2 release notes for the full list of changes.

Finally, we are also releasing an update to the SDK Tools, now in revision 4. This is a minor update with mostly bug fixes in the SDK Manager. A new version of the Eclipse plug-in that embeds those fixes is also available. For complete details, please see the SDK Tools, revision 4 and ADT 0.9.5 release notes.

One more thing: you can now follow us on twitter @AndroidDev.

Working with Alert / Log / Notification in Android

Here we are discussing about the some essential Source which is helps to track or use the inbuild system call.
1. Toast
    Toast notification are holdes alert message to the user. It does not accept the interaction events. It automatically fades in and out.

System Toast Notification
Activity : 1 -  MainActivity
 public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }
}
 

2.  Define Toast Object and Message
    // One-line Toast Notification Implementation
    Toast.makeText(this, "Demo Toast", Toast.LENGTH_LONG).show();

    // Change the Notification Position
    Toast myToast = Toast.makeText(this, "Demo Toast", Toast.LENGTH_LONG);
    myToast.setGravity(Gravity.TOP, 100, 100);
    myToast.show();

3. Save and run the Project.

Custom Toast Notification
Activity : 1 -  MainActivity
 public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }
}


2. Layout : Create a custom Layout with some icon and text message

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout android:id="@+id/AbsoluteLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
    <ImageView android:id="@+id/ImageView01" android:layout_height="wrap_content"
    android:layout_width="wrap_content" android:layout_y="161dip" android:layout_x="45dip"
    android:background="@drawable/icon"></ImageView>
    <TextView android:layout_width="wrap_content" android:layout_x="131dip"
    android:layout_height="wrap_content" android:layout_y="163dip" android:id="@+id/TextView01"
    android:text="Custom Message"></TextView>
</AbsoluteLayout>

3. Get the Layout View using the LayoutInflator in Activity Class
    LayoutInflater inflater = getLayoutInflater();
    View layout = inflater.inflate(R.layout.custommessage,
        (ViewGroup) findViewById(R.id.AbsoluteLayout01));

4. Define the Toast object with the custom message.
        Toast toast = new Toast(getApplicationContext());
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP | Gravity.LEFT, 100, 100);
        toast.setView(layout);
        toast.show();

5. Save and run the Project.

Full Source
custommessage.xml - Layout
    <?xml version="1.0" encoding="utf-8"?>
    <AbsoluteLayout android:id="@+id/AbsoluteLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
        <ImageView android:id="@+id/ImageView01" android:layout_height="wrap_content"
        android:layout_width="wrap_content" android:layout_y="161dip" android:layout_x="45dip"
        android:background="@drawable/icon"></ImageView>
        <TextView android:layout_width="wrap_content" android:layout_x="131dip"
        android:layout_height="wrap_content" android:layout_y="163dip" android:id="@+id/TextView01"
        android:text="Custom Message"></TextView>
    </AbsoluteLayout>
    
    
    
MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // One-line Toast Notification Implementation
        Toast.makeText(this, "Demo Toast", Toast.LENGTH_LONG).show();

        // Change the Notification Position
        Toast myToast = Toast.makeText(this, "Demo Toast", Toast.LENGTH_LONG);
        myToast.setGravity(Gravity.TOP, 100, 100);
        myToast.show();

        // Custom Notification
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.custommessage,
                (ViewGroup) findViewById(R.id.AbsoluteLayout01));
        Toast toast = new Toast(getApplicationContext());
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP | Gravity.LEFT, 100, 100);
        toast.setView(layout);
        toast.show();

    }
}


Log -
Log Class provides to create a log statement with Key Value Pair.
You can create Log statement using the following steps.
1. Create a Project -> Activity
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
    }
}
2. Call the d() with Key value pair. ->
    Log.d("@G MYLOG","Sample Log Message");
    Key -> @G MYLOG
    Value->Sample Log Message
    
3. Run and Check the Log.
    Go to Window->Show View -> Android -> Log Cat


    

Source :
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.d("@G MYLOG","Sample Log Message");
    }
}


Wednesday, December 2, 2009

Database Programming in android

Android provides four ways to achieve the persistence.
Preferences - Basically used for storing user preferences for a single application or across applications for a mobile. This is typically name-value pairs accessible to the context.
Databases - Android supports creating of databases based on SQLite db. Each database is private to the applications that creates it
Files - Files can be directly stored on the mobile or on to an extended storage medium. By default other applications cannot access it.
Network - Data can be stored and retrieved from the network too depending on the availability.    

Preference :
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). First we need to put our value in to the context. And the context object lets you retrieve SharedPreferences through the method Context.getSharedPreferences().

1. Make a Shared Preference Collection
2. Retrieve Shared Preference Collection

Make a Shared Preference Collection
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
    SharedPreferences.Editor prefsEditor = myPrefs.edit();
    prefsEditor.putString("sample", "this is test commands");
    prefsEditor.commit();


Retrieve Shared Preference Collection
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
    prefsEditor.getString("sample", "DEFAULT VALUE")
;


Creating and Using Databases in Android
Every application uses data, and Android applications are no exception. Android uses the open-source, stand-alone SQL database, SQLite. Learn how to create and manipulate a SQLite database for your Android app.

Android uses the SQLite database system, which is an open-source, stand-alone SQL database, widely used by many popular applications.

In Android, the database that you create for an application is only accessible to itself; other applications will not be able to access it. Once created, the SQLite database is stored in the /data/data//databases folder of an Android device. In this article, you will learn how to create and use a SQLite database in Android.

Here we are going to introduce two new class for database programming.
Class 1. Create a SQLiteFactoryManager which is provide the database.
Class 2. Create a DAOHelper which provides CRUD Operation.


Create a SQLiteFactoryManager which is provide the database.
SQLiteFactoryManager is used to create a database and tables
Step 1: Create a SQLConnectionFactory class which extends the SQLiteOpenHelper
        public class SQLConnectionFactory extends SQLiteOpenHelper {

Step 2: Create a database using the SQLiteOpenHelper constructor
        public SQLConnectionFactory(Context context) {
            super(context, DATABASENAME, null, 1);   
        }


Step 3: Create Tables
    db.execSQL(CREATE_USERTABLE);
   

SAMPLE SOURCE   

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

public class SQLConnectionFactory extends SQLiteOpenHelper {

    private static final String DATABASENAME = "BIRTHDAY";
    private static final String CREATE_USERTABLE = "CREATE TABLE BIRTHDAY(ID INTEGER NOT NULL CONSTRAINT USER_PK PRIMARY KEY AUTOINCREMENT,NAME TEXT,CATEGORY TEXT,DOB DATE,AGE INTEGER)";
   
    public SQLConnectionFactory(Context context) {
        super(context, DATABASENAME, null, 1);   
    }
   
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_USERTABLE);
        Log.d("@G SQLConnectionFactory", " CREATE_USERTABLE Table ");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}


Create a DAOHelper which provides CRUD Operation.
Step1: Get the Factory Object from SQLConnectionFactory.
        factoryObj = new SQLConnectionFactory(c);

Step2: Get the readable/writeable database object using the Factory Object.
        public static SQLiteDatabase getReadableDataBase(Context c) {
            return factoryObj.getReadableDatabase();
        }

        public static SQLiteDatabase getWriteableDataBase(Context c) {
            return factoryObj.getReadableDatabase();
        }


Step 3: Perform the CRUD operation using SQLite query. insertData,removeData,getData.

Sample Code

import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import android.widget.ArrayAdapter;

public class DAOHelper {

    static SQLConnectionFactory factoryObj;
    static SQLiteDatabase database;

    public DAOHelper(Context c) {
        factoryObj = new SQLConnectionFactory(c);
    }

    public static SQLiteDatabase getReadableDataBase(Context c) {
        return factoryObj.getReadableDatabase();
    }

    public static SQLiteDatabase getWriteableDataBase(Context c) {
        return factoryObj.getWriteableDatabase();
    }

    public void insertData(Context c, Object bindValue[]) {
        database = getWriteableDataBase(c);
        SQLiteStatement statement = database
                .compileStatement("SELECT MAX(ID) + 1 FROM BIRTHDAY");
        long taskId = statement.simpleQueryForLong();
        if (taskId <= 0) {
            taskId = 1;
        }
        database.execSQL(
                "INSERT INTO BIRTHDAY(NAME,CATEGORY,DOB) VALUES(?,?,?)",
                bindValue);
    }

    public ArrayList getData(Context c, Object bindValue[]) {
        ArrayList taskNameList = new ArrayList();
        try {
            database = database = getReadableDataBase(c);
            Cursor results = database.rawQuery("SELECT * FROM BIRTHDAY", null);
            if (results.moveToFirst()) {
                for (; !results.isAfterLast(); results.moveToNext()) {
                    taskNameList.add(results.getString(1) + " - "
                            + results.getString(3));
                }
            }
        } catch (Exception e) {
            Log.e("Tasks App", "Unable to to refresh tasks.", e);
        } finally {
            return taskNameList;
        }
    }

    public boolean removeData(Context c, Object bindValue[]) {
        try {
            database = database = getReadableDataBase(c);
            database.execSQL("DELETE FROM BIRTHDAY WHERE ID in (?)", bindValue);
        } catch (Exception e) {
            Log.e("Remove Data", "Unable to to DELETE id.", e);
        } finally {
            return true;
        }
    }

}

Hope this is helpful for you



Passing data or parameter to another Activity Android - 2

Passing data or parameter to another Activity Android - using Bundle
This following step helps to share the content using bundle.
 1. Create a two Activity [MainActivity & ChildActivity]

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

 
 Activity : 2 - ChildActivity
 public class ChildActivity extends Activity {
     /**
      * @see android.app.Activity#onCreate(Bundle)
      */
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         // TODO Put your code here
     }
 }

 

2.  Define Your Shared collection
    Bundle bundle = new Bundle();
    bundle.putString("sample", "this is the test commands");
    bundle.putString("sample1", "this is the test commands1");



3. Call the child Activity from mainactivity with the bundle
    startActivity(new Intent(this, ChildActivity.class).putExtras(bundle));
 
4. Get the Value from MainActivity in ChildActivity
     this.getIntent().getExtras().getString("sample")

5. Toast the Message
    Toast.makeText(this, this.getIntent().getExtras().getString("sample"),
            Toast.LENGTH_LONG).show();
    Toast.makeText(this, this.getIntent().getExtras().getString("sample1"),
        Toast.LENGTH_LONG).show();
 

 
 Full Source :MainActivity.java
 
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Bundle bundle = new Bundle();
        bundle.putString("sample", "this is the test commands");
        bundle.putString("sample1", "this is the test commands1");
        startActivity(new Intent(this, ChildActivity.class).putExtras(bundle));
    }
}

-------ChildActivity.java----------
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

public class ChildActivity extends Activity {
    /**
     * @see android.app.Activity#onCreate(Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(this, this.getIntent().getExtras().getString("sample"),
                Toast.LENGTH_LONG).show();
        Toast.makeText(this, this.getIntent().getExtras().getString("sample1"),
                Toast.LENGTH_LONG).show();
    }
}

Passing data or parameter to another Activity Android

In this blog we have discussed shared preference and bundle collection. We can pass the value from parent activity to child activity using the bundled collection and shared preference.
1. Shared Preference
2. Bundle Collection

Shared Preference
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). First we need to put our value in to the context. And the context object lets you retrieve SharedPreferences through the method Context.getSharedPreferences().

1. Make a Shared Preference Collection
2. Retrieve Shared Preference Collection

Make a Shared Preference Collection
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
    SharedPreferences.Editor prefsEditor = myPrefs.edit();
    prefsEditor.putString("sample", "this is test commands");
    prefsEditor.commit();

Retrieve Shared Preference Collection
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
    prefsEditor.getString("sample", "DEFAULT VALUE");


 1. Create a two Activity [MainActivity & ChildActivity]
 
Activity : 1 -  MainActivity
 public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }
}

 
 Activity : 2 - ChildActivity
 
public class ChildActivity extends Activity {
     /**
      * @see android.app.Activity#onCreate(Bundle)
      */
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         // TODO Put your code here
     }
 }

 

2.  Define Your Shared collection
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
        SharedPreferences.Editor prefsEditor = myPrefs.edit();
        prefsEditor.putString("sample", "this is test commands");
        prefsEditor.commit();   
   

3. Call the child Activity from mainactivity
   
startActivity(new Intent(this,ChildActivity.class));
 
4. Get the Value from MainActivity in ChildActivity
 
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);

5. Toast the Message
  
  Toast.makeText(this, myPrefs.getString("sample", "DEFAULT VALUE"), Toast.LENGTH_LONG).show();   
 
 
 Full Source :MainActivity.java
 
 import android.app.Activity;
 import android.content.Intent;
 import android.content.SharedPreferences;
 import android.os.Bundle;
 
 public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
         SharedPreferences.Editor prefsEditor = myPrefs.edit();
         prefsEditor.putString("sample", "this is test commands");
         prefsEditor.commit();       
         startActivity(new Intent(this,ChildActivity.class));
     }
}

-------ChildActivity.java----------
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

public class ChildActivity extends Activity {
    /**
     * @see android.app.Activity#onCreate(Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
        Toast.makeText(this, myPrefs.getString("sample", "DEFAULT VALUE"), Toast.LENGTH_LONG).show();       
    }
}