Hi All,

In a vane effort of helpless and shameless self-promotion, colleagues and I, of the Android-ActiveRecord group will be starting a NEW SERIES on how to use the ActiveRecord pattern as implemented in Android-ActiveRecord!……Hooray!

To kick things off, I will introduce users to:

  • the basics of ActiveRecord design pattern,
  • how to use the Android-ActiveRecord library.
  • some nice quirks and hacks!

The Application:
A simple Note-taking app, with the following features:

  • Create a new note
  • Read a note
  • Update a note
  • Delete a note
The Note App
Delete Alert Notification
SQLite terminal verification

Steps involved:
1. Create a New Android Project (details):
Project Name: TestActiveRecordAndroid
Android version: 2.2
Package: com.examples
Main: Main

2. Add the AndroidActiveRecord.jar library..follow these steps below:

  1. Create a libs/ folder under the project root directory.
  2. Copy the AndroidActiveRecord.jar file into it.
  3. Right-click…to configure build-path…and add JAR file
Add ActiveRecord-AR jar library

3.  Project structure to ensure things are fine.

Create a libs/ directory for JAR libs

That does the initial project setup!

Now..onto the actual coding parts….

File: Note.java – The Model

import org.kroz.activerecord.ActiveRecordBase;
import org.kroz.activerecord.Database;

public class Note extends ActiveRecordBase
	{
		// public for AR-access
		public String notesText;

		public Note()
			{
				// EMPTY
			}

		public Note(Database db)
			{
				super(db);
			}

		@Override
		public String toString()
			{
				return this.getID() + ":" + this.notesText;
			}
	}

File: NoteController.java


import org.kroz.activerecord.ActiveRecordBase;
import org.kroz.activerecord.ActiveRecordException;
import org.kroz.activerecord.Database;
import org.kroz.activerecord.DatabaseBuilder;

import android.content.Context;
import android.util.Log;

import com.examples.model.Note;

public class NoteController
	{
		// TODO: Externalise
		private final static String tag = "Main";
		private final static String dbName = "notes.db";
		private final static int dbVersion = 1;

		//
		private static Context ctx = null;
		private final int selectedItemIndex = 0;
		private static DatabaseBuilder builder = null;
		private static ActiveRecordBase conn = null;

		public NoteController(Context context)
			{
				this.ctx = context;
			}

		public static void initDatabase() throws ActiveRecordException
			{
				Log.d(tag, "init()");

				builder = new DatabaseBuilder(dbName);

				Log.d(tag, "Creating Table: Note ...");
				builder.addClass(Note.class);

				// Setup the builder
				Database.setBuilder(builder);

				Log.d(tag, "opening ActiveRecordBase");
				conn = ActiveRecordBase.open(ctx, dbName, dbVersion);
			}

		public Database getDatabase() throws ActiveRecordException
			{
				Database database = Database.createInstance(ctx, dbName, dbVersion);
				database.open();
				return database;
			}
	}

File: Main.java


import java.util.ArrayList;
import java.util.List;

import org.kroz.activerecord.ActiveRecordException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.examples.controller.NoteController;
import com.examples.model.Note;
import com.examples.view.NoteArrayAdapter;

public class Main extends Activity implements OnItemClickListener
	{
		private static final String tag = "Main";
		private EditText editText;
		private Button addButton;
		private ListView listView;
		private final List notesList = new ArrayList();
		private NoteArrayAdapter arrayAdapter;
		private NoteController noteController;
		private Note note;

		/** Called when the activity is first created. */
		@Override
		public void onCreate(Bundle savedInstanceState)
			{
				super.onCreate(savedInstanceState);

				// Set the View Layer
				setContentView(R.layout.main);

				try
					{
						noteController = new NoteController(getApplicationContext());
						noteController.initDatabase();
					}
				catch (ActiveRecordException e1)
					{
						e1.printStackTrace();
					}

				// Get reference to EditText view holder
				editText = (EditText) this.findViewById(R.id.editText);

				// Get reference to ListView holder
				listView = (ListView) this.findViewById(R.id.listView);

				// Get a customized ArrayAdapter
				arrayAdapter = new NoteArrayAdapter(getApplicationContext(), R.layout.list_item_icon, notesList);

				// Bind the Adapter to the ListView
				listView.setAdapter(arrayAdapter);

				// Set the EventListener
				listView.setOnItemClickListener(this);
				arrayAdapter.setNotifyOnChange(true);

				// Get reference to Button view holder
				addButton = (Button) this.findViewById(R.id.addButton);
				addButton.setOnClickListener(new OnClickListener()
					{
						@Override
						public void onClick(View arg0)
							{
								String noteText = editText.getText().toString();

								// Create and Save Note entry
								try
									{
										note = new Note();
										note.setDatabase(noteController.getDatabase());
										note.notesText = noteText;
										arrayAdapter.add(note);
										note.save();
									}
								catch (ActiveRecordException e)
									{
										e.printStackTrace();
									}
							}
					});
			}

		@Override
		public void onItemClick(AdapterView<!--?--> parent, View view, int position, long duration)
			{
				Note item = arrayAdapter.getItem(position);
				Toast.makeText(getApplicationContext(), item.toString(), Toast.LENGTH_SHORT).show();
				Builder alert = new AlertDialog.Builder(this);
				alert.setTitle("Delete Item?");

				// Set the positive button
				alert.setPositiveButton("Yes", new DialogInterface.OnClickListener()
					{
						@Override
						public void onClick(DialogInterface arg0, int arg1)
							{
								try
									{
										boolean success = note.delete();
										if (success)
											{
												Log.d(tag, "Deleted Note!");
												arrayAdapter.remove(note);
												Log.d(tag, "Removed from ListView layer");
											}
									}
								catch (ActiveRecordException e)
									{
										e.printStackTrace();
									}
							}
					});

				// Set the negative button
				alert.setNegativeButton("No", new DialogInterface.OnClickListener()
					{
						@Override
						public void onClick(DialogInterface arg0, int arg1)
							{
								// TODO Auto-generated method stub
							}
					});

				// When AlertDialog buttons are clicked - the dialog is dismissed
				alert.setCancelable(true);

				// Yeop - show it!!!
				alert.show();
			}
	}

File: NoteArrayAdapter.java


import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.examples.R;
import com.examples.model.Note;

public class NoteArrayAdapter extends ArrayAdapter
	{
		private static final String tag = "NoteArrayAdapter";
		private final List notes;

		public NoteArrayAdapter(Context context, int textViewResourceId, List list)
			{
				super(context, textViewResourceId, list);
				this.notes = list;
			}

		@Override
		public Note getItem(int index)
			{
				return this.notes.get(index);
			}

		@Override
		public int getCount()
			{
				return this.notes.size();
			}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
			{
				View row = convertView;
				if (row == null)
					{
						LayoutInflater inflater = LayoutInflater.from(getContext());
						row = inflater.inflate(R.layout.list_item_icon, parent, false);

					}
                                 //Get reference to TextView holder
				TextView label = (TextView) row.findViewById(R.id.list_item_title);
				Note item = getItem(position);
				label.setText(item.notesText.toString());

				return row;
			}
	}