Wednesday, February 27, 2008

Searching in a local database

SDK : M5-rc14


Previously, we searched in an array, now we are going to do that in a database. I'll be using the image viewing application from previous posts. The steps are,

a. Create a database in Images.java and insert the name and path of images.

b. Access the database in ImageSearch.java and retrieve the values.



Images.java

public SQLiteDatabase db = null;
public static String dbase = "imagedb";
static String dbTable = "my_table";

try {

createDatabase(dbase, 1, MODE_WORLD_READABLE,null);
db = openDatabase(dbase, null);


} catch (FileNotFoundException e)
{
e.printStackTrace();
}

db.execSQL("CREATE TABLE IF NOT EXISTS "+dbTable+ " (Name TEXT, Path TEXT);");

for(int i= 0 ; i< imagelist.length; i++)
{
// mFiles[i] = imagelist[i].getAbsolutePath();

db.execSQL("INSERT OR IGNORE INTO " + dbTable + " VALUES ('"+ imagelist[i].getName() + "', '" + imagelist[i].getAbsolutePath() +"');");
}

- Nothing much to explain here. They are the basic SQLite statements.




ImageSearch.java

public SQLiteDatabase db = null;

protected void onCreate(Bundle icicle)
{

super.onCreate(icicle);
try
{
db = this.openDatabase(Images.dbase, null);
}catch(FileNotFoundException e)
{
e.printStackTrace();
}


- Open the database in onCreate().



Remove/Comment the following code in doSearchQuery(). Thats the array part.

for(String file : Images.mFiles)
{
if(file.contains(queryString))
{
result.add(file);
}
}


And add the following code after queryString in doSearchQuery() method.

String[] values = {"Name", "Path"};
Cursor c = db.query(true, Images.dbTable, values, null, null, null, null, null);


int name = c.getColumnIndex("Name");

int path = c.getColumnIndex("Path");

if (c != null)
{
if (c.first())
{
do {
String imagename = c.getString(name);
String imagepath = c.getString(path);

if(imagepath.contains(queryString))
{
result.add(imagepath);
}
} while (c.next());
}
}


- We'll query the database for all the names and paths. But we are not using the name.

- Add the matching paths to the result ArrayList and pass it on to the Uri array like before.


These are the only differences between searching in an array and a database.

No comments: