Example usage for android.database.sqlite SQLiteDatabase delete

List of usage examples for android.database.sqlite SQLiteDatabase delete

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteDatabase delete.

Prototype

public int delete(String table, String whereClause, String[] whereArgs) 

Source Link

Document

Convenience method for deleting rows in the database.

Usage

From source file:com.rener.sea.DBHelper.java

private long deleteReport(JSONArray data) {
    SQLiteDatabase db = this.getWritableDatabase();
    int i = -1;//  www  .j  a va2  s  .  c o  m
    try {
        for (i = 0; i < data.length(); i++) {
            JSONObject item = data.getJSONObject(i);
            long id = db.delete(DBSchema.TABLE_REPORT, DBSchema.REPORT_ID + "=?",
                    new String[] { String.valueOf(item.getLong(DBSchema.REPORT_ID)) });
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    db.close();
    return i;
}

From source file:com.rener.sea.DBHelper.java

private long deleteUsers(JSONArray data) {
    SQLiteDatabase db = this.getWritableDatabase();
    int i = -1;//  ww w .  ja  va  2 s  .  c om
    try {
        for (i = 0; i < data.length(); i++) {
            JSONObject item = data.getJSONObject(i);
            long id = db.delete(DBSchema.TABLE_USERS, DBSchema.USER_ID + "=?",
                    new String[] { String.valueOf(item.getLong(DBSchema.USER_ID)) });
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    db.close();
    return i;
}

From source file:com.rener.sea.DBHelper.java

private long deleteFlowchart(JSONArray data) {
    SQLiteDatabase db = this.getWritableDatabase();
    int i = -1;//from w  w  w  . j a  v  a2s. c o m
    try {
        for (i = 0; i < data.length(); i++) {
            JSONObject item = data.getJSONObject(i);
            long id = db.delete(DBSchema.TABLE_FLOWCHART, DBSchema.FLOWCHART_ID + "=?",
                    new String[] { String.valueOf(item.getLong(DBSchema.FLOWCHART_ID)) });
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    db.close();
    return i;
}

From source file:com.rener.sea.DBHelper.java

private long deleteLocation_category(JSONArray data) {
    SQLiteDatabase db = this.getWritableDatabase();
    int i = -1;//w  w  w  . j a va  2 s  . c  om
    try {
        for (i = 0; i < data.length(); i++) {
            JSONObject item = data.getJSONObject(i);
            long id = db.delete(DBSchema.TABLE_LOCATION_CATEGORY,
                    DBSchema.LOCATION_CATEGORY_LOCATION_ID + " =? AND " + DBSchema.LOCATION_CATEGORY_CATEGORY_ID
                            + " =? ",
                    new String[] { String.valueOf(item.getLong(DBSchema.LOCATION_CATEGORY_LOCATION_ID)),
                            String.valueOf(item.getLong(DBSchema.LOCATION_CATEGORY_CATEGORY_ID)) });
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    db.close();
    return i;
}

From source file:com.google.android.apps.muzei.provider.MuzeiProvider.java

private int deleteArtwork(@NonNull final Uri uri, final String selection, final String[] selectionArgs) {
    // Opens the database object in "write" mode.
    final SQLiteDatabase db = databaseHelper.getWritableDatabase();
    String finalWhere = selection;
    if (MuzeiProvider.uriMatcher.match(uri) == ARTWORK_ID) {
        finalWhere = MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID + " = "
                + uri.getLastPathSegment();
        // If there were additional selection criteria, append them to the final WHERE clause
        if (selection != null)
            finalWhere = finalWhere + " AND " + selection;
    }//from w  ww.  j  a v a 2  s . c o m
    // We can't just simply delete the rows as that won't free up the space occupied by the
    // artwork image files associated with each row being deleted. Instead we have to query
    // and manually delete each artwork file
    String[] projection = new String[] { MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID,
            MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI, MuzeiContract.Artwork.COLUMN_NAME_TOKEN };
    Cursor rowsToDelete = queryArtwork(uri, projection, finalWhere, selectionArgs,
            MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI);
    if (rowsToDelete == null) {
        return 0;
    }
    // First we build a list of IDs to be deleted. This will be used if we need to determine
    // if a given image URI needs to be deleted
    List<String> idsToDelete = new ArrayList<>();
    rowsToDelete.moveToFirst();
    while (!rowsToDelete.isAfterLast()) {
        idsToDelete.add(Long.toString(rowsToDelete.getLong(0)));
        rowsToDelete.moveToNext();
    }
    String notInDeleteIds = MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID + " NOT IN ("
            + TextUtils.join(",", idsToDelete) + ")";
    // Now we actually go through the list of rows to be deleted
    // and check if we can delete the artwork image file associated with each one
    rowsToDelete.moveToFirst();
    while (!rowsToDelete.isAfterLast()) {
        Uri artworkUri = ContentUris.withAppendedId(MuzeiContract.Artwork.CONTENT_URI, rowsToDelete.getLong(0));
        String imageUri = rowsToDelete.getString(1);
        String token = rowsToDelete.getString(2);
        if (TextUtils.isEmpty(imageUri) && TextUtils.isEmpty(token)) {
            // An empty image URI and token means the artwork is unique to this specific row
            // so we can always delete it when the associated row is deleted
            File artwork = getCacheFileForArtworkUri(artworkUri);
            if (artwork != null && artwork.exists()) {
                artwork.delete();
            }
        } else if (TextUtils.isEmpty(imageUri)) {
            // Check if there are other rows using this same token that aren't
            // in the list of ids to delete
            Cursor otherArtwork = queryArtwork(MuzeiContract.Artwork.CONTENT_URI,
                    new String[] { MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID },
                    MuzeiContract.Artwork.COLUMN_NAME_TOKEN + "=? AND " + notInDeleteIds,
                    new String[] { token }, null);
            if (otherArtwork == null) {
                continue;
            }
            if (otherArtwork.getCount() == 0) {
                // There's no non-deleted rows that reference this same artwork URI
                // so we can delete the artwork
                File artwork = getCacheFileForArtworkUri(artworkUri);
                if (artwork != null && artwork.exists()) {
                    artwork.delete();
                }
            }
            otherArtwork.close();
        } else {
            // Check if there are other rows using this same image URI that aren't
            // in the list of ids to delete
            Cursor otherArtwork = queryArtwork(MuzeiContract.Artwork.CONTENT_URI,
                    new String[] { MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID },
                    MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI + "=? AND " + notInDeleteIds,
                    new String[] { imageUri }, null);
            if (otherArtwork == null) {
                continue;
            }
            if (otherArtwork.getCount() == 0) {
                // There's no non-deleted rows that reference this same artwork URI
                // so we can delete the artwork
                File artwork = getCacheFileForArtworkUri(artworkUri);
                if (artwork != null && artwork.exists()) {
                    artwork.delete();
                }
            }
            otherArtwork.close();
        }
        rowsToDelete.moveToNext();
    }
    rowsToDelete.close();
    int count = db.delete(MuzeiContract.Artwork.TABLE_NAME, finalWhere, selectionArgs);
    if (count > 0) {
        notifyChange(uri);
    }
    return count;
}

From source file:biz.shadowservices.DegreesToolbox.DataFetcher.java

public FetchResult updateData(Context context, boolean force) {
    //Open database
    DBOpenHelper dbhelper = new DBOpenHelper(context);
    SQLiteDatabase db = dbhelper.getWritableDatabase();

    // check for internet connectivity
    try {//from  w ww .  j  a va 2  s. c  o  m
        if (!isOnline(context)) {
            Log.d(TAG, "We do not seem to be online. Skipping Update.");
            return FetchResult.NOTONLINE;
        }
    } catch (Exception e) {
        exceptionReporter.reportException(Thread.currentThread(), e, "Exception during isOnline()");
    }
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    if (!force) {
        try {
            if (sp.getBoolean("loginFailed", false) == true) {
                Log.d(TAG, "Previous login failed. Skipping Update.");
                DBLog.insertMessage(context, "i", TAG, "Previous login failed. Skipping Update.");
                return FetchResult.LOGINFAILED;
            }
            if (sp.getBoolean("autoupdates", true) == false) {
                Log.d(TAG, "Automatic updates not enabled. Skipping Update.");
                DBLog.insertMessage(context, "i", TAG, "Automatic updates not enabled. Skipping Update.");
                return FetchResult.NOTALLOWED;
            }
            if (!isBackgroundDataEnabled(context) && sp.getBoolean("obeyBackgroundData", true)) {
                Log.d(TAG, "Background data not enabled. Skipping Update.");
                DBLog.insertMessage(context, "i", TAG, "Background data not enabled. Skipping Update.");
                return FetchResult.NOTALLOWED;
            }
            if (!isAutoSyncEnabled() && sp.getBoolean("obeyAutoSync", true)
                    && sp.getBoolean("obeyBackgroundData", true)) {
                Log.d(TAG, "Auto sync not enabled. Skipping Update.");
                DBLog.insertMessage(context, "i", TAG, "Auto sync not enabled. Skipping Update.");
                return FetchResult.NOTALLOWED;
            }
            if (isWifi(context) && !sp.getBoolean("wifiUpdates", true)) {
                Log.d(TAG, "On wifi, and wifi auto updates not allowed. Skipping Update");
                DBLog.insertMessage(context, "i", TAG,
                        "On wifi, and wifi auto updates not allowed. Skipping Update");
                return FetchResult.NOTALLOWED;
            } else if (!isWifi(context)) {
                Log.d(TAG, "We are not on wifi.");
                if (!isRoaming(context) && !sp.getBoolean("2DData", true)) {
                    Log.d(TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update.");
                    DBLog.insertMessage(context, "i", TAG,
                            "Automatic updates on 2Degrees data not enabled. Skipping Update.");
                    return FetchResult.NOTALLOWED;
                } else if (isRoaming(context) && !sp.getBoolean("roamingData", false)) {
                    Log.d(TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update.");
                    DBLog.insertMessage(context, "i", TAG,
                            "Automatic updates on roaming mobile data not enabled. Skipping Update.");
                    return FetchResult.NOTALLOWED;
                }

            }
        } catch (Exception e) {
            exceptionReporter.reportException(Thread.currentThread(), e,
                    "Exception while finding if to update.");
        }

    } else {
        Log.d(TAG, "Update Forced");
    }

    try {
        String username = sp.getString("username", null);
        String password = sp.getString("password", null);
        if (username == null || password == null) {
            DBLog.insertMessage(context, "i", TAG, "Username or password not set.");
            return FetchResult.USERNAMEPASSWORDNOTSET;
        }

        // Find the URL of the page to send login data to.
        Log.d(TAG, "Finding Action. ");
        HttpGetter loginPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/web/ip/login");
        String loginPageString = loginPageGet.execute();
        if (loginPageString != null) {
            Document loginPage = Jsoup.parse(loginPageString,
                    "https://secure.2degreesmobile.co.nz/web/ip/login");
            Element loginForm = loginPage.getElementsByAttributeValue("name", "loginFrm").first();
            String loginAction = loginForm.attr("action");
            // Send login form
            List<NameValuePair> loginValues = new ArrayList<NameValuePair>();
            loginValues.add(new BasicNameValuePair("externalURLRedirect", ""));
            loginValues.add(new BasicNameValuePair("hdnAction", "login_userlogin"));
            loginValues.add(new BasicNameValuePair("hdnAuthenticationType", "M"));
            loginValues.add(new BasicNameValuePair("hdnlocale", ""));

            loginValues.add(new BasicNameValuePair("userid", username));
            loginValues.add(new BasicNameValuePair("password", password));
            Log.d(TAG, "Sending Login ");
            HttpPoster sendLoginPoster = new HttpPoster(loginAction, loginValues);
            // Parse result

            String loginResponse = sendLoginPoster.execute();
            Document loginResponseParsed = Jsoup.parse(loginResponse);
            // Determine if this is a pre-pay or post-paid account.
            boolean postPaid;
            if (loginResponseParsed
                    .getElementById("p_CustomerPortalPostPaidHomePage_WAR_customerportalhomepage") == null) {
                Log.d(TAG, "Pre-pay account or no account.");
                postPaid = false;
            } else {
                Log.d(TAG, "Post-paid account.");
                postPaid = true;
            }

            String homepageUrl = "https://secure.2degreesmobile.co.nz/group/ip/home";
            if (postPaid) {
                homepageUrl = "https://secure.2degreesmobile.co.nz/group/ip/postpaid";
            }
            HttpGetter homepageGetter = new HttpGetter(homepageUrl);
            String homepageHTML = homepageGetter.execute();
            Document homePage = Jsoup.parse(homepageHTML);

            Element accountSummary = homePage.getElementById("accountSummary");
            if (accountSummary == null) {
                Log.d(TAG, "Login failed.");
                return FetchResult.LOGINFAILED;
            }
            db.delete("cache", "", null);
            /* This code fetched some extra details for postpaid users, but on reflection they aren't that useful.
             * Might reconsider this.
             *
             if (postPaid) {
                     
               Element accountBalanceSummaryTable = accountSummary.getElementsByClass("tableBillSummary").first();
               Elements rows = accountBalanceSummaryTable.getElementsByTag("tr");
               int rowno = 0;
               for (Element row : rows) {
                  if (rowno > 1) {
             break;
                  }
                  //Log.d(TAG, "Starting row");
                  //Log.d(TAG, row.html());
                  Double value;
                  try {
             Element amount = row.getElementsByClass("tableBillamount").first();
             String amountHTML = amount.html();
             Log.d(TAG, amountHTML.substring(1));
             value = Double.parseDouble(amountHTML.substring(1));
                  } catch (Exception e) {
             Log.d(TAG, "Failed to parse amount from row.");
             value = null;
                  }
                  String expiresDetails = "";
                  String expiresDate = null;
                  String name = null;
                  try {
             Element details = row.getElementsByClass("tableBilldetail").first();
             name = details.ownText();
             Element expires = details.getElementsByTag("em").first();
             if (expires != null) {
                 expiresDetails = expires.text();
             } 
             Log.d(TAG, expiresDetails);
             Pattern pattern;
             pattern = Pattern.compile("\\(payment is due (.*)\\)");
             Matcher matcher = pattern.matcher(expiresDetails);
             if (matcher.find()) {
                /*Log.d(TAG, "matched expires");
                Log.d(TAG, "group 0:" + matcher.group(0));
                Log.d(TAG, "group 1:" + matcher.group(1));
                Log.d(TAG, "group 2:" + matcher.group(2)); *
                String expiresDateString = matcher.group(1);
                Date expiresDateObj;
                if (expiresDateString != null) {
                   if (expiresDateString.length() > 0) {
                      try {
                         expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
                         expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
                      } catch (java.text.ParseException e) {
                         Log.d(TAG, "Could not parse date: " + expiresDateString);
                      }
                   }   
                }
             }
                  } catch (Exception e) {
             Log.d(TAG, "Failed to parse details from row.");
                  }
                  String expirev = null;
                  ContentValues values = new ContentValues();
                  values.put("name", name);
                  values.put("value", value);
                  values.put("units", "$NZ");
                  values.put("expires_value", expirev );
                  values.put("expires_date", expiresDate);
                  db.insert("cache", "value", values );
                  rowno++;
               }
            } */
            Element accountSummaryTable = accountSummary.getElementsByClass("tableAccountSummary").first();
            Elements rows = accountSummaryTable.getElementsByTag("tr");
            for (Element row : rows) {
                // We are now looking at each of the rows in the data table.
                //Log.d(TAG, "Starting row");
                //Log.d(TAG, row.html());
                Double value;
                String units;
                try {
                    Element amount = row.getElementsByClass("tableBillamount").first();
                    String amountHTML = amount.html();
                    //Log.d(TAG, amountHTML);
                    String[] amountParts = amountHTML.split("&nbsp;", 2);
                    //Log.d(TAG, amountParts[0]);
                    //Log.d(TAG, amountParts[1]);
                    if (amountParts[0].contains("Included") || amountParts[0].equals("All You Need")
                            || amountParts[0].equals("Unlimited Text*")) {
                        value = Values.INCLUDED;
                    } else {
                        try {
                            value = Double.parseDouble(amountParts[0]);
                        } catch (NumberFormatException e) {
                            exceptionReporter.reportException(Thread.currentThread(), e, "Decoding value.");
                            value = 0.0;
                        }
                    }
                    units = amountParts[1];
                } catch (NullPointerException e) {
                    //Log.d(TAG, "Failed to parse amount from row.");
                    value = null;
                    units = null;
                }
                Element details = row.getElementsByClass("tableBilldetail").first();
                String name = details.getElementsByTag("strong").first().text();
                Element expires = details.getElementsByTag("em").first();
                String expiresDetails = "";
                if (expires != null) {
                    expiresDetails = expires.text();
                }
                Log.d(TAG, expiresDetails);
                Pattern pattern;
                if (postPaid == false) {
                    pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?expiring on (.*)\\)");
                } else {
                    pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?will expire on (.*)\\)");
                }
                Matcher matcher = pattern.matcher(expiresDetails);
                Double expiresValue = null;
                String expiresDate = null;
                if (matcher.find()) {
                    /*Log.d(TAG, "matched expires");
                    Log.d(TAG, "group 0:" + matcher.group(0));
                    Log.d(TAG, "group 1:" + matcher.group(1));
                    Log.d(TAG, "group 2:" + matcher.group(2)); */
                    try {
                        expiresValue = Double.parseDouble(matcher.group(1));
                    } catch (NumberFormatException e) {
                        expiresValue = null;
                    }
                    String expiresDateString = matcher.group(2);
                    Date expiresDateObj;
                    if (expiresDateString != null) {
                        if (expiresDateString.length() > 0) {
                            try {
                                expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
                                expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
                            } catch (java.text.ParseException e) {
                                Log.d(TAG, "Could not parse date: " + expiresDateString);
                            }
                        }
                    }
                }
                ContentValues values = new ContentValues();
                values.put("name", name);
                values.put("value", value);
                values.put("units", units);
                values.put("expires_value", expiresValue);
                values.put("expires_date", expiresDate);
                db.insert("cache", "value", values);
            }

            if (postPaid == false) {
                Log.d(TAG, "Getting Value packs...");
                // Find value packs
                HttpGetter valuePacksPageGet = new HttpGetter(
                        "https://secure.2degreesmobile.co.nz/group/ip/prevaluepack");
                String valuePacksPageString = valuePacksPageGet.execute();
                //DBLog.insertMessage(context, "d", "",  valuePacksPageString);
                if (valuePacksPageString != null) {
                    Document valuePacksPage = Jsoup.parse(valuePacksPageString);
                    Elements enabledPacks = valuePacksPage.getElementsByClass("yellow");
                    for (Element enabledPack : enabledPacks) {
                        Element offerNameElemt = enabledPack
                                .getElementsByAttributeValueStarting("name", "offername").first();
                        if (offerNameElemt != null) {
                            String offerName = offerNameElemt.val();
                            DBLog.insertMessage(context, "d", "", "Got element: " + offerName);
                            ValuePack[] packs = Values.valuePacks.get(offerName);
                            if (packs == null) {
                                DBLog.insertMessage(context, "d", "",
                                        "Offer name: " + offerName + " not matched.");
                            } else {
                                for (ValuePack pack : packs) {
                                    ContentValues values = new ContentValues();
                                    values.put("plan_startamount", pack.value);
                                    values.put("plan_name", offerName);
                                    DBLog.insertMessage(context, "d", "",
                                            "Pack " + pack.type.id + " start value set to " + pack.value);
                                    db.update("cache", values, "name = '" + pack.type.id + "'", null);
                                }
                            }
                        }
                    }
                }
            }

            SharedPreferences.Editor prefedit = sp.edit();
            Date now = new Date();
            prefedit.putString("updateDate", DateFormatters.ISO8601FORMAT.format(now));
            prefedit.putBoolean("loginFailed", false);
            prefedit.putBoolean("networkError", false);
            prefedit.commit();
            DBLog.insertMessage(context, "i", TAG, "Update Successful");
            return FetchResult.SUCCESS;

        }
    } catch (ClientProtocolException e) {
        DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
        return FetchResult.NETWORKERROR;
    } catch (IOException e) {
        DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
        return FetchResult.NETWORKERROR;
    } finally {
        db.close();
    }
    return null;
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion);

    if (oldVersion <= 23) {
        Log.w(TAG, "Schema too old to migrate, dropping all.");
        dropAll(db);/*from  w w w . j  ava 2 s . c om*/
        onCreate(db);
        return;
    }

    if (oldVersion <= 24) {
        Log.w(TAG, "Adding columns 'presence' and 'status' to contact table.");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.STATUS + " TEXT");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.PRESENCE + " INTEGER DEFAULT "
                + Presence.AVAILABLE);
    }

    if (oldVersion <= 25) {
        Log.w(TAG, "Adding columns 'presence' and 'status' to contact table.");
        db.execSQL("ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.FEED_NAME + " TEXT");
    }

    if (oldVersion <= 26) {
        Log.w(TAG, "Adding column 'picture' to contact table.");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.PICTURE + " BLOB");
    }

    if (oldVersion <= 27) {
        Log.w(TAG, "Adding column 'last_presence_time' to contact table.");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.LAST_PRESENCE_TIME
                + " INTEGER DEFAULT 0");
    }

    if (oldVersion <= 28) {
        Log.w(TAG, "Adding column 'picture' to my_info table.");
        db.execSQL("ALTER TABLE " + MyInfo.TABLE + " ADD COLUMN " + MyInfo.PICTURE + " BLOB");
    }
    if (oldVersion <= 29) {
        Log.w(TAG, "Adding column 'version' to group table.");
        db.execSQL("ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.VERSION + " INTEGER DEFAULT -1");
    }
    if (oldVersion <= 30) {
        Log.w(TAG, "Adding column 'E' to object table.");
        db.execSQL("ALTER TABLE " + DbObject.TABLE + " ADD COLUMN " + DbObject.ENCODED + " BLOB");
        createIndex(db, "INDEX", "objects_by_encoded", DbObject.TABLE, DbObject.ENCODED);
    }
    if (oldVersion <= 31) {
        Log.w(TAG, "Adding column 'child_feed' to object table.");
        db.execSQL("ALTER TABLE " + DbObject.TABLE + " ADD COLUMN " + DbObject.CHILD_FEED_NAME + " TEXT");
        createIndex(db, "INDEX", "child_feeds", DbObject.TABLE, DbObject.CHILD_FEED_NAME);
    }
    if (oldVersion <= 32) {
        // Bug fix.
        Log.w(TAG, "Updating app state objects.");
        db.execSQL("UPDATE " + DbObject.TABLE + " SET " + DbObject.CHILD_FEED_NAME + " = NULL WHERE "
                + DbObject.CHILD_FEED_NAME + " = " + DbObject.FEED_NAME);
    }
    if (oldVersion <= 33) {
        Log.w(TAG, "Adding column 'nearby' to contact table.");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.NEARBY + " INTEGER DEFAULT 0");
    }
    if (oldVersion <= 34) {
        Log.w(TAG, "Adding column 'secret' to contact table.");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.SHARED_SECRET + " BLOB");

    }
    if (oldVersion <= 35) {
        Log.w(TAG, "Adding column 'last_updated' to group table.");
        db.execSQL("ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.LAST_UPDATED + " INTEGER");
    }
    if (oldVersion <= 36) {
        // Can't easily drop columns, but 'update_id' and 'is_child_feed' are dead columns.

        Log.w(TAG, "Adding column 'parent_feed_id' to group table.");
        db.execSQL(
                "ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.PARENT_FEED_ID + " INTEGER DEFAULT -1");

        Log.w(TAG, "Adding column 'last_object_id' to group table.");
        db.execSQL(
                "ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.LAST_OBJECT_ID + " INTEGER DEFAULT -1");
    }
    if (oldVersion <= 37) {
        // Can't easily drop columns, but 'update_id' and 'is_child_feed' are dead columns.

        Log.w(TAG, "Adding column 'num_unread' to group table.");
        db.execSQL("ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.NUM_UNREAD + " INTEGER DEFAULT 0");
    }
    if (oldVersion <= 38) {
        Log.w(TAG, "Adding column 'raw' to object table.");
        db.execSQL("ALTER TABLE " + DbObject.TABLE + " ADD COLUMN " + DbObject.RAW + " BLOB");
    }
    // sadly, we have to do this again because incoming voice obj's were not being split!
    if (oldVersion <= 50) {
        Log.w(TAG, "Converting voice and picture objs to raw.");

        Log.w(TAG, "Converting objs to raw.");
        Cursor c = db.query(DbObject.TABLE, new String[] { DbObject._ID },
                DbObject.TYPE + " = ? AND " + DbObject.RAW + " IS NULL", new String[] { PictureObj.TYPE }, null,
                null, null);
        ArrayList<Long> ids = new ArrayList<Long>();
        if (c.moveToFirst())
            do {
                ids.add(c.getLong(0));
            } while (c.moveToNext());
        c.close();
        DbEntryHandler dbh = DbObjects.forType(PictureObj.TYPE);
        for (Long id : ids) {
            c = db.query(DbObject.TABLE, new String[] { DbObject.JSON, DbObject.RAW }, DbObject._ID + " = ? ",
                    new String[] { String.valueOf(id.longValue()) }, null, null, null);
            if (c.moveToFirst())
                try {
                    String json = c.getString(0);
                    byte[] raw = c.getBlob(1);
                    c.close();
                    if (raw == null) {
                        Pair<JSONObject, byte[]> p = dbh.splitRaw(new JSONObject(json));
                        if (p != null) {
                            json = p.first.toString();
                            raw = p.second;
                            updateJsonAndRaw(db, id, json, raw);
                        }
                    }
                } catch (JSONException e) {
                }
            c.close();
        }
        c = db.query(DbObject.TABLE, new String[] { DbObject._ID },
                DbObject.TYPE + " = ? AND " + DbObject.RAW + " IS NULL", new String[] { VoiceObj.TYPE }, null,
                null, null);
        ids = new ArrayList<Long>();
        if (c.moveToFirst())
            do {
                ids.add(c.getLong(0));
            } while (c.moveToNext());
        c.close();
        dbh = DbObjects.forType(VoiceObj.TYPE);
        for (Long id : ids) {
            c = db.query(DbObject.TABLE, new String[] { DbObject.JSON, DbObject.RAW }, DbObject._ID + " = ? ",
                    new String[] { String.valueOf(id.longValue()) }, null, null, null);
            if (c.moveToFirst())
                try {
                    String json = c.getString(0);
                    byte[] raw = c.getBlob(1);
                    c.close();
                    if (raw == null) {
                        Pair<JSONObject, byte[]> p = dbh.splitRaw(new JSONObject(json));
                        if (p != null) {
                            json = p.first.toString();
                            raw = p.second;
                            updateJsonAndRaw(db, id, json, raw);
                        }
                    }
                } catch (JSONException e) {
                }
            c.close();
        }
    }
    if (oldVersion <= 40) {
        Log.w(TAG, "Adding column 'E' to object table.");
        db.execSQL("ALTER TABLE " + DbObject.TABLE + " ADD COLUMN " + DbObject.HASH + " INTEGER");
        createIndex(db, "INDEX", "objects_by_hash", DbObject.TABLE, DbObject.HASH);
        db.execSQL("DROP INDEX objects_by_encoded");
        db.delete(DbObject.TABLE, DbObject.TYPE + " = ?", new String[] { "profile" });
        db.delete(DbObject.TABLE, DbObject.TYPE + " = ?", new String[] { "profilepicture" });
        ContentValues cv = new ContentValues();
        cv.putNull(DbObject.ENCODED);
        db.update(DbObject.TABLE, cv, null, null);
    }
    if (oldVersion <= 41) {
        db.execSQL("DROP INDEX objects_by_sequence_id");
        db.execSQL("CREATE INDEX objects_by_sequence_id ON " + DbObject.TABLE + "(" + DbObject.CONTACT_ID + ", "
                + DbObject.FEED_NAME + ", " + DbObject.SEQUENCE_ID + ")");
    }
    //secret to life, etc
    if (oldVersion <= 42) {
        db.execSQL("DROP INDEX objects_by_creator_id");
        db.execSQL("CREATE INDEX objects_by_creator_id ON " + DbObject.TABLE + "(" + DbObject.CONTACT_ID + ", "
                + DbObject.SENT + ")");
    }

    if (oldVersion <= 44) {
        // oops.
        db.execSQL("DROP TABLE IF EXISTS " + DbRelation.TABLE);
        createRelationBaseTable(db);
    }
    if (oldVersion <= 45) {
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.LAST_OBJECT_ID + " INTEGER");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.LAST_UPDATED + " INTEGER");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.NUM_UNREAD + " INTEGER DEFAULT 0");
    }
    if (oldVersion <= 46) {
        db.execSQL("ALTER TABLE " + DbObject.TABLE + " ADD COLUMN " + DbObject.DELETED + " INTEGER DEFAULT 0");
    }
    if (oldVersion <= 47) {
        addRelationIndexes(db);
    }
    if (oldVersion <= 44) {
        createUserAttributesTable(db);
    }

    if (oldVersion <= 49) {
        if (oldVersion > 44) {
            db.execSQL("ALTER TABLE " + DbRelation.TABLE + " ADD COLUMN " + DbRelation.RELATION_TYPE + " TEXT");
            createIndex(db, "INDEX", "relations_by_type", DbRelation.TABLE, DbRelation.RELATION_TYPE);
        }
        db.execSQL("UPDATE " + DbRelation.TABLE + " SET " + DbRelation.RELATION_TYPE + " = 'parent'");
    }
    if (oldVersion <= 52) {
        Log.w(TAG, "Adding column 'about' to my_info table.");
        try {
            db.execSQL("ALTER TABLE " + MyInfo.TABLE + " ADD COLUMN " + MyInfo.ABOUT + " TEXT DEFAULT ''");
        } catch (Exception e) {
            // because of bad update, we just ignore the duplicate column error
        }
    }
    if (oldVersion <= 53) {
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.HIDDEN + " INTEGER DEFAULT 0");
    }
    if (oldVersion <= 55) {
        db.execSQL("ALTER TABLE " + DbObj.TABLE + " ADD COLUMN " + DbObj.COL_KEY_INT + " INTEGER");
    }
    if (oldVersion <= 56) {
        db.execSQL("DROP INDEX attrs_by_contact_id");
        createIndex(db, "INDEX", "attrs_by_contact_id", DbContactAttributes.TABLE,
                DbContactAttributes.CONTACT_ID);
    }
    if (oldVersion <= 57) {
        db.execSQL("ALTER TABLE " + DbObject.TABLE + " ADD COLUMN " + DbObject.LAST_MODIFIED_TIMESTAMP
                + " INTEGER");
        db.execSQL("UPDATE " + DbObject.TABLE + " SET " + DbObject.LAST_MODIFIED_TIMESTAMP + " = "
                + DbObject.TIMESTAMP);
    }
    if (oldVersion <= 58) {
        db.execSQL("ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.GROUP_TYPE + " TEXT DEFAULT 'group'");
        db.execSQL("UPDATE " + Group.TABLE + " SET " + Group.GROUP_TYPE + " = 'group'");
    }
    if (oldVersion <= 59) {
        createIndex(db, "INDEX", "objects_last_modified", DbObject.TABLE, DbObject.LAST_MODIFIED_TIMESTAMP);
    }
    if (oldVersion <= 60) {
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.PUBLIC_KEY_HASH_64
                + " INTEGER DEFAULT 0");
        createIndex(db, "INDEX", "contacts_by_pkp", Contact.TABLE, Contact.PUBLIC_KEY_HASH_64);
        Cursor peeps = db
                .rawQuery("SELECT " + Contact._ID + "," + Contact.PUBLIC_KEY + " FROM " + Contact.TABLE, null);
        peeps.moveToFirst();
        while (!peeps.isAfterLast()) {
            db.execSQL("UPDATE " + Contact.TABLE + " SET " + Contact.PUBLIC_KEY_HASH_64 + " = "
                    + hashPublicKey(peeps.getBlob(1)) + " WHERE " + Contact._ID + " = " + peeps.getLong(0));
            peeps.moveToNext();
        }
        peeps.close();
    }
    db.setVersion(VERSION);
}