published: January 1st, 2011

Happy New Years, Simple pattern for opening an Android Activity

Another New Year and like many other bloggers I’m thinking about resolutions of writing on my blog more often.  Actually, my resolutions are a little grander then just this blog, but I’m still ironing them out.

So instead of going into my life/work goals of 2011 I’d rather share a code snippet/Android pattern I’ve been using quite a bit lately.  It grew from working with other Android developers and wanting to specify a mini API for opening an Activity.  Many Activities pass data when they open another Android Activity; using Intents, name/value pairs can be defined for the data elements.  One problem is though, you must use code inspection to determine what data is passed in, and what the format it is.  What I’ve started to do is use a static method in the Activity as a means of starting it.  Here’s a simple code snippet to demonstrate what I’m talking about

public class ActivityOne extends Activity
{
    private static final String VALUE1 = "value1_param";
    private static final String VALUE2 = "value2_param";

    public static void startMe( Context ctx, int val1, String val2 )
    {
        Intent intent = new Intent( ctx, ActivityOne.class );
        intent.putExtra( VALUE1, val1 );
        intent.putExtra( VALUE2, val2 );
        ctx.startActivity( intent );
    }

    private int _value1;
    private String _value2;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_one );

        Bundle extras = getIntent().getExtras();
        if ( extras != null )
        {
            _value1 = extras.getInt( VALUE1 );
            _value2 = extras.getString( VALUE2 );
        }
    }
}

This way ActivityOne can be started from another Android Activity using the following call,

ActivityOne.startMe( this, 123, "abc" );

This places the actual means of defining the Intent for ActivityOne in one place, and if this contract is changed, ie adding another variable or changing types, it can be changed in the method signature of startMe and all the places this is called will fall out using a coding tool like Eclipse.

Hope this little snippet can give you some ways on writing cleaner Android code, Happy New Years!

published: July 22nd, 2010

Go home feature with FLAG_ACTIVITY_CLEAR_TOP

Here’s a little snippet I wrote up the other day to support a Go Home feature for the app I’ve been helping with.  It sets the FLAG_ACTIVITY_CLEAR_TOP flag on the Intent along with the HomeActivity.  This flag, according to the Android docs, launches a new instance of the activity if it isn’t currently running, and closes all the activities on top of it.  So if there are any activities on top of HomeActivity they are cleared and HomeActivity is displayed to the user.  I also added a check to determine if the supplied Context is already the HomeActivity, and if so, ignore the call.

public static void goHome( Context ctx )
{
    if ( ! ( ctx instanceof HomeActivity ) )
    {
        Intent intent = new Intent( ctx, HomeActivity.class );
        intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
        ctx.startActivity( intent );
    }
}

published: July 1st, 2010

Using layout include tag with Location proof of concept

I’ve been prototyping some code using the location api and not only have I learned some new things about this but also worked in the layout ‘include’ tag to minimize the amount of redundency in the layout file, and the Android Java code.  Include allows you to include one layout file in another, there’s an article about it on the Android dev site.  One minor speed bump I ran into was that I didn’t see an immediate way to access the resuseable portion of the layout file via a findById call.  After a little hacking around, the answer was pretty easy.

(more…)

published: June 28th, 2010

Multiple calls to addPreferencesFromResource from PreferenceActivity

Just found this out, maybe it’s obvious, but something new for me.  When you create a PreferenceActivity you call addPreferencesFromResource with the name of the resource file defining your preferences to display in the activity.  You can make multiple calls to the addPreferencesFromResource method; this gives your Android application a way to show preferences that may be specific to that component of your app by breaking your preferences up into multiple resource files and aggregating them as needed.

I’d think if this functionality was used you’d want one screen that would aggregate all the preferences (maybe a Dashboard or Home screen), but individual activities could call other preferences activities that would further filter the preferences specific to that activity.

Just another option that you may find useful in your app….cheers!

published: June 17th, 2010

Android Item Resource has a Name and Type

Here’s a handy trick to use instead of constants in your code.  It uses the Item resource tag to define application specific constants which are located in a resource XML file.

For example, given the following XML located in a file in the res/values directory

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <item name="host" type="setting">10.0.2.2</item>
 <item name="port" type="setting">3000</item>
</resources>

I can now use the following Java syntax within an Android Activity:

String host = getString( R.setting.host );
int port    = getResources().getInteger( R.setting.port );

This gives me a scheme to have a common place with ‘types’ to define constants. I’ve just barely started using it, but it seems like a nice clean way of handling these ‘magic’ values without using static final variables.

published: June 10th, 2010

ArrayAdapter and AlertDialog for single choice items

I thought this was pretty cool…I used the AlertDialog.Builder, an ArrayAdapter along with the View Holder Android UI pattern to build an AlertDialog containing a list of choices with images for each entry.

(more…)

published: June 5th, 2010

Cropping images from a png file in Android

So I’ve never tried to crop single images from a multi-image bitmap ( like these images ), but after some tweeking I ended up with the following code snippet, I’m sure it’s not the only way, but it seems to work out pretty well.

private Drawable getImg( int idx )
{
    InputStream is = getResources().openRawResource( R.raw.myicons );
    BitmapDrawable bm = new BitmapDrawable( is );
    try {
        is.close();
    } catch (IOException e) { /** noop, stream is closed **/ }
    BitmapDrawable img = new BitmapDrawable( Bitmap.createBitmap( bm.getBitmap(), 22 * idx, 0, 22, 22 ) );
    img.setBounds( 0, 0, 40, 40 );

    return img;
}

Of course, you’ll have to supply your own myicons.png in the /res/raw directory and a corresponding size (mine is 22).  You’ll also want to change the code so the BitmapDrawable “bm” is only loaded once, most likely in a constructor, then used multiple times from the above getImg method.

published: June 4th, 2010

setCompoundDrawable to add Drawables to TextView

Finally trying to get a couple new posts up, have a bunch of material just not a lot of free time to get ‘em posted.  Here’s a quick and easy one.

I was using the setCompoundDrawable method for a TextView to set an image to the left of some text, I was hoping it was going to be as easy as loading the drawable and calling

txtVw.setCompoundDrawables( img, null, null, null );

Unfortunately nothing showed up, and I had no internet connection at the time, so I was left to fumble around trying a bunch of different things…nothing worked.  Finally, after getting to work and looking at some existing code from a co-worker, I found out that using setBounds will define a bounding rectangle around the image.  So the final lines of code look like…

Drawable img = getContext().getResources().getDrawable( R.drawable.smiley );
img.setBounds( 0, 0, 60, 60 );
txtVw.setCompoundDrawables( img, null, null, null );

UPDATE: See comments to make this even easier, thanks Romain Guy and Nerdrow

published: February 25th, 2010

MediaDroid YouTube demo video

Well here’s my very first YouTube video…it’s a demo of MediaDroid. Certainly not perfect, but I think it gets the job done and I’m stick’n with it!

Here’s the link in case the embed doesn’t work

published: February 16th, 2010

MediaDroid 1.3.4 on Android Market

Just released a brand new version of MediaDroid.  Thanks to some reverse engineering of the Android Image Gallery, I’ve been able to greatly increase the performance and stability of the app.  Hopefully I’ll be able to get into the specific changes (for all the Android developers out there) in a later post when I get a little more time.  Also, improved the button icons thanks to my son’s (OK…they where mine first) Crayons (TM).

Already have plans for some more features (filtering the image buckets shown in the Image Gallery) and with this re-write out of the way I think I’ll be able to get the next version out sooner.

Cheers, and thanks for all the support from the current users of MediaDroid, it’s great to hear all your feedback…good and bad!!