Category Archives: Android/Java

Posts about Java and Android

Android on iPhone

Yes, you read the title correctly. Now it is possible to run Android on iPhone (and can have flash too 😉 )

Planentbeing from linux on iphone project has successfully ported Android to run on iPhone. You can see the following video where he demos dual booting iPhone with android.

Man, seriously this guy is a genius and I really adore his reverse engineering skills.

You can also download pre-built images and source and can try it out, if you have an old iPhone lying around.

Posted in Android/Java, Apple/Mac/iDevices | Tagged , | 5 Comments

Free online course on developing android applications using Java – Part 2

CreativeLive who conducted a free 6 weeks course on developing Android applications with Java are back again with a follow up course. The part 2 course is also a 6 weeks course (like part 1) and will be conducted by Tony Hillerson, who also conduced the first course.

In this course, a Twitter client would be created and will cover OAuth, access the Twitter APIs, and also how to post photos to Twitter amount other things.

The part 2 of this course is also free to watch live, like the first course. You can check out the schedule in the official page.

If you have attended the first course or if you are interested in Android, then do register for the course, at the official page and follow it up. 🙂

Posted in Android/Java | Tagged , , | 4 Comments

10 Open Source Android Apps which every Android developer must look into

I used to read code from popular open source projects to see how others implement certain functionalities and also to learn from them. (I am a firm believer of the fact that you have to read good code to write good code)

Recently I have been following up a couple of good open source Android apps and thought of listing them here so that it could be useful for others.

Update: I have updated this list with a new set of apps, which have come out recently. Check out them as well.

Sample Apps by Android Team

Could there be a better way to start without looking at the code of the developers who developed the framework? 😉 These are 15 different android sample apps created by the core developers of the Android framework. These include a couple of games, photostream, time display, home screen shortcuts etc.

url : http://code.google.com/p/apps-for-android/

Remote Droid

RemoteDroid is an android app which turns your phone into a wireless keyboard and mouse with touchpad, using your own wireless network. You can learn lot of things like connecting to a network, controlling user finger movement etc from its source.

url: http://code.google.com/p/remotedroid/

TorProxy and Shadow

TorProxy is an implementation of Tor for Android mobiles. Together with Shadow, it allows you to browse website anonymously from your mobile phone. You can learn about tunnelling socket connections, managing cookies etc by reading its source code.

url: http://www.cl.cam.ac.uk/research/dtg/code/svn/android-tor/ and http://www.cl.cam.ac.uk/research/dtg/android/tor/

Android SMSPopup

It is an Android app that intercepts incoming text messages and displays them in a popup window. Apart from being a time saver, this app also shows us how to interface with the built-in app that manages SMS.

url: http://code.google.com/p/android-smspopup/

Standup Timer

Standup Timer is an Android application that acts as a simple, stand-up meeting stop watch. It can be used to ensure your stand-up meeting finishes on time, and gives all the participants an equal share of time to state their progress. You can learn how to use the timer functionality by reading the source code. Also this apps has clear distinction between view, model etc and has lot of util methods which we can reuse in our app.

url: http://github.com/jwood/standup-timer

Foursquare

It is a four square client for android. This app is basically divided into two components; Reading the source code you can find out how to make

url: http://code.google.com/p/foursquared/

Pedometer

The pedometer app tries to take the number of steps you take every day. Even though the count is not accurate, you can learn different things like interacting with accelerometer, doing voice updates, running background services etc by reading its source code.

url: http://code.google.com/p/pedometer/

opensudoku-android

OpenSudoku is a simple open source sudoku game. You can learn how to display things in a grid in your view and also how to interact with a website by reading its source code.

url: http://code.google.com/p/opensudoku-android/

ConnectBot

ConnectBot is a Secure Shell client for the Android platform. There are lot of good things about this app’s source code. Check it out for yourself 🙂

http://code.google.com/p/connectbot/

WordPress for Android

How can you expect a list of apps from me without mentioning WordPress 😉 This android app is from the official WordPress development team. You can learn how to make XMLRPC calls (in addition to other cool things) by reading its source code.

url: http://android.svn.wordpress.org/trunk/

If you got any good open source android apps from which we can learn something, then do leave a comment and I will add them up here, till then happy reading 🙂

Update: I have updated this list with a new set of apps, which have come out recently. Check out them as well.

