Example usage for android.database.sqlite SQLiteDatabase close

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

Introduction

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

Prototype

public void close() 

Source Link

Document

Releases a reference to the object, closing the object if the last reference was released.

Usage

From source file:com.ideateam.plugin.DownloadDB.java

private void ReplaceDB() {

    Log.d(TAG, "..Get physical DB name and path. zipPath " + zipPath);

    String dbPath = zipPath.substring(0, zipPath.lastIndexOf("/")) + "/app_database/";
    SQLiteDatabase master_db = null;
    String field = "path";

    Log.d(TAG, dbPath + "Databases.db");
    File file = new File(dbPath + "Databases.db");

    if (!file.exists()) {

        Log.d(TAG, "Databases.db not found");
        field = "id";
        dbPath = zipPath.substring(0, zipPath.lastIndexOf("/")) + "/app_webview/databases/";
    }//from   w ww .ja  va2  s .  c o m

    try {
        master_db = SQLiteDatabase.openDatabase(dbPath + "Databases.db", null, SQLiteDatabase.OPEN_READONLY);
    } catch (Exception e) {

    }

    if (master_db != null) {
        Cursor c = master_db.rawQuery("SELECT origin, " + field + " FROM Databases WHERE name='" + dbName + "'",
                null);
        c.moveToFirst();

        cordovaDBPath = dbPath + c.getString(0) + "/";
        cordovaDBName = c.getString(1);

        if (field == "id") {
            field += ".db";
        }

        c.close();
        master_db.close();

        Log.d(TAG, ": " + cordovaDBPath + cordovaDBName);

    }
}

From source file:com.appmanager.parimal.activity.MainActivity.java

private void loadApps() {

    manager = this.getPackageManager();
    apps = new ArrayList<AppDetail>();

    Intent i = new Intent(Intent.ACTION_MAIN, null);
    i.addCategory(Intent.CATEGORY_LAUNCHER);
    AppEntryDBHelper mDbHelper = new AppEntryDBHelper(getApplicationContext());
    SQLiteDatabase db = mDbHelper.getWritableDatabase();
    List<ResolveInfo> availableActivities = manager.queryIntentActivities(i, 0);
    for (ResolveInfo ri : availableActivities) {
        if (!ri.activityInfo.packageName.matches("com.appmanager.parimal")) {
            AppDetail app = new AppDetail();
            app.setLabel(ri.loadLabel(manager));
            app.setName(ri.activityInfo.packageName);
            app.setIcon(ri.activityInfo.loadIcon(manager));
            apps.add(app);/*  w w w .  j  a v  a 2s .com*/
            ContentValues values = new ContentValues();
            values.put(AppsReaderContract.AppEntry.COLUMN_APP_NAME, ri.loadLabel(manager).toString());
            values.put(AppsReaderContract.AppEntry.COLUMN_APP_PACKAGE, ri.activityInfo.packageName);
            values.put(AppsReaderContract.AppEntry.COLUMN_APP_CATEGORY, "Uncategorized");
            values.put(AppsReaderContract.AppEntry.COLUMN_APP_PIN, "0000");
            values.put(AppsReaderContract.AppEntry.COLUMN_APP_PIN_USE, "false");
            values.put(AppsReaderContract.AppEntry.COLUMN_APP_USAGE, "0");

            long newRowId;
            newRowId = db.insert(AppsReaderContract.AppEntry.TABLE_NAME, null, values);
        }

    }
    db.close();
}

From source file:ru.gkpromtech.exhibition.db.Table.java

