Developer How-To

Examples and Tips for Android Development

Resources NotFoundException

The below Resources$NotFoundException log results from user error and is easily fixed.

Uncaught handler: thread main exiting due to uncaught exception
android.content.res.Resources$NotFoundException: String resource ID #0x1
at android.content.res.Resources.getText(Resources.java:205)
at android.widget.TextView.setText(TextView.java:2809)

I get this error when I am trying to set a View’s text using an integer value like:

view.setText(iSomeInteger) // This is incorrect !

Instead, to set the text of a view using an integer, you need to do:

view.setText(Integer.toString(iSomeInteger)) // setText with an int

The problem is that setText(int) is reserved for string resource ids, like:

view.setText(R.string.someStringId) // setText with a string resource id

The last part of this puzzle is when you want to concatenate a string resource with other text, you need to use getString(int). Otherwise you will end up with the string resource id (not the string itself) as part of your new text:

// concatenate a string with a string resource
view.setText("Some Text: " + getString(R.string.someStringId))

Click & Long-Press Event Listeners in a ListActivity

Listening for and handling click and long-press (a.k.a. long-click) events in an Android ListActivity is a a simple matter of defining setOnItemClickListener and setOnItemLongClickListener delegate methods in the ListView.

For individual list items to be clickable, you will want to let the ListActivity’s ListView handle the onItemClick and onItemLongClick events that Android fires when a user interacts with your application.

First, get your ListView from your ListActivity. The ListView will handle the click and long press Android events for your ListActivity.

ListView lv = getListView();

Next, provide a method to handle the click when users press and release a list item in the ListView.

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
        onListItemClick(v,pos,id);
    }
});

Define your method to handle the onItemClick. This accepts a View which is the individual UI element that was clicked. This View corresponds to your layout that you set in your Adapter for your ListActivity. The position corresponds to which list item was clicked in the ListView (starting with a 1-index).

protected void onListItemClick(View v, int pos, long id) {
    Log.i(TAG, "onListItemClick id=" + id);
}

Handling long press events is essentially the same as handling clicks except that you return a boolean which specifies whether Android should continue to propagate the click event.

lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
        return onLongListItemClick(v,pos,id);
    }
});

If your long-click method returns true then you are telling Android that you handled the event and nobody else should know about the long-press. If your method returns false, Android will still call other handlers such as your onItemClick handler. Long-press events in Android typically do not perform the same action as a regular press, so it may be best to return true to stop event propagation.

protected boolean onLongListItemClick(View v, int pos, long id) {
    Log.i(TAG, "onLongListItemClick id=" + id);
    return true;
}

Outside This Scope

This is just the beginning for handling clicks within Android ListActivities and ListViews. Below are topics not covered within the scope of this post.

  • Performing actions within your onListItemClick such as starting a new Activity and sending information about the item that was clicked
  • Creating a custom context menu during your onLongListItemClick method
  • In Android SDK 1.6+, there is an easier way to attach click listeners to Views
  • You can set individual click listeners for Views within each list item to perform different actions depending on where you click within the list item

Resources

I did not come up with this out of my own brainz. I have only compiled and annotated information I have found online. The following resources may provide additional, useful information.

Vibration Examples for Android Phone Development

Making Android phones vibrate is a good way to provide haptic feedback to users or to interact with users even when phone volume is low. This can ensure a better user experience and therefore increase the perceived integrity of your Android application.

The Vibrator Documentation describes the interface for making an Android phone vibrate. With this interface, you can cause an Android phone to vibrate in one of the following ways:

  1. Vibrate for a given length of time
  2. Vibrate in a given pattern
  3. Vibrate repeatedly until cancelled

Below are examples of these three vibrating methods.

IMPORTANT: First, Grant Vibration Permissions

Before you start adding the code necessary to cause your application to vibrate, you must first notify Android that your application expects to have permission to use the Vibrator. If you do not do this, you will receive a Force Close. Nobody likes encountering a Force Close; Do not forget this important first step!

Add the uses-permission line to your Manifest.xml file, outside of the block.

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="...">
	<uses-permission android:name="android.permission.VIBRATE"/>
	<application android:label="...">
		...
	</application>
</manifest>

Example: Vibrate for a Given Length of Time

This example is useful when a user touches your application and you would like to provide haptic feedback. This is the simplest method of vibration. I like 50 milliseconds as a good single-touch-feedback vibrate. You can experiment with different lengths (on your physical phone) to decide how long to make your vibration.

CUIDADO: This code must be called with a reference to a Context

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Vibrate for 300 milliseconds
v.vibrate(300);

Example: Vibrate in a Given Pattern

This method of vibration is useful when you need to provide a user with a one-time notification, such as receiving a text message. In this example, I have created a one-time vibration notification in the Morse Code SOS pattern.

CUIDADO: This code must be called with a reference to a Context

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// This example will cause the phone to vibrate "SOS" in Morse Code
// In Morse Code, "s" = "dot-dot-dot", "o" = "dash-dash-dash"
// There are pauses to separate dots/dashes, letters, and words
// The following numbers represent millisecond lengths
int dot = 200;		// Length of a Morse Code "dot" in milliseconds
int dash = 500;		// Length of a Morse Code "dash" in milliseconds
int short_gap = 200;	// Length of Gap Between dots/dashes
int medium_gap = 500;	// Length of Gap Between Letters
int long_gap = 1000;	// Length of Gap Between Words
long[] pattern = {
	0, 	// Start immediately
	dot, short_gap, dot, short_gap, dot, 	// s
	medium_gap,
	dash, short_gap, dash, short_gap, dash, // o
	medium_gap,
	dot, short_gap, dot, short_gap, dot, 	// s
	long_gap
};

// Only perform this pattern one time (-1 means "do not repeat")
v.vibrate(pattern, -1);

Example: Vibrate Repeatedly Until Cancelled

This method of vibration is useful when you need to notify the user of something that requires more immediate action, such as an incoming phone call. You can repeat a given pattern until the Vibrator is cancelled, either by the system or manually by your Android application.

CUIDADO: The below example will cease vibrating when the screen times out.
CUIDADO: This code must be called with a reference to a Context

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Start immediately
// Vibrate for 200 milliseconds
// Sleep for 500 milliseconds
long[] pattern = { 0, 200, 500 };

// The "0" means to repeat the pattern starting at the beginning
// CUIDADO: If you start at the wrong index (e.g., 1) then your pattern will be off --
// You will vibrate for your pause times and pause for your vibrate times !
v.vibrate(pattern, 0);

In another part of your code, you can handle turning off the vibrator as shown below:

// Stop the Vibrator in the middle of whatever it is doing
// CUIDADO: Do *not* do this immediately after calling .vibrate().
// Otherwise, it may not have time to even begin vibrating!
v.cancel();

Notes

This article only covers a subset of issues related to Vibration on the Android platform but it should provide a good starting point. Below are a few things I have noticed but did not cover in this write-up. I would appreciate comments about these, if you have any:

  • From what I have read, there is unfortunately no way of changing the vibration intensity.
  • I did not research or discuss how to make phone vibrate despite the screen timeout.
  • I have not seen the Vibrator log its activities in LogCat which makes it difficult to tweak vibration.
  • As a result, I test vibration directly on my phone which requires exporting and installing my application on my physical phone. Tedious at best.

Reference Material