New Year’s Resolution

2012 is coming to an end and it’s been an interesting year for me. I spent most of the time in California where I’ve been working for SAP Labs in Palo Alto. I discovered a great culture, made awesome new friends, and learned quite a few things about myself. Recapitulating the past 12 months, I’ve come up with a few habits that I think would be worth hanging on to in 2013.

Blogging

This year, I haven’t been very active when it comes to blogging. Although I’ve experienced so many new technologies/languages/people, I kept everything I learned from that to myself. As a software engineer, I gain most of my knowledge by reading stuff on the internet, mostly blog posts or articles in online magazines. Hacker News is my daily news paper – I read it every morning to know what’s going on in the tech world. It provides me with countless interesting blog posts where people share their experiences with the world, and I feel a little guilty for not giving anything back to the community. Every problem I solve, every neat little library I discover, every Idea I come up with is worth sharing. For now, one blog post a month will be my goal for next year.

Meditation

In the beginning of 2012, I moved in with a couple of friends that I made in California. Shortly after that, I rushed into a relationship with a friend of one of my roommates, which didn’t work out that well. During that time, a side of me surfaced that I never even knew existed. I went through a time of deep depression, which affected most aspects of my personal life. I said horrible things to people I care about and freaked out about the smallest issues. After a lot of thinking, talking (thank you everyone who had to listen to my emotional bullshit) and overreacting, I finally found something that would help me pulling myself together: Meditation. I know, it sounds strange at first, but the more you read about it, the more you realize that meditation is something anyone can (and should) do. 8 Minute Meditation helped me understanding what Meditation is all about: A quiet mind. It is amazing how just 10 minutes of meditation everyday can have such a big impact on your personality. My ability to focus, the way I treated my friends, in general everything about myself improved over time. Small things that made me angry or sad before didn’t affect me at all anymore – and that’s just the tip of the iceberg. I can highly recommend everyone to try it. Don’t know how to start? There are tons of great blog posts on the internet that talk about the benefits of meditation, read about it, try it out, it will change your life. Next year, I will try to be more consistent about it. 10 minutes daily and one longer session at least once a week are definitely doable and already enough to keep up a healthy level of mindfulness.

Travelling

During my time in California, I had the time and the financial resources to travel a lot. Never before have I seen so many different places in such a short amount of time. Not only did I have a lot of fun, but I also learned a lot about the places I’ve been to and met many interesting people from all over the world. Now that I’m back in Berlin, everything is fairly close by compared to America. Most major cities are reachable by train or car, and if I stay at a hostel, I can afford a couple of trips a year – even as a student. Although only one trip (to Warsaw, Poland) is planned so far, I hope to see many more places around Europe. Possible destinations are for example Bruge, London, Hamburg, Munich, Madrid, Paris, or Barcelona. I’d also love to do a backpacking trip through Norway. I’ve been there a couple of times before, but I never got to experience the true beauty of its wilderness.

Besides that

Despite those three main points on my agenda, I really want to find more ways to meet a lot of new people, especially international people. Thinking back, I have to say that socializing was the catalyst to all those changes in my life back in 2012. It is incredible how much you can learn from just talking to strangers. Besides the fact that it is always interesting, you get the chance to exchange ideas, get job offers, visit places you’ve never even heard of, or find new friends. For example, attending meetups is the perfect opportunity. You get together with people that you have similar interests with, listen to interesting talks, and most times you even get free food and drinks :). If you’re travelling, stay at a hostel! There is no easier way to meet awesome people than just having a beer in a hostel’s community area. Everyone is in the same situation – they’re new in town and looking for cool things to do!

Of course it is always easy to talk about new year’s resolutions (“I’m totally gonna quit smoking”) and I’m probably not going to show as much power of endurance as I’d like to, but I think even if I just manage to achieve half of what I just wrote by the end of 2013, my life will be going into the right direction.

That said, good luck everyone with your own new years resolutions. Happy 2013!

Persistent Model Framework for Android

A few months ago, a fellow student of mine came back from SAP in South Africa and told me about his new Android project: Androrm, which is a persistent relational data mapper especially for Android. Since I really hate writing ContentProviders and SQL queries, I gave it a try – and as luck would have it, I’m now using it in two of my projects!

Let me just give you a quick overview on what Androrm is about and how easy it is to define your data model with it. Basically it works like this:

1. Defining models

