public boolean checkDB() {
    SQLiteDatabase checkDB = null;
    try {
      checkDB = SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.OPEN_READWRITE);
    } catch (SQLiteException e) {
      Logging.Log(LOG_TAG, "checkDB() - Database not found");
    }

    if (checkDB != null) {
      if (checkDB.getVersion() != DB_VERSION) {
        Logging.Log(
            LOG_TAG,
            "checkDB() - Wrong DB version: old " + checkDB.getVersion() + " new " + DB_VERSION);
        // checkDB.execSQL("DROP TABLE IF EXISTS " + PREF_TABLE);
        // checkDB.execSQL("DROP TABLE IF EXISTS " + "showsTbl");
        checkDB.close();
        needsUpgrade = true;
        return needsUpgrade;
      } else {
        checkDB.close();
        return true;
      }
    } else {
      return false;
    }
  }
    @Override
    protected String doInBackground(String... upgradeString) {
      /*Upgrade or copy*/
      // Upgrade existing
      if (db.needsUpgrade) {
        Logging.Log(LOG_TAG, "Upgrading DB");
        success = db.upgradeDB();
        // Copy new one if failure upgrading

        if (!success) {
          try {
            db.copyDB();
          } catch (IOException e) {
            throw new Error("Error copying database");
          }
        }
        // Finally open DB
        try {
          db.openDataBase();
        } catch (SQLException e) {
          Logging.Log(LOG_TAG, "Unable to open database");
          Logging.Log(LOG_TAG, e.getStackTrace().toString());
        }
        // DB is now ready to use
        db.updatePref("splashShown", "true");
        publishProgress(25);
      }

      // Fix bad shows
      ArrayList<ArchiveShowObj> shows = db.getBadShows();
      Logging.Log(LOG_TAG, "Looking for shows to fix, found " + shows.size());
      if (shows.size() > 0) {
        Logging.Log(LOG_TAG, "Starting to fix shows");
        for (ArchiveShowObj s : shows) {
          Searching.getSongs(s, null, db, false);
        }
        publishProgress(50);
      }

      // Update Artists if necessary
      if (needsArtistFetching()) {
        Searching.updateArtists(db);
        publishProgress(75);
      }

      Downloading.syncFilesDirectory(parentScreen, db);

      return "Completed";
    }
 public boolean getSongIsDownloading(ArchiveSongObj song) {
   Logging.Log(LOG_TAG, "Get downloading status for " + song.getFileName());
   Cursor cur =
       db.rawQuery(
           "Select count(1) as count from songTbl "
               + "where fileName = '"
               + song.getFileName()
               + "' and download_id is not null and isDownloaded = 'false'",
           null);
   cur.moveToFirst();
   int count = cur.getInt(cur.getColumnIndex("count"));
   Logging.Log(LOG_TAG, "Result: " + count);
   cur.close();
   return count > 0;
 }
 private StaticDataStore(Context context, String caller) {
   super(context, DB_NAME, null, DB_VERSION);
   this.context = context;
   DB_PATH = context.getDatabasePath(DB_NAME).toString();
   initialize();
   Logging.Log(LOG_TAG, "DB opened by (initialized): " + caller);
 }
 public ArchiveShowObj getShow(String identifier) {
   Logging.Log(LOG_TAG, "Getting show: " + identifier);
   ArchiveShowObj show = null;
   Cursor cur =
       db.query(
           true,
           SHOW_TBL,
           new String[] {
             SHOW_IDENT, SHOW_TITLE, SHOW_ARTIST, SHOW_SOURCE, SHOW_HASVBR, SHOW_HASLBR, "_id"
           },
           SHOW_IDENT + "=" + "'" + identifier + "'",
           null,
           null,
           null,
           null,
           null);
   if (cur != null) {
     cur.moveToFirst();
     show =
         new ArchiveShowObj(
             cur.getString(cur.getColumnIndex(SHOW_IDENT)),
             cur.getString(cur.getColumnIndex(SHOW_TITLE)),
             cur.getString(cur.getColumnIndex(SHOW_ARTIST)),
             cur.getString(cur.getColumnIndex(SHOW_SOURCE)),
             cur.getString(cur.getColumnIndex(SHOW_HASVBR)),
             cur.getString(cur.getColumnIndex(SHOW_HASLBR)),
             cur.getInt(cur.getColumnIndex("_id")));
   }
   cur.close();
   return show;
 }
 public void initialize() {
   try {
     createDB();
   } catch (IOException e) {
     Logging.Log(LOG_TAG, "Unable to create database");
     Logging.Log(LOG_TAG, e.getStackTrace().toString());
   }
   if (!needsUpgrade) {
     try {
       openDataBase();
     } catch (SQLException e) {
       Logging.Log(LOG_TAG, "Unable to open database");
       Logging.Log(LOG_TAG, e.getStackTrace().toString());
     }
   }
 }
  public void copyDB() throws IOException {
    Logging.Log(LOG_TAG, "copyDB() - Copying database to " + DB_PATH);
    InputStream is = context.getAssets().open(DB_NAME);
    OutputStream os = new FileOutputStream(DB_PATH);

    byte[] buffer = new byte[1024];
    int length;
    while ((length = is.read(buffer)) > 0) {
      os.write(buffer, 0, length);
    }

    os.flush();
    os.close();
    is.close();
    dbCopied = true;
    Logging.Log(LOG_TAG, "copyDB() - Finished copying database");
  }
 public void updatePref(String pref_name, String pref_value) {
   Logging.Log(LOG_TAG, "Update " + pref_name + " to " + pref_value);
   db.execSQL(
       "UPDATE prefsTbl SET prefValue = '"
           + sanitize(pref_value)
           + "' WHERE prefName = '"
           + sanitize(pref_name)
           + "'");
 }
 public void setSongDownloading(ArchiveSongObj song, long id) {
   Logging.Log(LOG_TAG, "Start Downloading " + song.getFileName() + ": " + id);
   db.execSQL(
       "UPDATE songTbl "
           + "SET download_id = '"
           + id
           + "' WHERE fileName = '"
           + song.getFileName()
           + "'");
 }
 public ArrayList<ArchiveShowObj> getFavoriteShows() {
   Logging.Log(LOG_TAG, "Returning all favorite shows");
   /*
    * return db.query(RECENT_TBL, new String[] { SHOW_KEY, SHOW_IDENT,
    * SHOW_TITLE, SHOW_HASVBR, SHOW_HASLBR }, null, null, null, null,
    * null);
    */
   Cursor cur = db.rawQuery("SELECT * FROM " + FAVORITE_SHOW_VW, null);
   ArrayList<ArchiveShowObj> shows = getShowListFromCursor(cur);
   cur.close();
   return shows;
 }
 public ArrayList<ArchiveShowObj> getDownloadShows() {
   Logging.Log(LOG_TAG, "Returning all downloaded shows");
   /*
    * return db.query(SHOW_TBL, new String[] { SHOW_KEY, SHOW_IDENT,
    * SHOW_TITLE, SHOW_HASVBR, SHOW_HASLBR }, null, null, null, null,
    * null);
    */
   Cursor cur = db.rawQuery("SELECT * FROM " + DOWNLOADED_SHOW_VW, null);
   ArrayList<ArchiveShowObj> shows = getShowListFromCursor(cur);
   cur.close();
   return shows;
 }
  public void insertArtistBulk(ArrayList<ArrayList<String>> artists) {
    // db.execSQL("PRAGMA synchronous=OFF");
    /*InsertHelper ih = new InsertHelper(db,"artistTbl");
    ih.prepareForInsert();*/
    Logging.Log(LOG_TAG, "Bulk inserting " + artists.size() + " artists");
    db.execSQL("DELETE FROM artistTbl");
    try {
      db.beginTransaction();
      for (int i = 0; i < artists.size(); i++) {
        ContentValues artist = new ContentValues();
        artist.put("artistName", artists.get(i).get(0));
        artist.put("numShows", artists.get(i).get(1));
        db.insert("artistTbl", null, artist);
      }
      db.setTransactionSuccessful();
    } catch (SQLException e) {
      Logging.Log(LOG_TAG, e.toString());
    } finally {
      db.endTransaction();
    }

    // ih.execute();
  }
 protected void onProgressUpdate(Integer... progress) {
   if (progress[0] == 25) {
     parentScreen.dismissDialog(UPGRADE_DB);
     setImageButtonToFragments();
     completed = true;
     notifyActivityTaskCompleted();
   }
   if (progress[0] == 50) {
     Logging.Log(LOG_TAG, "Finished fixing shows");
   }
   if (progress[0] == 75) {
     String message = "Updated Artists";
     Toast.makeText(HomeScreen.this, message, Toast.LENGTH_SHORT).show();
   }
 }
 private boolean needsArtistFetching() {
   String dateString = db.getPref("artistUpdate");
   SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
   try {
     Logging.Log(LOG_TAG, "Trying date parse: " + dateString);
     Date dbDate = format.parse(dateString);
     GregorianCalendar cal1 = new GregorianCalendar();
     cal1.add(Calendar.MONTH, -2);
     Date upgradeDate = cal1.getTime();
     GregorianCalendar cal2 = new GregorianCalendar();
     cal2.add(Calendar.YEAR, 1);
     Date yearLater = cal2.getTime();
     Logging.Log(LOG_TAG, "Comparing " + upgradeDate.toString() + " .after(" + dbDate.toString());
     if (upgradeDate.after(dbDate) || yearLater.before(dbDate)) {
       return true;
     } else {
       return false;
     }
   } catch (java.text.ParseException e) {
     Logging.Log(LOG_TAG, "Error Getting Artists");
     e.printStackTrace();
     return false;
   }
 }
  public void createDB() throws IOException {

    boolean dbExists = checkDB();
    if (dbExists) {
    } else {
      Logging.Log(LOG_TAG, "createDB() - Database does not exist");
      this.getReadableDatabase();
      this.close();
      try {
        copyDB();
      } catch (IOException e) {
        throw new Error("Error copying database");
      }
    }
  }
  public static ArrayList<ArchiveShowObj> getShowListFromCursor(Cursor cur) {
    ArrayList<ArchiveShowObj> shows = new ArrayList<ArchiveShowObj>();

    for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
      shows.add(
          new ArchiveShowObj(
              cur.getString(cur.getColumnIndex(SHOW_IDENT)),
              cur.getString(cur.getColumnIndex(SHOW_TITLE)),
              cur.getString(cur.getColumnIndex(SHOW_ARTIST)),
              cur.getString(cur.getColumnIndex(SHOW_SOURCE)),
              cur.getString(cur.getColumnIndex(SHOW_HASVBR)),
              cur.getString(cur.getColumnIndex(SHOW_HASLBR)),
              cur.getInt(cur.getColumnIndex("_id"))));
    }

    Logging.Log(LOG_TAG, "Returning " + shows.size() + " shows from the DB.");
    return shows;
  }
 public void setSongDownloaded(String fileName) {
   Logging.Log(LOG_TAG, "Adding Song: " + fileName);
   db.execSQL(
       "UPDATE songTbl " + "SET isDownloaded = 'true' " + "WHERE fileName = '" + fileName + "'");
 }
 public void setSongDownloaded(long id) {
   Logging.Log(LOG_TAG, "Finished Downloading: " + id);
   db.execSQL(
       "UPDATE songTbl " + "SET isDownloaded = 'true' " + "WHERE download_id = '" + id + "'");
 }
 protected void onPreExecute() {
   Logging.Log(LOG_TAG, "Starting UpgradeTask");
   if (db.needsUpgrade) {
     parentScreen.showDialog(UPGRADE_DB);
   }
 }
 public void clearRecentShows() {
   Logging.Log(LOG_TAG, "Deleting all show");
   db.delete(RECENT_TBL, null, null);
 }
 public void deleteRecentShow(long show_id) {
   Logging.Log(LOG_TAG, "Deleting recent show at id=" + show_id);
   db.delete(RECENT_TBL, RECENT_SHOW_KEY + "=" + show_id, null);
 }
 public void deleteFavoriteShow(long show_id) {
   Logging.Log(LOG_TAG, "Deleting favorite show at show_id=" + show_id);
   db.execSQL("DELETE FROM favoriteShowsTbl WHERE show_id=" + show_id);
 }
 public void openDB(String caller) {
   if (!db.isOpen()) {
     openDataBase();
     Logging.Log(LOG_TAG, "DB opened by: " + caller);
   }
 }
 public void closeDB(String caller) {
   super.close();
   Logging.Log(LOG_TAG, "Database closed by:" + caller);
 }
 public void clearFavoriteShows() {
   Logging.Log(LOG_TAG, "Deleting all show");
   db.execSQL("DELETE FROM favoriteShowsTbl");
 }
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home_screen);

    Object retained = getLastNonConfigurationInstance();

    if (retained instanceof UpgradeTask) {
      Logging.Log(LOG_TAG, "UpgradeTask retained");
      upgradeTask = (UpgradeTask) retained;
      upgradeTask.setActivity(this);
    } else {
      // upgradeTask = new UpgradeTask(this);
    }

    int[] gradientColors = {0, 0xFF127DD4, 0};
    int curOrientation = this.getResources().getConfiguration().orientation;
    // FIXME
    separator1 = (ImageView) findViewById(R.id.separator1);
    separator1.setBackgroundDrawable(
        new GradientDrawable(
            curOrientation == Configuration.ORIENTATION_PORTRAIT
                ? Orientation.RIGHT_LEFT
                : Orientation.RIGHT_LEFT,
            gradientColors));
    // separator1.setBackground(new GradientDrawable(Orientation.RIGHT_LEFT, gradientColors));
    separator2 = (ImageView) findViewById(R.id.separator2);
    separator2.setBackgroundDrawable(
        new GradientDrawable(
            curOrientation == Configuration.ORIENTATION_PORTRAIT
                ? Orientation.RIGHT_LEFT
                : Orientation.TOP_BOTTOM,
            gradientColors));
    // separator2.setBackground(new GradientDrawable(Orientation.RIGHT_LEFT, gradientColors));
    separator3 = (ImageView) findViewById(R.id.separator3);
    separator3.setBackgroundDrawable(
        new GradientDrawable(
            curOrientation == Configuration.ORIENTATION_PORTRAIT
                ? Orientation.TOP_BOTTOM
                : Orientation.TOP_BOTTOM,
            gradientColors));
    // separator3.setBackground(new GradientDrawable(Orientation.TOP_BOTTOM, gradientColors));

    searchButton = (ImageButton) findViewById(R.id.HomeSearch);
    recentButton = (ImageButton) findViewById(R.id.HomeRecent);
    downloadButton = (ImageButton) findViewById(R.id.HomeDownload);
    playingButton = (ImageButton) findViewById(R.id.HomePlaying);
    featuredShowsButton = (ImageButton) findViewById(R.id.HomeFeatured);
    browseArtistsButton = (ImageButton) findViewById(R.id.HomeBrowse);

    db = StaticDataStore.getInstance(this);
    //		setImageButtonToToast();
    //		upgradeTask = new UpgradeTask(this);
    //		upgradeTask.execute();
    if (db.needsUpgrade && upgradeTask == null) { // DB needs updating
      setImageButtonToToast();
      upgradeTask = new UpgradeTask(this);
      upgradeTask.execute();
    } else { // DB Up to date, check artist date
      setImageButtonToFragments();
      if (needsArtistFetching() && upgradeTask == null) {
        upgradeTask = new UpgradeTask(this);
        upgradeTask.execute();
      }
    }

    if (db.dbCopied && !Boolean.parseBoolean(db.getPref("splashShown"))) {
      this.showDialog(
          this.getResources().getString(R.string.splash_screen), "Welcome to Vibe Vault 4");
      db.updatePref("splashShown", "true");
    } else if (db.needsUpgrade) {
      this.showDialog(
          this.getResources().getString(R.string.splash_screen), "Welcome to Vibe Vault 4");
    }
  }