public <F extends Entity, S extends Entity> List<Pair<F, S>> selectLinked(Class<F> f, Class<S> s,
        String selection, String[] selectionArgs, String orderBy)
        throws InvalidClassException, IllegalAccessException, InstantiationException {

    if (mFks.length != 2)
        throw new InvalidClassException("Entity " + mEntityClass.getName() + " is not a link");

    List<Pair<F, S>> result = new ArrayList<>();
    FkInfo fk1;//from  w w  w . j  av  a2s. c om
    FkInfo fk2;

    if (mFks[0].entityClass.equals(f) && mFks[1].entityClass.equals(s)) {
        fk1 = mFks[0];
        fk2 = mFks[1];
    } else if (mFks[1].entityClass.equals(f) && mFks[0].entityClass.equals(s)) {
        //     ?   ?? ?
        fk1 = mFks[1];
        fk2 = mFks[0];
    } else {
        throw new InvalidClassException("Invalid classes passed as arguments");
    }

    Table<F> table1 = ((DbHelper) mSqlHelper).getTableFor(f);
    Table<S> table2 = ((DbHelper) mSqlHelper).getTableFor(s);

    StringBuilder query = new StringBuilder();
    for (String column : table1.mColumns) {
        query.append(",f.").append(column);
    }
    for (String column : table2.mColumns)
        query.append(",s.").append(column);
    query.replace(0, 1, "SELECT ");

    query.append("\nFROM ").append(mTableName).append(" t\nJOIN ").append(table1.mTableName).append(" f ON f.")
            .append(fk1.fkName).append(" = t.").append(fk1.fieldName).append("\nJOIN ")
            .append(table2.mTableName).append(" s ON s.").append(fk2.fkName).append(" = t.")
            .append(fk2.fieldName);
    if (selection != null)
        query.append("\nWHERE ").append(selection);
    if (orderBy != null)
        query.append("\nORDER BY ").append(orderBy);

    String queryString = query.toString();
    if (BuildConfig.DEBUG)
        Log.d("PP", queryString);

    SQLiteDatabase db = mSqlHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery(queryString, selectionArgs);

    //noinspection TryFinallyCanBeTryWithResources
    try {
        while (cursor.moveToNext()) {
            F entity1 = f.newInstance();
            S entity2 = s.newInstance();
            for (int i = 0; i < table1.mFields.length; ++i)
                fillFieldValue(table1.mType[i], table1.mFields[i], entity1, cursor, i);
            for (int i = 0; i < table2.mFields.length; ++i)
                fillFieldValue(table2.mType[i], table2.mFields[i], entity2, cursor, table1.mFields.length + i);
            result.add(new Pair<>(entity1, entity2));
        }
    } finally {
        cursor.close();
        db.close();
    }

    return result;
}

From source file:net.potterpcs.recipebook.RecipeData.java

public void deleteRecipe(long rid) {
    synchronized (DB_LOCK) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        try {/*from w w w.ja  v  a2s .  co m*/
            db.delete(INGREDIENTS_TABLE, IT_RECIPE_ID + " = ?", new String[] { Long.toString(rid) });
            db.delete(DIRECTIONS_TABLE, DT_RECIPE_ID + " = ?", new String[] { Long.toString(rid) });
            db.delete(TAGS_TABLE, TT_RECIPE_ID + " = ?", new String[] { Long.toString(rid) });
            db.delete(RECIPES_TABLE, RT_ID + " = ?", new String[] { Long.toString(rid) });
        } finally {
            db.close();
        }
    }
}

From source file:com.maxwen.wallpaper.board.databases.Database.java