Let’s take two simple models: We have books and authors. All you have to do is extending the Model class and defining your fields:

Note: The source code was taken from the Android documentation and modified by me.

public class Book extends Model {
     
    // fields visibility is set to protected,
    // so the Model class can access it
    protected CharField mTitle;
     
    // zero-argument constructor, that can be called 
    // by androrm, to gather field information
    public Book() {
        super();
         
        // set up field with maxLength parameter
        mTitle = new CharField(80);
    }

    public String getTitle() {
        return mTitle.get();
    }
     
}

public class Author extends Model {
     
    protected CharField mName;
     
    public Author() {
        super();
         
        mName = new CharField(80);
    }

    public String getName() {
         return mName.get();
    }

    public void setName(String name) {
         mName.set(name);
    }
     
}

As you can see, there is a DataField type for each basic data type in java. Use them to define your model’s fields. They have set() and get() methods so you can easily set and get your values.

2. Creating a database

Once your models are defined, call this code in your onCreate() method of your app’s start activity to initialize the Androrm database and register your models:

List<Class<? extends Model>> models = new ArrayList<Class<? extends Model>>(); 
models.add(Author.class);                                                     
models.add(Book.class);                                                     
                                                                               
DatabaseAdapter.setDatabaseName("a_database_name");                                      
DatabaseAdapter adapter = new DatabaseAdapter(getApplicationContext());        
adapter.setModels(models);                                                     

In a next step, we want our books to be connected to their authors:

3. Creating relations

For relations, there is a special DataField called ForeignKeyField. It lets you extend your models with new classes, if basic data types are not enough. You just need a few lines of code:

public class Book extends Model {
     
    // fields visibility is set to protected,
    // so the Model class can access it
    protected CharField mTitle;
     
    // Link the Author model to the Book model.
    protected ForeignKeyField<Author> mAuthor;
     
    // zero-argument constructor, that can be called 
    // by androrm, to gather field information
    public Book() {
        super();
         
        // set up field with maxLength parameter
        mTitle = new CharField(80);
         
        // initialize the foreign key relation
        mAuthor = new ForeignKeyField<Author>(Author.class);
    }

    public String getTitle() {
        return mTitle.get();
    }

   public void setAuthor(Author author) {
        mAuthor.set(author);
   }
     
}

4. Insert your data

This is the part which amazed me the most when I first saw it. You just create your objects – business as usual – and then the magic happens:

// In your activity

Author author = new Author();
author.setName("My Author");
author.save(this);

Book book = new Book();
book.setName("Book name");
book.setAuthor(author);
book.save(this);

That’s it! You just create an instance of your class, do whatever you like and call save() to persist it. No SQL, no complicated ContentProviders. Of course, you can do a lot more with Androrm like querying your data and defining more complex relationships between your models. This was just a quick overview – for more details, please have a look at the documentation.

Androrm is still in an early stage, but – as far as I can tell – it works pretty stable! It is open source and hosted on GitHub, so feel free to contribute or file bugs!
If you find any related projects, please comment on this post!

That’s it for now, thanks for reading!

Dropbox SDK for Android

Last night I had a great idea for an app, which should be pretty easy to implement, I thought. I needed to use the Dropbox API for that and so I went to their website and found out that they have an own Android SDK. I could not find any instructions on how to use it and so I tried to find out by myself and downloaded that package. Next thing I tried was importing it to Eclipse, and that’s where the trouble took its course…

What went wrong?

First thing I noticed: The package didn’t contain any Eclipse project file. So I created a new Android Project in Eclipse and imported their source code – Build Error. I found out that I had to add the .jar files included in the package to my project’s Java build path. Bingo! It compiled and started the Demo application.

Cool! I could sign in and out. Now I just had to reference it as an Android Library and use it in my own project, right? The answer is no. Despite the .jar for the Dropbox Java API implementation, the “SDK” includes only two files: DropboxSample.java (the Activity) and LoginAsyncTask.java
. The second one handles all the login stuff and would be very handy when writing an app which should be connected to Dropbox, but it is so tightly coupled to the sample Activity, that it’s impossible to reuse it anywhere else. That made me pretty angry and so I decided to refactor the SDK.

Refactoring an SDK

