package com.drewschrauf.robotronic.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DatabaseHandler {
	
	DatabaseHelper helper;
	
	public DatabaseHandler(Context context) {
		helper = new DatabaseHelper(context);
	}
	
	public void addData(String url, String data) {
		SQLiteDatabase db = helper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(DatabaseHelper.COLUMN_URL, url);
		values.put(DatabaseHelper.COLUMN_DATA, data);
		values.put(DatabaseHelper.COLUMN_FETCHED_DATE, System.currentTimeMillis());
		db.replace(DatabaseHelper.TABLE_NAME, null, values);
		db.close();
	}
	
	public String getData(String url) {
		SQLiteDatabase db = helper.getReadableDatabase();
		String[] columns = {DatabaseHelper.COLUMN_DATA};
		Cursor cursor = db.query(DatabaseHelper.TABLE_NAME, columns, DatabaseHelper.COLUMN_URL + " = '" + url + "'", null, null,
		        null, "1");
		
		String data = null;
		while (cursor.moveToNext()) {
			data = cursor.getString(0);
		}
		cursor.close();
		db.close();
		return data;
	}

}

@@ -187,16 +187,41 @@
 atabase;
+%0Aimport android.util.Log;
 %0A%0Apublic
@@ -245,17 +245,16 @@
 ndler %7B%0A
-%09
 %0A%09Databa
@@ -270,17 +270,16 @@
 helper;%0A
-%09
 %0A%09public
@@ -353,25 +353,24 @@
 ontext);%0A%09%7D%0A
-%09
 %0A%09public voi
@@ -646,17 +646,21 @@
 ED_DATE,
- 
+%0A%09%09%09%09
 System.c
@@ -752,17 +752,218 @@
 e();%0A%09%7D%0A
-%09
+%0A%09/**%0A%09 * Fetch the cached data for the given URL%0A%09 * %0A%09 * @param url%0A%09 *            The URL to be looked up in the cache%0A%09 * @return The cached data from the URL or null if there is none available%0A%09 */
 %0A%09public
@@ -988,24 +988,33 @@
 ring url) %7B%0A
+%09%09try %7B%0A%09
 %09%09SQLiteData
@@ -1053,16 +1053,17 @@
 base();%0A
+%09
 %09%09String
@@ -1076,16 +1076,17 @@
 umns = %7B
+ 
 Database
@@ -1107,11 +1107,13 @@
 DATA
+ 
 %7D;%0A
+%09
 %09%09Cu
@@ -1170,17 +1170,22 @@
 columns,
- 
+%0A%09%09%09%09%09
 Database
@@ -1238,24 +1238,19 @@
 null,%0A%09%09
-        
+%09%09%09
 null, %221
@@ -1255,18 +1255,16 @@
 %221%22);%0A%09%09
-%0A%09
 %09String 
@@ -1276,16 +1276,17 @@
 = null;%0A
+%09
 %09%09while 
@@ -1309,16 +1309,17 @@
 xt()) %7B%0A
+%09
 %09%09%09data 
@@ -1343,18 +1343,20 @@
 g(0);%0A%09%09
+%09
 %7D%0A
+%09
 %09%09cursor
@@ -1363,24 +1363,25 @@
 .close();%0A%09%09
+%09
 db.close();%0A
@@ -1380,16 +1380,17 @@
 lose();%0A
+%09
 %09%09return
@@ -1396,14 +1396,221 @@
 n data;%0A
+%09%09%7D catch (Exception e) %7B%0A%09%09%09// database was closed before it could be read, just skip it this%0A%09%09%09// time%0A%09%09%09Log.e(%22DatabaseHandler%22,%0A%09%09%09%09%09%22Database could not be read, skipping cache%22);%0A%09%09%09return null;%0A%09%09%7D%0A%0A
 %09%7D%0A%0A%7D%0A

Add error handling for when cache database unavailable