Storing data locally in Android is very easy. Here are few ways we can do it:
- Using SharedPreferences
- Using Files
- Using SQL databases.
This tutorial will tell you how to save data using SQL databases. For this we are taking a very simple application which stores a very simple list of tasks with their boolean status: done or not done.
The Database
The database contains only one table called "task" which has the following columns:
- Id
- Task
- Status
This tutorial will show us how to save data in a SQL database. For this we are would build a very simple application which stores a list of tasks with their boolean status(whether done or not done).
Creating the project
Create a project in eclipse with a activity called ViewTaskActivity like the following:

Here is the manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tasker"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.tasker.ViewTask"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Setting up the database helper
Now in the app you need to create a simple java class to represent the task. This will help us when we set up operations for the database.
-
-
package com.example.tasker;
-
public class Task {
-
private String taskName;
-
private int status;
-
private int id;
-
-
public Task()
-
{
-
this.taskName=null;
-
this.status=0;
-
}
-
public Task(String taskName, int status) {
-
super();
-
this.taskName = taskName;
-
this.status = status;
-
}
-
-
public int getId() {
-
return id;
-
}
-
public void setId(int id) {
-
this.id = id;
-
}
-
public String getTaskName() {
-
return taskName;
-
}
-
public void setTaskName(String taskName) {
-
this.taskName = taskName;
-
}
-
public int getStatus() {
-
return status;
-
}
-
public void setStatus(int status) {
-
this.status = status;
-
}
-
-
}
-
In Android we need to set up a database helper which will help in performing operations on the database. For now I am only going to define three database operations: Create, Read and Update.
In order to create a Database helper, we create a class that would extend SQLiteOpenHelper. And you also need to put in two methods: on Create() and onUpgrade().
onCreate() is called only one time when the database is accessed the first time. It will contain all the table create statements. And onUpgrade() is called when database is modifed in any way. So here is the helper class initially.
-
-
package com.example.tasker;
-
-
import android.content.ContentValues;
-
import android.content.Context;
-
import android.database.sqlite.SQLiteDatabase;
-
import android.database.sqlite.SQLiteDatabase.CursorFactory;
-
import android.database.sqlite.SQLiteOpenHelper;
-
-
public class TaskerDbHelper extends SQLiteOpenHelper {
-
-
private static final int DATABASE_VERSION = 1;
-
-
// Database Name
-
private static final String DATABASE_NAME = "taskerManager";
-
-
// tasks table name
-
private static final String TABLE_TASKS = "tasks";
-
-
// tasks Table Columns names
-
private static final String KEY_ID = "id";
-
private static final String KEY_TASKNAME = "taskName";
-
private static final String KEY_STATUS = "status";
-
-
public TaskerDbHelper(Context context) {
-
super(context, DATABASE_NAME, null, DATABASE_VERSION);
-
}
-
-
@Override
-
public void onCreate(SQLiteDatabase db) {
-
-
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_TASKS + " ( "
-
+ KEY_ID + "INTEGER PRIMARY KEY AUTOINCREMENT, "
-
+ KEY_TASKNAME+ " TEXT, "
-
+ KEY_STATUS + " INTEGER)";
-
db.execSQL(sql);
-
}
-
-
@Override
-
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
-
// Drop older table if existed
-
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TASKS);
-
// Create tables again
-
onCreate(db);
-
}
-
}
-
Adding Create Operation
Now as I said we need to add three operations on this database. Lets start with Create.
public void addTask(Task task) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASKNAME, task.getTaskName()); // task name
// status of task- can be 0 for not done and 1 for done
values.put(KEY_STATUS, task.getStatus());
// Inserting Row
db.insert(TABLE_TASKS, null, values);
db.close(); // Closing database connection
}
Adding a Read Operation
We will read from database and store all values in an Array list.
public List<Task> getAllTasks() {
List<Task> taskList = new ArrayList<Task>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_TASKS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Task task = new Task();
task.setId(cursor.getInt(0));
task.setTaskName(cursor.getString(1));
task.setStatus(cursor.getInt(2));
// Adding contact to list
taskList.add(task);
} while (cursor.moveToNext());
}
// return task list
return taskList;
}
The update operation
In this app I only need to update the status of the task. Status is 0 if task is not done and 1 if done.
public void updateTask(Task task) {
// updating row
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASKNAME, task.getTaskName());
values.put(KEY_STATUS, task.getStatus());
db.update(TABLE_TASKS, values, KEY_ID + " = ?",
new String[]{String.valueOf(task.getId())});
}
The View
I will try to include all options in one view so that the App has two seections in one screen. On the top is a EditText and an "Add" button to add tasks. And below that are the tasks in a ListView. The xml file for this view is as follows:
-
-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-
xmlns:tools="http://schemas.android.com/tools"
-
android:layout_width="match_parent"
-
android:layout_height="match_parent"
-
tools:context=".ViewTask" >
-
-
<EditText
-
android:id="@+id/editText1"
-
android:layout_width="wrap_content"
-
android:layout_height="wrap_content"
-
android:layout_alignParentLeft="true"
-
android:layout_alignParentTop="true"
-
android:ems="10" >
-
-
<requestFocus />
-
</EditText>
-
-
<Button
-
android:id="@+id/button1"
-
android:layout_width="wrap_content"
-
android:layout_height="wrap_content"
-
android:layout_alignParentRight="true"
-
android:layout_alignParentTop="true"
-
android:layout_marginRight="14dp"
-
android:text="@string/button"
-
android:onClick="addTaskNow"/>
-
-
<ListView
-
android:id="@+id/listView1"
-
android:layout_width="match_parent"
-
android:layout_height="wrap_content"
-
android:layout_alignParentLeft="true"
-
android:layout_below="@+id/button1" >
-
</ListView>
-
</RelativeLayout>
-
This list view is going to have a different view inside it. A checkbox to show status of the task as well as the description of the task. Pretty simple and easy right??? Lets see how that works out.
Create a new xml file in your layout folder called list_inner_view.xml and add the following controls in it:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="CheckBox" />
</RelativeLayout>
For now as there are no tasks added our app looks like this