Posted in Android/Java | Tagged , , | 144 Comments

Developing Android applications in Java – Session 3 – My notes

This week in the Android course, Tony taught about the storing and retrieving information from database. Android has a bundled SQLite database and your app can store and retrieve information by creating a new database. The database that is created by an application is available only to that application and no other application can access it.

SQLiteOpenHelper

Android SDK provides a class called SQLiteOpenHelper which can be used for interfacing with this SQLite database that is associated with your application.

SQLiteOpenHelper has two methods which can be used for creating/updating the database. They are the following.

onCreate

The onCreate() method gets called when the app gets installed for the first time. The SQL code to create the database should go in this method. In addition to the SQL code we should also specify a version number for the database which will be used subsequently during upgrades.

onUpgrade

The onUpgrade() method gets called when the app is upgraded or if the version number specified in the app is greater than the one which is present in the database. Typically this function contains Alter table SQL code which will be used to upgrade the database.

In addition to the above two methods, the SQLiteOpenHelper also has other methods which can be used to access the database. One such method is getWritableDatabase()

getWritableDatabase

The getWritableDatabase() method will return a SQLiteDatabase object which has reference to the database. You can read more about this method from android documentation.

In addition to these methods, the SQLiteOpenHelper class other methods but the above there are the notable ones. You can read more about the SQLiteOpenHelper class from the android documentation.

Selecting data from the database

To selected data from the database, we have to call the query() method on the SQLiteDatabase object which is returned by the getWritableDatabase() method above.

The query() method returns an object of type Cursor, which can be iterated over to retrieve the resultset. The following code snippet explains the query() method.

private void loadTasks() {
	currentTasks = new ArrayList<Task>();
	Cursor tasksCursor = database.query(TASKS_TABLE,
			new String[] {TASK_ID, TASK_NAME, TASK_COMPLETE},
			null, null, null, null, String.format("%s,%s", TASK_COMPLETE, TASK_NAME));

	tasksCursor.moveToFirst();
	Task t;
	if (! tasksCursor.isAfterLast()) {
		do {
			int id = tasksCursor.getInt(0);
			String name = tasksCursor.getString(1);
			String boolValue = tasksCursor.getString(2);
			boolean complete = Boolean.parseBoolean(boolValue);
			t = new Task(name);
			t.setId(id);
			t.setComplete(complete);
			currentTasks.add(t);
		} while(tasksCursor.moveToNext());
	}
}

Inserting data into the database

In order to insert the data into the database we have to call the insert() method of the SQLiteDatabase. The data that needs to be inserted should be added to a ContextValues object and then passed to the insert() method. The ContextValues object is like a HashMap which contains the key and the value for each column of the row that will be inserted.

The insert() method returns the id of the row that was inserted. The following code snippet explains the insert() method.

public void addTask(Task t) {
	ContentValues values = new ContentValues();
	values.put(TASK_NAME, t.getName());
	values.put(TASK_COMPLETE, Boolean.toString(t.isComplete()));

	t.setId(database.insert(TASKS_TABLE, null, values));
	currentTasks.add(t);
}

Updating data in the database

To update data in the database we have to call the update() method of the SQLiteDatabase object. Like the insert() method, the data that needs to be updated should be passed in a ContextValues object.

The following code snippet explains the update() method.

public void saveTask(Task t) {

	ContentValues values = new ContentValues();
	values.put(TASK_NAME, t.getName());
	values.put(TASK_COMPLETE, Boolean.toString(t.isComplete()));

	long id = t.getId();
	String where = String.format("%s = %d", TASK_ID, id);
	database.update(TASKS_TABLE, values, where, null);
}

Deleting data from the database

To delete data from the database we have to call (guess what 😉 ) the delete() method of the SQLiteDatabase objet. The delete() method takes the where condition based on which the rows will be deleted.

public void deleteTasks(Long[] ids) {
	StringBuffer idList = new StringBuffer();
	for (int i =0; i< ids.length; i++) {
		idList.append(ids[i]);
		if (i < ids.length -1 ) {
			idList.append(",");
		}
	}

	String where = String.format("%s in (%s)", TASK_ID, idList);
	database.delete(TASKS_TABLE, where, null);
}

You can read more about this method from android documentation.

Demo App Sourcecode

