package com.drewschrauf.robotronic.database;

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

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();
	}

	/**
	 * Fetch the cached data for the given URL
	 * 
	 * @param url
	 *            The URL to be looked up in the cache
	 * @return The cached data from the URL or null if there is none available
	 */
	public String getData(String url) {
		try {
			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;
		} catch (Exception e) {
			// database was closed before it could be read, just skip it this
			// time
			Log.e("DatabaseHandler",
					"Database could not be read, skipping cache");
			return null;
		}

	}

}

@@ -406,16 +406,25 @@
 data) %7B%0A
+%09%09try %7B%0A%09
 %09%09SQLite
@@ -469,16 +469,17 @@
 se();%0A%09%09
+%09
 ContentV
@@ -514,16 +514,17 @@
 lues();%0A
+%09
 %09%09values
@@ -559,24 +559,25 @@
 RL, url);%0A%09%09
+%09
 values.put(D
@@ -610,16 +610,17 @@
  data);%0A
+%09
 %09%09values
@@ -660,16 +660,17 @@
 D_DATE,%0A
+%09
 %09%09%09%09Syst
@@ -696,16 +696,17 @@
 s());%0A%09%09
+%09
 db.repla
@@ -752,16 +752,17 @@
 ues);%0A%09%09
+%09
 db.close
@@ -765,16 +765,218 @@
 lose();%0A
+%09%09%7D catch (Exception e) %7B%0A%09%09%09// database was closed before it could be written to, just skip it%0A%09%09%09// this time%0A%09%09%09Log.e(%22DatabaseHandler%22,%0A%09%09%09%09%09%22Database could not be written to, skipping cache%22);%0A%09%09%7D%0A
 %09%7D%0A%0A%09/**

Add error handling code to database writes