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

Consolidated all my code in github

I got introduced to Git and Gitbub by Yuvi and ever since I have been hooked up. I have started using it for all my pet projects. I even convinced Steve Bruner so that I can use Github for RoloPress. 🙂

Over the years I have released lot of code out in the wild and I thought of consolidating all of them in Github, so that it can be of use to someone who might need them. At last I found some time and uploaded most of them to my Gitbub account.

Below is the description of some of those projects which are currently there in my Github account.

Bright Light

Bright Light is the WordPress theme, which is powering up my blog. I have released it out hoping that it might be useful for someone.

Android Samples

I created this project to share my homework and the sample code used in the “Developing Android Applications in Java” online class, which I am currently following.

RoloPress core and RoloPress Default

These projects contain my contribution to RoloPress, a WordPress based contact manager. You can read more about WordPress from its homepage.

FeedBurner – stats

FeedBurner-stats is a Google Gadget which allows you to keep track of your Feedburner subscriber count. It uses Google Chart API and Google Gadget API.

Bloglines Notifier

Bloglines Notifier is a Google Gadget which will notify you the count of unread items in your Bloglines account. (Hope someone is still using Bloglines 😉 )

Retweet

It is a fork of John Resig’s retweet script which I am using in my Easy Reweet WordPress Plugin. I have added a new feature to this script which allows you to associate the list of urls created to your bit.ly account.

Count Words

It’s a small Ruby script which prints the number of words (with their count) present in a given text file

Bulk unrar

It is a small Ruby script which unrars all files found in all the subdirectories of a director given in the command line.

I am still undecided about porting my WordPress Plugins from the official WordPress Plugin repository to Github. I guess it is better to have my Plugins in the Plugin repository for now.

Update (Feb-2013): I have now started to use github for my WordPress Plugins as well.

BTW feel free to fork any of these projects and I would be happy to pull in your changes if you have added some enhancements to them. 🙂

Posted in Random/Personal | Tagged , , , | 2 Comments

Bulk Delete can now move posts to trash instead of deleting

It’s been quite some time since I released updates to my WordPress Plugins since I was quite busy recently with lot of stuff (including the android course). Anyways I found some free time today and was able to push some updates to my Bulk Delete WordPress Plugin, which was overdue for quite some time. 🙂

Support for trash

WordPress 2.9 introduced the concept of trash, which allows you to move posts to trash (like Recycle bin in Windows or Trash in Mac) instead of deleting them directly.

I have added support for trash to my Bulk Delete WordPress Plugin. Now you can choose whether you want to delete the posts directly or just move them to trash. The credit for this feature goes to David Wren, you contributed code for this functionality.

Batch Deletes

I have also enabled another option which will be quite handy when you want to delete tons of posts. The most popular complain I hear from users of my Plugin is that, the PHP script times out if there were more than 1000 posts.

One possible solution is to increase the timeout period in php.ini file. But changing php.ini values is quite difficult especially if you were on a shared host.

I have now added support for batch deletes which allows you to delete the posts in batches. Say suppose you have to delete 5000 posts, you can now delete them in 5 batches with 1000 in each batch instead of trying to delete all the 5000 posts in a single go which usually results in script timeout. Hope this helps most of the users. 🙂

Screenshot

Below is the screenshot of the updated admin screen of the Plugin.

bulk-delete-wordpress-plugin

Support for translation

I have also generated the pot file for the Plugin and is available with the Plugin. If you are willing to do translation for the Plugin, use the pot file to create the .po files for your language and let me know. I will add it to the Plugin after giving credit to you.

Download

You can download the latest version of the Plugin from the Plugin’s home page.

Feedback

If you have any comments or if you want to report any bugs, please leave a comment below or contact me.

Stay updated

I would be posting updates about this Plugin in my blog and in Twitter. If you want to be informed when new version of this Plugin is released, then you can either subscribe to this blog’s RSS feed or follow me in Twitter.

Posted in Plugin Releases | Tagged , , | 9 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

Bright Light, a free WordPress theme

After promising a couple of times, I have finally found time to clean up the files and release the theme which I am using for my blog.

Right now I have uploaded the theme to my github page and you can find more information about using it from the theme’s homepage.

I have to clean up the files a bit more before I could upload them to the WordPress official theme directory. Till then you may have to download it from the theme’s homepage.

Features

The following are the some of the features of the theme

  • Two columns
  • Fluid width
  • Custom top navigation
  • Built-in support for social icons
  • Widgetized sidebar
  • Widgetized footer
  • Easy integration with couple of Plugins

Licence

The theme is released under GPL. Feel free to use or modify it as long as you can keep the link back to this page in the footer. If you cannot place the link (for instance on internal projects) and would still like to use the theme, then contact me and we can see what can be done.

Feedback

If you have any comments or if you want to report any bugs, please leave a comment below or contact me.

Posted in WordPress | Tagged , , , | 4 Comments