The demo TaskManager app that we have been using in the previous classes was modified to store the tasks in the database. You can find the source code from my github page. I am also working in this week’s homework and will be posting the explanation and source code once I am done.

You can also subscribe to my blog’s RSS feed or follow me in Twitter to receive updates about my notes for the next sessions.

Posted in Android/Java | Tagged , , , , | 7 Comments

Using ArrayAdapter and ListView in Android Applications

This week’s homework in the android class was to create a simple ListView using ArrayAdapter instead of generic ListAdapter.

ArrayAdapter

ArrayAdapter is a special kind of ListAdapter which supplies data to ListView. You can refer to my notes for last week to know about ListView and ListAdapter. You can also read about ArrayAdapter in android documentation.

Adding views

First create an empty android project. Then edit the main.xml layout file to add a ListView. Then create another layout xml file which will contain the TextView (or any component) that will be displayed within the ListView.

Editing Activity

The next step is to change the generated activity class to extend from ListActivity. This is very important because only a ListActivity will be able to display the ListView.

Binding the adapter

The next step is to bind the ArrayAdapter to the ListActivity. We can do this by calling the setListAdapter() method.

To this method we have to pass an object of type ArrayAdapter. You can pass an object reference to this method or we can even create a new anonymous method like below.

We have to override the getView() method of the ArrayAdapter class to create the TextView (or any other component) which will be created for each list.

Finishing up

So that’s it, you are done. 🙂 All you have to do now is to save the project and run it in the emulator. If everything is done properly, then you can see the list of items displayed in the ListView like below.

android-listview

Source code

I have uploaded the entire project source code into github and you download it from there and verify it with your code.

Try to complete the homework, before the next session and do come back to view the notes and the homework for the next session too. 🙂

You can also subscribe to my blog’s RSS feed or follow me in Twitter to receive updates about my notes for the next sessions.

Posted in Android/Java | Tagged , , | 34 Comments

Developing Android applications in Java – Session 2 – My notes

Like last week, I attended the session on Developing Android applications in Java by Creative Techs and O’Reilly and here are my notes which I took during the session.

Replace TextView with ListView

In this week’s session, the demo app that was created last week was modified to use the ListView element instead of TextView.

The ListView provides a nice UI for displaying the list of tasks together with a checkbox to indicate whether they were complete or not.

Screenshot

You can see the new UI of the application in the following screenshots.

android-listview

ListView and ListAdapter

ListView is a control which can be used for creating list of scrollable items. The data to the ListView will be provided by ListAdapter.

You can think of ListView as the “view” component in a MVC framework and ListAdapter as the “model”

The class which is going to act as the ListAdapater should implement following methods

  • getCount()
  • getItem()
  • getItemId()
  • getView()

You can read more about ListView and ListAdapter from android documentation.

Adding ListView

To add ListView to any activity, we have to include the <ListView /> tag to the activity’s layout xml. In our sample app, the ListView tag is added to the main.xml file.

The Activity class that uses ListView should implement the ListActivity instead of plain Activity class. In our sample app, the ViewTasksActivity class is derived from the ListActivity class.

Magic ids

Android SDK provides some predefined ids which can be used some specific purposes. One such “magic id” is android:empty.

We can assign this to any element that we want to be displayed when the ListView is empty.

Homework

This week’s homework is to Build a simpler (but less flexible) way to load data into a list using an ArrayAdapter (instead of a BaseAdapter). I would be completing the homework and would be posting the explanation and the source code later this week. So stay tuned 🙂

Source code

I have uploaded source code for yesterday’s session in github and you can download it from there. I am also working in this week’s homework and will be posting the explanation and source code once I am done.

You can also subscribe to my blog’s RSS feed or follow me in Twitter to receive updates about my notes for the next sessions.

Posted in Android/Java | Tagged , , | 8 Comments

Using preference API in Android applications

This week’s homework in the android class was to persist the task information in the sample TaskManager application across program runs, which was created during the class.

Preference API

Android provides a preference API, using which we can store task information. The preference API is very simple to use and all we have to do is to get the instance to the preference object from the Application object and then call the getString() and putString() method.

Serializing ArrayList to string

The only tricky part of the home work is that, since the preference API supports only storing and retrieving of strings, we have to serialize and de-serialize the ArrayList object which has the list of tasks into string.

