Source code snippets (examples)

This is a list of Alvin Alexander's source code snippets (simple source code examples).

How to get the Android ActionBar Back/Up button to work like the Android back button

As a quick note, I was just in a situation where I wanted to get my ActionBar’s Back/Up button to work just like the Android back button. To get it to work like that, I used this Java code in my Fragment class:

 * react to the user tapping the back/up icon in the action bar
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
            // this takes the user 'back', as if they pressed the left-facing triangle icon on the main android toolbar.
            // if this doesn't work as desired, another possibility is to call `finish()` here.
            return true;
            return super.onOptionsItemSelected(item);

A key to that code is calling this method in the switch statement:


As noted, calling the finish() method may have the same effect -- and may, in fact, be a better approach in some situations -- but I haven’t tested that yet.

In summary, if you wanted to see how to make your ActionBar Back/Up button work just like the Android “back” button -- the triangle that points to the left -- I hope this source code is helpful.

Android: An example onCreateView method in a Fragment class

This Java code shows how to implement a couple of things in an onCreateView method inside a Fragment class:

public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_single_image, parent, false);
    ImageView imageView = (ImageView)rootView.findViewById(;
    return rootView;

What I’m doing here is:

  1. Enabling the Android Back/Up button in the ActionBar
  2. Getting a reference to the “root view” in my layout file
  3. Getting a reference to an ImageView that I know is in that layout file
  4. Setting a bitmap image on that ImageView

If you wanted to see how to do any of these things in a fragment’s onCreateView method, I hope this source code is helpful.

Android: Getting references to Drawable images

As two quick Android “drawable” notes, if you want to convert a drawable resource into a Drawable reference, you can use code like this:

Drawable myImage = getResources().getDrawable(R.drawable.myImage);

Second, if you want to display a drawable image resource on an ImageView, you can use code like this:


(I share little code snippets out here like this because I can never remember how to do some of these things.)

Android: How to load an image from a file and set on an ImageView

If you’re working with an Android application, this source code seems to work to load an image from a file:

Bitmap bitmap = BitmapFactory.decodeFile(pathToPicture);

The Bitmap and BitmapFactory classes are located in the package:


Assuming that your pathToPicture is correct, you can then add this bitmap image to an ImageView like this:

ImageView imageView = (ImageView) getActivity().findViewById(;

As shown, the setImageBitmap method is another key to this solution.

I’m currently using this approach to let users choose an image from their image/photo gallery, which is where I get the file path.

Android setDisplayHomeAsUpEnabled not needed to enable Up/Home/Back ActionBar button

When you want to provide Up/Back/Home navigation in an Android sub-activity, this Java code doesn’t seem to be needed:


The “Add Up Action” docs on this page state that is needed, but as of some (unknown) Android version it is not needed. All you need to do is specify the “Up/Parent” activity in your AndroidManifest.xml file, like this:

    android:parentActivityName=".QuotesListActivity" />

I’m not sure about Android version specifics, but I’m developing my app with a minSdkVersion of 16 and my Up/Back buttons work fine without the Java code.

Android centering example: ImageButton in a Toolbar

As a quick Android “centering” tip, I found that by adding this snippet to the ImageButton below:


I was able to get the ImageButton to center itself in the Toolbar. Here’s the layout code for the Toolbar and the ImageButton:




I don’t think I needed this line in the ImageButton:


but I could be wrong. Once I got this Toolbar floated down to the bottom of the display I decided I didn’t like the look of it after all, so I deleted this code before getting a screenshot. But I do know that the android:layout_gravity setting was the one that centered my ImageButton. (Also, a lot of that other layout configuration code is unnecessary. I was experimenting with several different things when I was working on this button centering problem.)

Android: How to add a click listener to a Button (action listener)

As another quick Android example, this Java source code shows how to add a “click listener” to an Android Button:

public class MyActivity extends Activity {

     protected void onCreate(Bundle icicle) {

         final Button button = (Button) findViewById(;
         button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 // your handler code here


Important things to know are a) you need to add a listener to the Button, b) the listener you need is called an OnClickListener (not an ActionListener or ButtonClickListener, etc.), c) you add the listener with the setOnClickListener method, and d) that you need to implement the onClick method.

If you needed to see how to add a listener to an Android Button, I hope this example code is helpful.

How to set an image on an Android ImageButton

To set an image on an Android ImageButton, you basically just need to put your image in the “res/drawable” directories, and then add this tag to your ImageButton XML definition:


That assumes the image file is named my_image.png.

Here’s a full ImageButton example to demonstrate this:


There is even more you can do with images on ImageButton’s. See the Android ImageButton docs for more information.

Android - How to access a String resource from Java code

To access a String resource that you’ve defined in an XML file from your Android/Java code, use the Android getString method, like this:

String prefsKeyTimeBetweenNotifications = getString(R.string.prefsKeyTimeBetweenNotifications);

In this example I’ve defined prefsKeyTimeBetweenNotifications as a string resource key in a res/values/strings.xml file, like this:

<?xml version="1.0" encoding="utf-8"?>

    <string name="prefsKeyTimeBetweenNotifications">timeBetweenNotifications</string>


If you don’t use the getString method you’ll end up retrieving a long value.

Android: SQLite: SQLiteOpenHelper/SQLiteDatabase insert method doesn't throw exception

Android SQLite FAQ: I’m trying to catch an exception when my SQLiteOpenHelper/SQLiteDatabase insert method fails (typically because of a unique/duplicate constraint); why can’t I catch the exception?

Solution: The SQLiteOpenHelper insert method (SQLiteDatabase, actually) doesn’t throw an exception. The insert method returns the ID of the newly inserted row if it succeeds, or -1 if it fails. If you want an exception when the insert method fails, use the insertOrThrow method instead, as shown in this Java code:

 * @throws java.sql.SQLException if the insert fails (typically because of a
 * "duplicate/unique" constraint.
public long insert(String quote) {
    ContentValues cv = new ContentValues();
    cv.put(COL_QUOTES_QUOTE, quote);
    return getWritableDatabase().insertOrThrow(TABLE_QUOTES, null, cv);

The signature for insertOrThrow is the same as the insert method, so this is a simple change, assuming you want an exception. As my documentation shows, the insertOrThrow method throws a standard Java SQLException if the SQL INSERT fails.

For more information, see the SQLiteDatabase javadoc.