I have used a couple of SDKs before and what I wanted to have was this:

  • An isolated Android Library Project containing only SDK classes
  • A project containing the sample application, which references the SDK project
  • A decoupled LoginAsyncTask.java
  • A small set of helper classes providing the easiest way to use the SDK

Long story short – The result is a Github project containing two projects: One SDK project, which is an Android Library, and a Sample Application. As I said before, I decoupled the LoginAsyncTask.java and made the SDK easier to use. I added a Dropbox.java class, which encapsulates the login procedure, and a LoginListener class as a simple callback. Here are some code snippets on how to use it in your Activity:

Creating the Dropbox object and checking existing logins:

final static private String CONSUMER_KEY = "PUT_YOUR_CONSUMER_KEY_HERE";
final static private String CONSUMER_SECRET = "PUT_YOUR_CONSUMER_SECRET_HERE";

// ... //

mDropbox = new Dropbox(getBaseContext(), CONSUMER_KEY, CONSUMER_SECRET);
if (mDropbox.authenticate()) {
        	// We can query the account info already, since we have stored 
        	// credentials
        	getAccountInfo();
} 

Handling the login callback:

    // Notifies our Activity when a login process succeeded or failed.     
    DropboxLoginListener mLoginListener = new DropboxLoginListener() {

		@Override
		public void loginFailed(String message) {			
			showToast("Login failed: "+message);
			setLoggedIn(false);
		}

		@Override
		public void loginSuccessfull() {
			showToast("Logged in!");
			setLoggedIn(true);		
			displayAccountInfo(mDropbox.accountInfo());
		}    	
    };

Logging in:

 private void getAccountInfo() {
    	
    	if (mDropbox.isAuthenticated()) {
		// Access credentials are already stored, just login
		mDropbox.login(mLoginListener);	            		
    	} else {
    		// Code for getting email and password goes here //

	        mDropbox.login(mLoginListener, email, password);	        
    	}
    }

For more details, just have a look at the Sample Application! If you have any feedback, feel free to comment.

Thanks so far

Android UI pattern implementations

Most Android users may have recognized more and more common UI elements in Android applications these days. Widgets like ActionBar and QuickActions are a great approach to standardize the way Android applications are used. Google posted some design proposals and took the Twitter for Android app as a great example for Android design patterns. A more precise definition for these and more patterns can be found at androidpatterns.com.
Of course, I immediately needed to have some of these in my own applications. So I started looking for Google’s implementation examples or developer documentation – nothing! Not even a code snippet. Fortunately, I was not the only one with that problem. I found some pretty good implementations for ActionBar and QuickActions, but I was looking for a more “integrated” solution, so I continued my research. Hours of googling later, I found a video from a talk at Google I/O 2010, which pointed me at the Google I/O app, which seems to be a good reference. But I wanted a library, not an example implementation and so I kept on searching. Finally, I found this awesome project, which perfectly fits my needs: Greendroid!

Greendroid

… is the most complete library for android UI patterns I found by now. Just load the Greendroid project into Eclipse, add it as a library to your project and you’re ready to go! To give you an example, creating an ActionBar and filling it with items is as easy as this:

1. Put this into your XML layout:

<greendroid.widget.ActionBar
 	android:id="@+id/MyActionBar" 
	android:layout_height="@dimen/gd_action_bar_height"
	android:layout_width="fill_parent" />

2. Fill your ActionBar with items and a title:

@Override
	public void fillActionBar(final ActionBar mActionBar) {
		mActionBar.addItem(Type.Compose);
		mActionBar.addItem(Type.Refresh);
		mActionBar.addItem(Type.Locate);
		mActionBar.setTitle("My ActionBar");
		mActionBar.setOnActionBarListener(new OnActionBarListener() {

			@Override
			public void onActionBarItemClicked(int position) {
				switch(position) {
				case 0:
					// Compose action
					break;
				case 1:
					// Refresh action
					LoaderActionBarItem item = (LoaderActionBarItem) mActionBar.getItem(position);
					// Turn the item into a progress indicator
					item.setLoading(true);
					break;
				case 2:
					// Map action
					break;
 				default:
 					// Action for home button
					break;
 				}
 			}
	 });

I recommend you to take a look at their example application (also included in the repository) to see what else you can do with Greendroid. There isn’t really a documentation, but the example application is pretty much everything you need to understand how Greendroid should be used.

I hope we’ll see more applications use the UI patterns in the future to give the Android application landscape a more consistent look.
Have fun!