Instead of writing my own code to do this conversion, I used the code from the Apache Pig project. You can check out the class from the pig’s github page.

Storing the task

In the addTask() method of the TaskManagerApplication class, we have to get the instance of the shared preference and then store the serialized ArrayList using the putString() method.

	public void addTask(Task t) {
		assert(null != t);
		if (null == currentTasks) {
			currentTasks = new ArrayList<task>();
		}
		currentTasks.add(t);

		//save the task list to preference
		SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
		Editor editor = prefs.edit();
		try {
			editor.putString(TASKS, ObjectSerializer.serialize(currentTasks));
		} catch (IOException e) {
			e.printStackTrace();
		}
		editor.commit();
	}

Retrieving the task

Similarly we have to retrieve the list of tasks from the preference in the onCreate() method

	public void onCreate() {
		super.onCreate();
		if (null == currentTasks) {
			currentTasks = new ArrayList<task>();
		}

		//		load tasks from preference
		SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);

		try {
			currentTasks = (ArrayList<task>) ObjectSerializer.deserialize(prefs.getString(TASKS, ObjectSerializer.serialize(new ArrayList<task>())));
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

Finishing up

So that’s it, you are done. 🙂 All you have to do now is to save the project and run it in the emulator. If everything is done properly, the tasks that you enter will be saved even after you restart the app.

Source code

I have uploaded the entire project source code into github and you download it from there and verify it with your code.

Try to complete the homework, before the next session and do come back to view the notes and the homework for the next session too. 🙂

You can also subscribe to my blog’s RSS feed or follow me in Twitter to receive updates about my notes for the next sessions.

Posted in Android/Java | Tagged , , | 7 Comments

Developing Android applications in Java – Session 1 – My Notes

Like last week, I attended the session on Developing Android applications in Java by Creative Techs and O’Reilly and here are my notes which I took during the session.

Demo Application

In this week’s session, he created a sample task manager app which can be used for maintaining list of things to track. This app was created using Android 1.6 with Google API support. You can download the source code of this demo app below.

The sample app will have two activities. One will have a simple data entry form which can be used to add tasks and the other to view tasks which were entered. Check the screenshots below to see how the sample app looks like.

android-taskmanager-1 android-taskmanager-2

Layouts

Tony (the instructor) briefly explained about the different types of layouts and for the sample apps he used Relative Layout. You can read more about the relative layout from the android documentation.

The major pain point in using Relative layout is that, the controls should be specified in the order in which they are referenced and not in the order in which they will be displayed.

EditText control

EditText control is an editable control which can be used to get user input. It is similar to the HTML textbox or the Java Swing JTextField.

You can read more about EditText control from android documentation.

Sharing data between views

An application can have multiple activities (views) and to share data between these multiple activities, the android framework provides a class called Application. This Application class can be accessed from all the activities of the app by calling the getApplication() of the Activity class. Tony explained this about this class and also used it in the demo app to store and retrieve tasks from multiple activities.

You can find this class in the TaskManagerApplication.java in the sample app. You can download the source code of this demo app below.

Safe cancelling

Tony also explained about how to listen to text changes and make sure the user is not moving away from the activity when there are unsaved work.android-taskmanager-3

You can check the cancel() method in AddTaskActivity class, where we will be showing an alert box (see screenshot) using the built in AlertDialog, whenever the user clicks the cancel button without saving the task that he has entered.

You can read about the AlertDialog class in the android documentation.

Source code

I have uploaded source code for yesterday’s session in github and you can download it from there. I am also working in this week’s homework and will be posting the explanation and source code once I am done.

You can also subscribe to my blog’s RSS feed or follow me in Twitter to receive updates about my notes for the next sessions.

Posted in Android/Java | Tagged , , | 16 Comments

Android application that triggers the phone dial screen

As you know, I am following the free course on Developing Android applications in Java by CreativeTech and O’Reilly (even you should, if you are interested in developing apps for android) and this week’s homework in the course is to create an app which will show the phone dial screen when a button is clicked.

I just finished it and I thought of posting the source code and explanation so that it will be useful for others too.

Creating the project

The first step is to create the android project. You should follow the instructions given in the android documentation. You would need Eclipse and the android SDK to be installed to do this.

You will have an empty project to start with and with the default project structure, which I explained in my previous post.

Adding the button to the view

If you have followed the first session then you know that adding a button to the view is quite easy. All you have to do is to open your view file (/res/layout/main.xml) and add the following code.

<Button
    android:id="@+id/dialer_button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/dialer"
/>

You should also declare the value for the @string/dialer key in your values (/res/values/strings.xml) file by adding the following line

<string name="dialer">Phone Dialer</string>

Adding the button to the activity

After adding the button to the view, we have to declare the button in the activity. To do so, we have to add the following line in the Activity file.

Button dialerButton = (Button)findViewById(R.id.dialer_button);

Bind the Listener to the button

After creating the button instance in the activity, we have to bind a click listener to it. In the click listener we have to invoke the Phone dialer intent. Add the following code to the activity

dialerButton.setOnClickListener(new OnClickListener() {
	@Override
	public void onClick(View v) {
		//open the phone dialer on clicking the button
		Intent intent = new Intent(Intent.ACTION_DIAL);
		startActivity(intent);
	}
});

In the above snippet the following line does the trick

Intent intent = new Intent(Intent.ACTION_DIAL);

It creates the intent, which will open the phone dialer.

Finishing up

So that’s it, you are done 🙂 All you have to do now is to save the project and run it in the emulator. If everything is done properly, you will see the following screen in the emulator.

android-homework-1  android-homework-2

When you click the button, it should open the phone dialer.

Source code

I have uploaded the entire project source code into github and you download it from there and verify it with your code.

Try to complete the homework, before the next session and do come back to view the notes and the homework for the next session too. 🙂

You can also subscribe to my blog’s RSS feed or follow me in Twitter to receive updates about my notes for the next sessions.

Posted in Android/Java | Tagged , , | 7 Comments

The structure of an Android project

In my notes for the first session on the “Developing Android applications with Java” course, I forgot to mention about the project structure, which Tony (the instructor) explained. So this is a follow-up post to my previous post where I wrote about the notes, which I took during the session.

Android project structure

After you create a new project in eclipse, you will see the following top-level folders in your package explorer.

android-project-structure-1

Let me explain each of them in detail

/srcandroid-project-structure-2

This folder will contain the Java source files that you will be creating. In the screenshot you can see the ‘activity’ files that were created for the sample project. The files inside this  folder will be organized according to the package structure. This is similar to the /src folder which is present in any normal Java project.

/genandroid-project-structure-3

This is also a source folder, but will be contain Java source files that will be automatically generated by the android platform. Notable among the generated Java files is the R class, which you see in the screenshot. The framework will generate R class file and you can read more about it in the android documentation.

/Android {version Number}

This is the folder, which will contain the libraries (jars) that are need for the project. In the screenshot, you can see that it contains the framework jar file. This is similar to the /lib folder which is present in any normal Java project.

/resandroid-project-structure-4

This directory contains all the external resources (images, data files etc) that are used by the android application. These external resources (content) will be referenced in the android application.

This contains the following sub-folders

  • /res/drawable
  • /res/layout
  • /res/Values

/res/drawable

This folder contains all images, pictures etc. If you want to include an image or an icon in your android application, then you will be placing it in this folder.

/res/layout

This folder contains the UI layouts that will be used in the project. These UI layouts are stored as XML files. You can read more about the UI layouts in the android documentation.

/res/Values

This folder again contains XML files, which contain key values pairs that will be referenced in the application. These XML files declare Arrays, colors, dimensions, strings etc. The main idea of having these values in a separate XML file is that the values can be used based on the locale without actually changing the source code. For example the messages in the application can be in different languages based on the use locale.

/assets

This folder also contains external resources used in the application like the /res folder. But the main difference is that the resources are stored in raw format and can be read only programmatically.

AndroidManifest.xml

This is an XML file which contains meta information about the android application and is important file for every android application project. It contains information about various activities, views, services etc. It also contains the list of user permissions that are needed to run the android application.

That explains the project structure of the android application. You can read more about it in the android documentation.

BTW how is your homework coming along? Hope you all were able to finish it quickly. I will be posting the source code for the homework together with the explanation soon. So stay tuned. 🙂

Update: I have also completed the homework for this session and have posted my source code and explanation.

You can also subscribe to my blog’s RSS feed or follow me in Twitter to receive updates about my notes for the next sessions.

Posted in Android/Java | Tagged , , , | 12 Comments