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.almarsoft.GroundhogReader.lib.DBUtils.java

public static void logSentMessage(String msgId, String group, Context context) {
    int groupid = getGroupIdFromName(group, context);

    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbwrite = db.getWritableDatabase();

    /* Check first that the number of logged messages for this group is not greater than the 
    * limit impossed per group, because if it's greater we must delete number-limit older logs
    * until the table only has the limit. This is done this way because on the MessageList a set
    * is built with the post messages from that group, and then every loaded message's msgId is checked 
    * to see if it's in the set (to check for replies to our messages), so allowing it to grow too much
    * could make the MessageView slow//  w w  w.  j  av a 2  s  .c  om
    */

    Cursor c = dbwrite.rawQuery(
            "SELECT _id FROM sent_posts_log WHERE subscribed_group_id=" + groupid + " ORDER BY _id", null);
    int count = c.getCount();
    int toKill = count - UsenetConstants.SENT_POSTS_LOG_LIMIT_PER_GROUP;
    int kennyId;

    if (toKill > 0) {
        // Delete some more than needed so we don't have to do this on every post sent
        toKill += UsenetConstants.SENT_POST_KILL_ADITIONAL;
        c.moveToFirst();

        for (int i = 0; i < toKill; i++) {
            kennyId = c.getInt(0);
            dbwrite.execSQL("DELETE FROM sent_posts_log WHERE _id=" + kennyId);
            c.moveToNext();
        }
    }
    c.close();

    // Now we have room for sure, insert the log
    ContentValues cv = new ContentValues(2);
    cv.put("server_article_id", msgId);
    cv.put("subscribed_group_id", groupid);
    dbwrite.insert("sent_posts_log", null, cv);

    dbwrite.close();
    db.close();
}

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

@Nullable
public List<Object> getWallpapersOfCatgegoryUnified(String category) {
    List<Object> wallpapers = new ArrayList<>();
    List<String> selection = new ArrayList<>();
    Map<String, Category> categoryMap = getCategoryMap();

    StringBuilder CONDITION = new StringBuilder();
    CONDITION.append("LOWER(").append(KEY_CATEGORY).append(")").append(" LIKE ?");
    selection.add("%" + category.toLowerCase(Locale.getDefault()) + "%");

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(TABLE_WALLPAPERS, null, CONDITION.toString(),
            selection.toArray(new String[selection.size()]), null, null, null, null);
    if (cursor.moveToFirst()) {
        Category c = new Category(0, category, categoryMap.get(category).getThumbUrl(), false);
        wallpapers.add(c);//from  www.  java2 s  . com
        int numWallpapers = 0;
        do {
            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);
            numWallpapers++;
        } while (cursor.moveToNext());
        c.setNumWallpapers(numWallpapers);
    }
    cursor.close();
    db.close();
    return wallpapers;
}

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

public Set<Wallpaper> getWallpapersNewer(long millis, Set<String> categories) {
    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  av  a 2s . c o 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);
            categories.add(cursor.getString(5));
        } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return wallpapers;
}

From source file:com.rs.TCOfflineStatementCollection.java

/**
 * get all statements that haven't been posted
 * @param limit// www.j a v a 2  s .  com
 * @return List of LocalStatementsItem
 */