Adding the logic
Now to populate my list view I will need a custom data adapter so inside my activity class I am going to create a private class extending an ArrayAdapter. The class is inside the activity we created earlier.
private class MyAdapter extends ArrayAdapter<Task>
{
Context context;
List<Task> taskList=new ArrayList<Task>();
int layoutResourceId;
public MyAdapter(Context context, int layoutResourceId,
List<Task> objects) {
super(context, layoutResourceId, objects);
this.layoutResourceId = layoutResourceId;
this.taskList=objects;
this.context=context;
}
/**This method will DEFINe what the view inside the list view will finally look like
* Here we are going to code that the checkbox state is the status of task and
* check box text is the task name
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_inner_view, parent, false);
CheckBox chk=(CheckBox)rowView.findViewById(R.id.chkStatus);
Task current=taskList.get(position);
chk.setText(current.getTaskName());
chk.setChecked(current.getStatus()==1?true:false);
return rowView;
}
}
Now you on start up of the app we need to add a few lines in the Activity OnCreate method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_task);
//db is a variable of type TaskerDbHelper
db=new TaskerDbHelper(this);
list=db.getAllTasks();
adapt=new MyAdapter(this,R.layout.list_inner_view , list);
ListView listTask=(ListView)findViewById(R.id.listView1);
listTask.setAdapter(adapt);
}
Next up is listing all the tasks in the list view and refreshing when ever a task is added. So in the xml finle don't forget to declare the listener for button then add the following method to activity
So after adding task we can see this

Lastly we need to change status of task when the checkbox against it is checked. This is a complicated bit as we will need the ID of task which was checked and then proceed. So here is what we are going to do we are going to visit our adapter again and add a listener over there.
So here is the updated complete code of the activity.
-
-
package com.example.tasker;
-
-
import java.util.ArrayList;
-
import java.util.List;
-
-
import android.os.Bundle;
-
import android.app.Activity;
-
import android.content.Context;
-
import android.database.sqlite.SQLiteDatabase;
-
import android.util.Log;
-
import android.view.LayoutInflater;
-
import android.view.Menu;
-
import android.view.View;
-
import android.view.ViewGroup;
-
import android.widget.ArrayAdapter;
-
import android.widget.CheckBox;
-
import android.widget.EditText;
-
import android.widget.ListView;
-
import android.widget.TextView;
-
import android.widget.Toast;
-
-
public class ViewTask extends Activity {
-
protected TaskerDbHelper db;
-
List<Task> list;
-
MyAdapter adapt;
-
-
@Override
-
protected void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.activity_view_task);
-
db = new TaskerDbHelper(this);
-
list = db.getAllTasks();
-
adapt = new MyAdapter(this, R.layout.list_inner_view, list);
-
ListView listTask = (ListView) findViewById(R.id.listView1);
-
listTask.setAdapter(adapt);
-
}
-
-
public void addTaskNow(View v) {
-
EditText t = (EditText) findViewById(R.id.editText1);
-
String s = t.getText().toString();
-
if (s.equalsIgnoreCase("")) {
-
Toast.makeText(this, "enter the task description first!!",
-
Toast.LENGTH_LONG);
-
} else {
-
Task task = new Task(s, 0);
-
db.addTask(task);
-
Log.d("tasker", "data added");
-
t.setText("");
-
adapt.add(task);
-
adapt.notifyDataSetChanged();
-
}
-
-
}
-
-
@Override
-
public boolean onCreateOptionsMenu(Menu menu) {
-
// Inflate the menu; this adds items to the action bar if it is present.
-
getMenuInflater().inflate(R.menu.activity_view_task, menu);
-
return true;
-
}
-
-
private class MyAdapter extends ArrayAdapter<Task> {
-
-
Context context;
-
List<Task> taskList = new ArrayList<Task>();
-
int layoutResourceId;
-
-
public MyAdapter(Context context, int layoutResourceId,
-
List<Task> objects) {
-
super(context, layoutResourceId, objects);
-
this.layoutResourceId = layoutResourceId;
-
this.taskList = objects;
-
this.context = context;
-
}
-
-
/**
-
* This method will DEFINe what the view inside the list view will
-
* finally look like Here we are going to code that the checkbox state
-
* is the status of task and check box text is the task name
-
*/
-
@Override
-
public View getView(int position, View convertView, ViewGroup parent) {
-
CheckBox chk = null;
-
if (convertView == null) {
-
LayoutInflater inflater = (LayoutInflater) context
-
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
-
convertView = inflater.inflate(R.layout.list_inner_view,
-
parent, false);
-
chk = (CheckBox) convertView.findViewById(R.id.chkStatus);
-
convertView.setTag(chk);
-
-
chk.setOnClickListener(new View.OnClickListener() {
-
-
@Override
-
public void onClick(View v) {
-
CheckBox cb = (CheckBox) v;
-
Task changeTask = (Task) cb.getTag();
-
changeTask.setStatus(cb.isChecked() == true ? 1 : 0);
-
db.updateTask(changeTask);
-
Toast.makeText(
-
getApplicationContext(),
-
"Clicked on Checkbox: " + cb.getText() + " is "
-
+ cb.isChecked(), Toast.LENGTH_LONG)
-
.show();
-
}
-
-
});
-
} else {
-
chk = (CheckBox) convertView.getTag();
-
}
-
Task current = taskList.get(position);
-
chk.setText(current.getTaskName());
-
chk.setChecked(current.getStatus() == 1 ? true : false);
-
chk.setTag(current);
-
Log.d("listener", String.valueOf(current.getId()));
-
return convertView;
-
}
-
-
}
-
-
}
-
Now the finally when we check the checkbox our database will reflect changes as this

And the task will be checked

So that is it for now folks. Hope you enjoyed this tutorial. I had fun making it!!! With some more work it can be turned into a full fledged check-list for you.
The project source code is attached with the tutorial, download the Eclipse Project from there.
| Attachment | Size |
|---|---|
| Tasker.zip - Android Todo App Project | 1.11 MB |
|
|
Related Links
- Building a TODO List app in Android using SQLite
- Sending SMS using Android
- Building Paint like Application in Android
- Building Live Stock Quotes App in Android
- How does Android Service Lifecycle look like?
- Android - Sensors a review
- What's new in Google Icecream Sandwich (Android 4.0)?
- What is a Niche?
- How to keep screen from dimming or sleeping in Android?
- What is the size of icon for various devices profile in Android?



Building Live Stock Quotes App in Android
Did you like this article? Did it Help you Solve your Problem? You can get the all the latest articles published at DeveloperFeed in your email inbox by entering your email address below. Your address will only be used for mailing you the articles, and each one will include a link so you can unsubscribe at any time.


Manpreet is an Architect & Software developer currently focusing on developing mobile apps on the iOS (iPhone/iPad) Platform. He’s the founder of a small iPhone development studio