public Set<Wallpaper> getWallpapersNewer(long millis) {
    Set<Wallpaper> wallpapers = new HashSet<>();
    SQLiteDatabase db = this.getReadableDatabase();
    StringBuilder CONDITION = new StringBuilder();
    List<String> selection = new ArrayList<>();
    CONDITION.append(KEY_ADDED_ON + " > ?");
    selection.add(String.valueOf(millis));
    Cursor cursor = db.query(TABLE_WALLPAPERS, null, CONDITION.toString(),
            selection.toArray(new String[selection.size()]), null, null, KEY_CATEGORY);
    if (cursor.moveToFirst()) {
        do {//from   w  w w  .  j a va2  s.  co m
            Wallpaper wallpaper = new Wallpaper(cursor.getInt(0), cursor.getString(1), cursor.getString(2),
                    cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getInt(6) == 1,
                    cursor.getLong(7));
            wallpapers.add(wallpaper);
        } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return wallpapers;
}

From source file:com.openerp.orm.ORM.java

/**
 * Creates the.//from   ww  w . j av  a  2  s  .  c om
 * 
 * @param dbHelper
 *            the db helper
 * @param values
 *            the values
 * @return the int
 */
public int create(BaseDBHelper dbHelper, ContentValues data_values) {
    int newId = 0;
    ContentValues values = new ContentValues();
    if (data_values.containsKey("id")) {
        newId = data_values.getAsInteger("id");
    } else {
        newId = createRecordOnserver(dbHelper, data_values);
        data_values.put("id", newId);
    }

    for (Fields field : dbHelper.getColumns()) {
        values.put(field.getName(), data_values.getAsString(field.getName()));
    }

    values.put("oea_name", OpenERPAccountManager.currentUser(context).getAndroidName());

    // Handling Many2Many Records
    HashMap<String, Object> many2manycols = dbHelper.getMany2ManyColumns();
    for (String key : many2manycols.keySet()) {
        try {
            JSONArray m2mArray = new JSONArray(values.getAsString(key));
            Many2Many m2m = (Many2Many) many2manycols.get(key);
            createM2MRecords(values.getAsString("id"), m2mArray, key, dbHelper, m2m, values);
        } catch (Exception e) {
        }
        values.remove(key);
    }

    // Handling Many2One Record
    HashMap<String, Object> many2onecols = dbHelper.getMany2OneColumns();
    for (String key : many2onecols.keySet()) {
        try {
            if (!values.getAsString(key).equals("false")) {
                JSONArray m2oArray = new JSONArray(values.getAsString(key));
                values.put(key, many2oneRecord(m2oArray));
                List<Integer> list = new ArrayList<Integer>();
                int m2o_id = Integer.parseInt(many2oneRecord(m2oArray));
                list.add(m2o_id);
                BaseDBHelper m2oDb = ((Many2One) many2onecols.get(key)).getM2OObject();
                if (!m2oDb.hasRecord(m2oDb, m2o_id)) {
                    oe_obj.syncReferenceTables(m2oDb, list, false);
                }
            }
        } catch (Exception e) {
        }

    }

    SQLiteDatabase db = getWritableDatabase();
    db.insert(modelToTable(dbHelper.getModelName()), null, values);
    db.close();
    return newId;
}

From source file:com.raspi.chatapp.util.storage.MessageHistory.java

public void addChat(String buddyId, String name) {
    SQLiteDatabase db = mDbHelper.getWritableDatabase();
    int index = buddyId.indexOf('@');
    if (index >= 0) {
        buddyId = buddyId.substring(0, index);
    }/*w  w w  .  ja  v  a  2  s.  c o m*/
    index = name.indexOf('@');
    if (index >= 0) {
        name = name.substring(0, index);
    }
    ContentValues values = new ContentValues();
    values.put(MessageHistoryContract.ChatEntry.COLUMN_NAME_BUDDY_ID, buddyId);
    values.put(MessageHistoryContract.ChatEntry.COLUMN_NAME_NAME, name);
    try {
        db.insertOrThrow(MessageHistoryContract.ChatEntry.TABLE_NAME_ALL_CHATS,
                MessageHistoryContract.ChatEntry._ID, values);
    } catch (SQLException e) {
        Log.d("DATABASE", "Couldn't insert --> is already inserted.");
        return;
    } catch (Exception e) {
        Log.e("ERROR", "got an error while inserting a row into "
                + MessageHistoryContract.ChatEntry.TABLE_NAME_ALL_CHATS);
        return;
    }
    mDbHelper.createMessageTable(buddyId);
    db.close();
}

From source file:com.openerp.orm.ORM.java

/**
 * Creates the many2many records for a column.
 * //  w  ww .ja  va  2  s  .c  o m
 * @param id
 *            the id
 * @param values
 *            the values
 * @param key
 *            the key
 * @param dbHelper
 *            the db helper
 * @param m2m
 *            the m2m
 * @param rootRow
 *            the root row
 */
private void createM2MRecords(String id, JSONArray values, String key, BaseDBHelper dbHelper, Many2Many m2m,
        ContentValues rootRow) {
    String table1 = modelToTable(dbHelper.getModelName());
    String table2 = "";
    BaseDBHelper tbl2Obj = null;
    if (m2m.isM2MObject()) {
        tbl2Obj = (BaseDBHelper) m2m.getM2mObject();
        table2 = modelToTable(tbl2Obj.getModelName());
    } else {
        table2 = modelToTable(m2m.getModel_name());
    }
    String rel_table = table1 + "_" + table2 + "_rel";
    String col1 = table1 + "_id";
    String col2 = table2 + "_id";
    String col3 = "oea_name";

    // Temp dummy helper
    BaseDBHelper newDb = generateM2MHelper(dbHelper, m2m);

    int loop_val = (values.length() > 10) ? 10 : values.length();
    List<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < loop_val; i++) {
        try {
            int row_id = 0;

            if (values.get(i) instanceof JSONArray) {
                row_id = values.getJSONArray(i).getInt(0);
            }
            if (values.get(i) instanceof JSONObject) {
                JSONObject obj = (JSONObject) values.get(i);
                if (obj.has("id")) {
                    row_id = obj.getInt("id");
                }
            }
            if (values.get(i) instanceof Integer) {
                row_id = values.getInt(i);
            }
            ContentValues m2mvals = new ContentValues();
            String android_name = OpenERPAccountManager.currentUser(context).getAndroidName();
            m2mvals.put(col1, id);
            m2mvals.put(col2, row_id);
            m2mvals.put(col3, android_name);
            int res = Integer.parseInt(
                    search(newDb, new String[] { col1 + " = ?", "AND", col2 + "= ?", "AND", col3 + " = ?" },
                            new String[] { id, row_id + "", android_name }).get("total").toString());
            if (res == 0) {
                SQLiteDatabase db = getWritableDatabase();
                db.insert(rel_table, null, m2mvals);
                db.close();
            }
            if (tbl2Obj != null && !tbl2Obj.hasRecord(tbl2Obj, row_id)) {
                list.add(row_id);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if (list.size() > 0) {
        oe_obj.syncReferenceTables(tbl2Obj, list, false);
    }
}

From source file:com.openerp.orm.ORM.java

public boolean delete(BaseDBHelper db, int id, boolean fromLocal) {
    try {/*  w ww  .j a  v  a2s  .co  m*/
        if (!fromLocal) {

            if (oe_obj.unlink(db.getModelName(), id)) {
                SQLiteDatabase sdb = getWritableDatabase();
                String where = "id = " + id;
                sdb.delete(modelToTable(db.getModelName()), where, null);
                sdb.close();
                return true;
            }
        } else {
            SQLiteDatabase sdb = getWritableDatabase();
            String where = "id = " + id;
            sdb.delete(modelToTable(db.getModelName()), where, null);
            sdb.close();
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:com.renjunzheng.vendingmachine.MyGcmListenerService.java

private void updateStorageInfo(String updated_info) {

    //as far as I think, this should receive all the information about all four products
    //so whenever we substitute some product, the original one will not be kept in there
    //or we need some level of delete functionality? or do we need a sync adapter?
    //is this a good idea? what happens when the number of item increases?

    try {//ww w  . j av a 2 s .  com
        DataDbHelper dbHelper = new DataDbHelper(this);
        SQLiteDatabase database = dbHelper.getWritableDatabase();

        database.delete(DataContract.ItemEntry.TABLE_NAME, null, null);
        database.execSQL(
                "DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + DataContract.ItemEntry.TABLE_NAME + "'");

        //get this valueArray from the string
        JSONArray valueArray = new JSONArray(updated_info);
        for (int lc = 0; lc < valueArray.length(); ++lc) {
            JSONObject infoJson = valueArray.getJSONObject(lc);
            //everything is the same as following code
            ContentValues newValues = new ContentValues();
            newValues.put(DataContract.ItemEntry.COLUMN_REMAINING_NUM, infoJson.getInt("remaining_num"));
            newValues.put(DataContract.ItemEntry.COLUMN_SHORT_DESC, infoJson.getString("short_desc"));
            newValues.put(DataContract.ItemEntry.COLUMN_PRICE, infoJson.getString("item_price"));
            newValues.put(DataContract.ItemEntry.COLUMN_ITEM_NAME, infoJson.getString("item_name"));
            Uri returnedUri = getContentResolver().insert(DataContract.ItemEntry.CONTENT_URI, newValues);
            Log.i(TAG, "inserted row num " + ContentUris.parseId(returnedUri));
        }

        database.close();
        dbHelper.close();
    } catch (JSONException e) {
        Log.e(TAG, "error when parsing Json");
    }
}