List<LocalStatementsItem> getUnsentStatements(int limit) {
    List<LocalStatementsItem> statementArray = new ArrayList<LocalStatementsItem>();

    Cursor cursor;
    SQLiteDatabase database;
    TCLocalStorageDatabaseOpenHelper dbHelper;
    dbHelper = new TCLocalStorageDatabaseOpenHelper(appContext);
    database = dbHelper.getWritableDatabase();

    String select = LocalStatements.POSTED_DATE + "=" + "\'" + "0" + "\'";

    cursor = database.query(TCOfflineDataManager.LOCAL_STATEMENT_TABLE_NAME, null, select, null, null, null,
            LocalStatements.CREATE_DATE + " ASC", Integer.toString(limit)); //query for all the unposted statements

    cursor.moveToFirst(); //go to the beginning of the query and then loop through all the packages, adding them to the return List
    while (!cursor.isAfterLast()) {
        LocalStatementsItem thisPackage = new LocalStatementsItem();
        thisPackage.id = cursor.getInt(0);
        thisPackage.statementId = cursor.getString(cursor.getColumnIndex("statementId"));
        thisPackage.statementJson = cursor.getString(cursor.getColumnIndex("statementJson"));
        thisPackage.createDate = cursor.getLong(cursor.getColumnIndex("createDate"));
        thisPackage.postedDate = cursor.getLong(cursor.getColumnIndex("postedDate"));
        thisPackage.querystring = cursor.getString(cursor.getColumnIndex("querystring"));

        statementArray.add(thisPackage);
        cursor.moveToNext();
    }

    cursor.close();
    database.close();

    return statementArray;
}

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

/**
 * Clean user records./*from w  w w .  j a v  a 2s . c  o m*/
 * 
 * @param user_name
 *            the user_name
 * @return true, if successful
 */
public boolean cleanUserRecords(String user_name) {
    SQLiteDatabase db = getWritableDatabase();
    for (String table : databaseTables()) {
        String sql = "DELETE FROM " + table + " where oea_name = '" + user_name + "'";
        db.execSQL(sql);
    }
    db.close();
    return true;

}

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

public long addMessage(String chatId, String buddyId, String type, String content, String url, String status,
        long othersId) {
    //Log.d("DATABASE", "Adding a message");
    SQLiteDatabase db = mDbHelper.getWritableDatabase();
    //remove everything after @ if it exists
    int index = buddyId.indexOf('@');
    if (index >= 0) {
        buddyId = buddyId.substring(0, index);
    }/*from   ww  w.j a  v  a  2 s. c  o  m*/
    index = chatId.indexOf('@');
    if (index >= 0) {
        chatId = chatId.substring(0, index);
    }

    ContentValues values = new ContentValues();
    values.put(MessageHistoryContract.MessageEntry.COLUMN_NAME_BUDDY_ID, buddyId);
    values.put(MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TYPE, type);
    values.put(MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_CONTENT, content);
    values.put(MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_URL, url);
    values.put(MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_STATUS, status);
    values.put(MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TIMESTAMP, new Date().getTime());
    values.put(MessageHistoryContract.MessageEntry.COLUMN_NAME_OTHERS_ID, othersId);
    long result = db.insert(chatId, MessageHistoryContract.MessageEntry._ID, values);
    db.close();
    return result;
}

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

/**
 * Execute query.//  ww w .  j a  v  a 2  s . co m
 * 
 * @param dbHelper
 *            the db helper
 * @param where
 *            the where
 * @return the list
 */
private List<HashMap<String, Object>> executeQuery(BaseDBHelper dbHelper, String where) {
    List<String> cols = new ArrayList<String>();
    for (Fields col : dbHelper.getColumns()) {
        if (!(col.getType() instanceof Many2Many)) {
            cols.add(col.getName());
        }
    }
    String columns[] = cols.toArray(new String[cols.size()]);
    SQLiteDatabase db = getWritableDatabase();
    Cursor cursor = db.query(modelToTable(dbHelper.getModelName()), columns, where, null, null, null, null);
    List<HashMap<String, Object>> data = getResult(dbHelper, null, cursor);
    db.close();
    cursor.close();
    return data;
}

From source file:net.smart_json_database.JSONDatabase.java

public boolean delete(JSONEntity entity) {
    boolean returnValue = false;
    if (entity.getUid() == -1) {
        return returnValue;
    }/* w ww  .ja  v  a 2s.  c  om*/
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    try {
        db.beginTransaction();
        String[] params = new String[] { "" + entity.getUid() };
        db.delete(TABLE_REL_JSON_DATA_JSON_DATA, "from_id = ?", params);
        db.delete(TABLE_REL_JSON_DATA_JSON_DATA, "to_id = ?", params);
        db.delete(TABLE_REL_TAG_JSON_DATA, "to_id = ?", params);
        db.delete(TABLE_JSON_DATA, "json_uid = ?", params);
        db.setTransactionSuccessful();
        notifyListenersOnEntityChange(entity.getUid(), IDatabaseChangeListener.CHANGETYPE_DELETE);
        returnValue = true;
    } catch (Exception e) {
        returnValue = false;
    } finally {
        db.endTransaction();
        db.close();
    }

    return returnValue;
}

