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.

Related posts

Tags: , ,

4 Comments so far

Follow up comments through RSS Feed | Post a comment

  • felix says:

    Just downloaded and compiled your TaskManager project, got these errors:

    The method afterTextChanged(Editable) of type new TextWatcher(){} must override a superclass method AddTaskActivity.java /TaskManager/src/com/sudarmuthu/android/taskmanager line 64 Java Problem
    The method beforeTextChanged(CharSequence, int, int, int) of type new TextWatcher(){} must override a superclass method AddTaskActivity.java /TaskManager/src/com/sudarmuthu/android/taskmanager line 58 Java Problem
    The method onClick(View) of type new View.OnClickListener(){} must override a superclass method AddTaskActivity.java /TaskManager/src/com/sudarmuthu/android/taskmanager line 37 Java Problem
    The method onClick(View) of type new View.OnClickListener(){} must override a superclass method AddTaskActivity.java /TaskManager/src/com/sudarmuthu/android/taskmanager line 45 Java Problem
    The method onClick(View) of type new View.OnClickListener(){} must override a superclass method ViewTasksActivity.java /TaskManager/src/com/sudarmuthu/android/taskmanager line 32 Java Problem
    The method onTextChanged(CharSequence, int, int, int) of type new TextWatcher(){} must override a superclass method AddTaskActivity.java /TaskManager/src/com/sudarmuthu/android/taskmanager line 53 Java Problem
    The import android.util.Log is never used TaskManagerApplication.java /TaskManager/src/com/sudarmuthu/android/taskmanager line 10 Java Problem

    • Sudar says:

      In your eclipse configuration, try changing the Java compiler compliance level to 1.6 (using Java SDK 1.6). There is a bug in Java SDK 1.5 in handling @override annotations.

  • felix says:

    cool that fixed it thanks.

2 Tweetbacks so far

1 Trackbacks/Pingbacks so far

Leave a Reply to sudarmuthu (Sudar) Cancel reply

Your email address will not be published. Required fields are marked *