1. package com.android.googleio2010bootcampcodelab;
  2.  
  3. import android.content.Context;
  4. import android.database.Cursor;
  5. import android.database.sqlite.*;
  6. import android.util.Log;
  7.  
  8. import java.util.HashMap;
  9. import java.util.LinkedList;
  10.  
  11. public class DataHelper {
  12. private static final String DATABASE_NAME = "searchterms.sqlite";
  13. private static final int DATABASE_VERSION = 1;
  14. private static final String TABLE_NAME = "terms";
  15.  
  16. static final String QUERY_TEXT = "QT";
  17. static final String QUERY_DATE = "QD";
  18.  
  19. private Context context;
  20. private SQLiteDatabase db;
  21.  
  22. private SQLiteStatement insertStmt;
  23. private static final String INSERT = "insert into "
  24. + TABLE_NAME + "(term, date) values (?, ?)";
  25.  
  26. public DataHelper(Context context) {
  27. this.context = context;
  28. OpenHelper openHelper = new OpenHelper(this.context);
  29. try {
  30. this.db = openHelper.getWritableDatabase();
  31. this.insertStmt = this.db.compileStatement(INSERT);
  32. }catch(Exception e) {
  33. Log.e("CollectData", "misfunctioning open" + e.toString());
  34. }
  35. }
  36.  
  37. public long insert(String term, String date) {
  38. this.insertStmt.bindString(1, term);
  39. this.insertStmt.bindString(2, date);
  40. return this.insertStmt.executeInsert();
  41. }
  42.  
  43. public void deleteAll() {
  44. this.db.delete(TABLE_NAME, null, null);
  45. }
  46.  
  47. public LinkedList<HashMap<String, String>> selectAll() {
  48. LinkedList<HashMap<String, String>> list = new LinkedList<HashMap<String, String>>();
  49.  
  50. HashMap<String, String> map;
  51.  
  52. Cursor cursor = this.db.query(TABLE_NAME, new String[] { "term", "date" },
  53. null, null, null, null, "id desc");
  54. if (cursor.moveToFirst()) {
  55. do {
  56. map = new HashMap<String, String>();
  57. map.put(QUERY_TEXT, cursor.getString(0));
  58. map.put(QUERY_DATE, cursor.getString(1));
  59. list.add(map);
  60. } while (cursor.moveToNext());
  61. }
  62.  
  63. if (cursor != null && !cursor.isClosed()) {
  64. cursor.close();
  65. }
  66.  
  67. return list;
  68. }
  69.  
  70. private static class OpenHelper extends SQLiteOpenHelper {
  71. OpenHelper(Context context) {
  72. super(context, DATABASE_NAME, null, DATABASE_VERSION);
  73. }
  74.  
  75. @Override
  76. public void onCreate(SQLiteDatabase db){
  77. Log.w("CollectData", "Create database.");
  78. db.execSQL("CREATE TABLE " + TABLE_NAME + " " +
  79. "(id INTEGER PRIMARY KEY, term text, date text);");
  80. }
  81.  
  82. @Override
  83. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  84. Log.w("CollectData", "Upgrading database, this will drop tables and recreate.");
  85. db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
  86. onCreate(db);
  87. }
  88. }
  89. }