From source file:net.olejon.mdapp.SubstanceActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Intent/*from   ww  w . j a v a  2 s . c o m*/
    final Intent intent = getIntent();

    final long substanceId = intent.getLongExtra("id", 0);

    // Open database
    SQLiteDatabase sqLiteDatabase = new SlDataSQLiteHelper(mContext).getReadableDatabase();

    String[] queryColumns = { SlDataSQLiteHelper.SUBSTANCES_COLUMN_ATC_CODE,
            SlDataSQLiteHelper.SUBSTANCES_COLUMN_NAME };
    Cursor cursor = sqLiteDatabase.query(SlDataSQLiteHelper.TABLE_SUBSTANCES, queryColumns,
            SlDataSQLiteHelper.SUBSTANCES_COLUMN_ID + " = " + substanceId, null, null, null, null);

    if (cursor.moveToFirst()) {
        // Substance
        substanceAtcCode = cursor
                .getString(cursor.getColumnIndexOrThrow(SlDataSQLiteHelper.SUBSTANCES_COLUMN_ATC_CODE));
        substanceName = cursor
                .getString(cursor.getColumnIndexOrThrow(SlDataSQLiteHelper.SUBSTANCES_COLUMN_NAME));

        // Layout
        setContentView(R.layout.activity_substance);

        // Toolbar
        final Toolbar toolbar = (Toolbar) findViewById(R.id.substance_toolbar);
        toolbar.setTitle(substanceName);

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // ATC code
        TextView atcCodeTextView = (TextView) findViewById(R.id.substance_atc_code);
        atcCodeTextView.setText(substanceAtcCode);

        // List
        mListView = (ListView) findViewById(R.id.substance_list);
    }

    // Close database
    cursor.close();
    sqLiteDatabase.close();
}

From source file:com.bufarini.reminders.AlarmReceiver.java

private void setReminders(Context context, String accountName) {
    RemindersDbHelper dbHelper = new RemindersDbHelper(context);
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery(String.format("select %s, %s, %s, %s, %s, %s, %s from %s where %s=\"%s\"",
            Tables.COMPLETED, Tables.REMINDER_DATE, Tables.REMINDER_INTERVAL, Tables.ID, Tables.DUE_DATE,
            Tables.LIST_ID, Tables.TITLE, Tables.TASK_TABLE, Tables.ACCOUNT_NAME, accountName), null);
    try {/*from   w ww.j av  a2 s. c o m*/
        while (cursor.moveToNext()) {
            boolean notCompleted = cursor.getLong(cursor.getColumnIndexOrThrow(Tables.COMPLETED)) == 0;
            if (notCompleted) {
                long reminderDate = cursor.getLong(cursor.getColumnIndexOrThrow(Tables.REMINDER_DATE));
                long reminderInterval = cursor.getLong(cursor.getColumnIndexOrThrow(Tables.REMINDER_INTERVAL));
                if (reminderDate > System.currentTimeMillis() || reminderInterval > 0) {
                    long id = cursor.getLong(cursor.getColumnIndexOrThrow(Tables.ID));
                    String title = cursor.getString(cursor.getColumnIndexOrThrow(Tables.TITLE));
                    long dueDate = cursor.getLong(cursor.getColumnIndexOrThrow(Tables.DUE_DATE));
                    long listId = cursor.getLong(cursor.getColumnIndexOrThrow(Tables.LIST_ID));
                    NotificationUtils.setReminder(context, id, title, dueDate, listId, reminderDate,
                            reminderInterval);
                }
            }
        }
    } finally {
        cursor.close();
        db.close();
    }
}