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.example.shutapp.DatabaseHandler.java

/**
 * Adds a chatroom to the database./*from   ww w.  java 2 s.co  m*/
 * @param chatroom
 */
public void addChatroom(Chatroom chatroom) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, chatroom.getName()); // Chatroom Name
    values.put(KEY_LATITUDE, chatroom.getLatitude()); // Chatroom Latitude
    values.put(KEY_LONGITUDE, chatroom.getLongitude()); // Chatroom Longitude
    values.put(KEY_RADIUS, chatroom.getRadius()); // Chatroom Radius

    // Inserting Row
    db.insert(TABLE_CHATROOMS, null, values);
    db.close(); // Closing database connection
}

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

private void search(final String string, boolean cache) {
    try {//from www  .j a  va2 s. c  o m
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);

        String apiUri = getString(R.string.project_website_uri) + "api/1/poisonings/?search="
                + URLEncoder.encode(string.toLowerCase(), "utf-8");

        if (!cache)
            requestQueue.getCache().remove(apiUri);

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(apiUri, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                mProgressBar.setVisibility(View.GONE);
                mSwipeRefreshLayout.setRefreshing(false);

                if (response.length() == 0) {
                    mSwipeRefreshLayout.setVisibility(View.GONE);
                    mNoPoisoningsLayout.setVisibility(View.VISIBLE);
                } else {
                    if (mTools.isTablet()) {
                        int spanCount = (response.length() == 1) ? 1 : 2;

                        mRecyclerView.setLayoutManager(
                                new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL));
                    }

                    mRecyclerView.setAdapter(new PoisoningsCardsAdapter(mContext, response));

                    ContentValues contentValues = new ContentValues();
                    contentValues.put(PoisoningsSQLiteHelper.COLUMN_STRING, string);

                    SQLiteDatabase sqLiteDatabase = new PoisoningsSQLiteHelper(mContext).getWritableDatabase();

                    sqLiteDatabase.delete(PoisoningsSQLiteHelper.TABLE, PoisoningsSQLiteHelper.COLUMN_STRING
                            + " = " + mTools.sqe(string) + " COLLATE NOCASE", null);
                    sqLiteDatabase.insert(PoisoningsSQLiteHelper.TABLE, null, contentValues);

                    sqLiteDatabase.close();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mProgressBar.setVisibility(View.GONE);
                mSwipeRefreshLayout.setRefreshing(false);

                mTools.showToast(getString(R.string.poisonings_cards_something_went_wrong), 1);

                finish();

                Log.e("PoisoningsCardsActivity", error.toString());
            }
        });

        jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        requestQueue.add(jsonArrayRequest);
    } catch (Exception e) {
        Log.e("PoisoningsCardsActivity", Log.getStackTraceString(e));
    }
}

From source file:com.snt.bt.recon.database.DBHandler.java

public <T> int dbSyncCount(Class<T> cl) throws InstantiationException, IllegalAccessException {
    T inst = cl.newInstance();/*  w  ww. jav a 2s.co  m*/
    String selectQuery = "";

    if (inst instanceof Trip)
        selectQuery = "SELECT * FROM " + TABLE_TRIPS + " where " + KEY_UPLOAD_STATUS + " = '" + "no" + "' or "
                + KEY_UPLOAD_STATUS + " = '" + "partial" + "'";

    else if (inst instanceof GPSLocation)
        selectQuery = "SELECT  * FROM " + TABLE_LOCATIONS + " where " + KEY_UPLOAD_STATUS + " = '" + "no" + "'";

    else if (inst instanceof BluetoothClassicEntry)
        selectQuery = "SELECT  * FROM " + TABLE_BC + " where " + KEY_UPLOAD_STATUS + " = '" + "no" + "'";

    else if (inst instanceof BluetoothLowEnergyEntry)
        selectQuery = "SELECT  * FROM " + TABLE_BLE + " where " + KEY_UPLOAD_STATUS + " = '" + "no" + "'";

    int count = 0;
    SQLiteDatabase database = this.getWritableDatabase();
    Cursor cursor = database.rawQuery(selectQuery, null);
    count = cursor.getCount();
    cursor.close();
    database.close();
    return count;
}

From source file:github.popeen.dsub.util.SongDBHandler.java

public synchronized Pair<Integer, String> getIdFromPath(String path) {
    SQLiteDatabase db = this.getReadableDatabase();

    String[] columns = { SONGS_SERVER_KEY, SONGS_SERVER_ID };
    Cursor cursor = db.query(TABLE_SONGS, columns, SONGS_COMPLETE_PATH + " = ?", new String[] { path }, null,
            null, SONGS_LAST_PLAYED + " DESC", null);

    try {//ww  w  . ja  v a  2s. com
        cursor.moveToFirst();
        return new Pair(cursor.getInt(0), cursor.getString(1));
    } catch (Exception e) {
        return null;
    } finally {
        db.close();
    }
}

From source file:org.akop.crosswords.Storage.java

public boolean moveTo(long folderId, long... puzzleIds) {
    if (puzzleIds.length < 1) {
        return false;
    }// w w  w .j  a v a 2 s .c o  m

    StringBuilder whereBuilder = new StringBuilder();
    whereBuilder.append(Puzzle._ID);
    whereBuilder.append(" IN (");
    for (int i = 0, n = puzzleIds.length - 1; i <= n; i++) {
        whereBuilder.append(puzzleIds[i]);
        if (i < n) {
            whereBuilder.append(",");
        }
    }
    whereBuilder.append(")");

    StorageHelper helper = getHelper();
    SQLiteDatabase db = helper.getWritableDatabase();
    int rowsUpdated = 0;

    ContentValues cv = new ContentValues();
    cv.put(Puzzle.FOLDER_ID, folderId);

    try {
        rowsUpdated += db.update(Puzzle.TABLE, cv, whereBuilder.toString(), null);
    } finally {
        db.close();
    }

    if (rowsUpdated > 0) {
        Intent outgoing = new Intent(ACTION_PUZZLE_CHANGE);
        sendLocalBroadcast(outgoing);
    }

    Crosswords.logv("Moved %d puzzles to folder id %d", rowsUpdated, folderId);

    return rowsUpdated > 0;
}

From source file:com.dpcsoftware.mn.EditGroups.java

private void renderGroups() {
    SQLiteDatabase db = DatabaseHelper.quickDb(this, 1);
    Cursor c = db.rawQuery("SELECT " + Db.Table3._ID + "," + Db.Table3.COLUMN_NGRUPO + " FROM "
            + Db.Table3.TABLE_NAME + " ORDER BY " + Db.Table3.COLUMN_NGRUPO + " ASC", null);
    if (adapter == null) {
        adapter = new GroupsAdapter(this, c);
        lv.setAdapter(adapter);//w w w  . j a  v a 2  s . com
        setContentView(lv);
    } else {
        adapter.swapCursor(c);
        adapter.notifyDataSetChanged();
    }
    db.close();
}

From source file:com.armtimes.activities.SingleArticlePreviewActivity.java

@Override
public void onSingleArticleDownloadCompleted(final ArticleInfo articleInfo) {

    if (progressDialog != null) {
        progressDialog.dismissAllowingStateLoss();
        progressDialog = null;/*from   w w w .  j  a va  2 s  . co m*/
    }

    // Finish current activity if Description or Title
    // are missing, missing of image is not a case to
    // finish activity.
    if (articleInfo == null) {
        Toast.makeText(getApplicationContext(), R.string.cant_show_news_data_missing, Toast.LENGTH_LONG).show();
        setResult(Activity.RESULT_CANCELED);
        finish();
        return;
    }

    // Title comes from the Database and it should be there
    // as it is downloaded at first phase from RSS.
    String title = getIntent().getStringExtra(EXTRA_TITLE);
    if (title == null || title.isEmpty()) {
        Toast.makeText(getApplicationContext(), R.string.cant_show_news_data_missing, Toast.LENGTH_LONG).show();
        setResult(Activity.RESULT_CANCELED);
        finish();
        return;
    }

    String description = articleInfo.getDescription();
    if (description == null || description.isEmpty()) {
        Toast.makeText(getApplicationContext(), R.string.cant_show_news_data_missing, Toast.LENGTH_LONG).show();
        setResult(Activity.RESULT_CANCELED);
        finish();
        return;
    }

    // If news article information was successfully downloaded,
    // and shown to the user - update database by setting given
    // news item read state to TRUE.
    try {
        // Get current table name, in which information for given
        // article must be updated.
        final String table = getIntent().getStringExtra(EXTRA_CATEGORY).toUpperCase();
        // Create Database helper object.
        NewsDatabaseHelper helper = new NewsDatabaseHelper(getApplicationContext());
        SQLiteDatabase database = helper.getWritableDatabase();
        // Create data which must be updated.
        ContentValues cv = new ContentValues();
        cv.put(NewsContract.COL_NAME_NEWS_IS_READ, 1);
        // Update appropriate field in database.
        database.update(table, cv, String.format("%s=\"%s\"", NewsContract.COL_NAME_NEWS_URL, articleInfo.url),
                null);
        // Close database
        database.close();
        helper.close();
    } catch (Exception ex) {
        Logger.e(TAG, "Exception occurs while trying to Update database!");
    }

    // Set layout Visible.
    layoutMain.setVisibility(View.VISIBLE);

    textTitle.setText(title.trim());
    textDescription.setText(Html.fromHtml(articleInfo.getDescription()));

    // Try to set image if it exists.
    InputStream is = null;
    try {
        is = new FileInputStream(new File(articleInfo.getMainImagePath()));
        imageBanner.setImageBitmap(BitmapFactory.decodeStream(is));
        imageBanner.setScaleType(ImageView.ScaleType.CENTER_CROP);
    } catch (IOException ex) {
        imageBanner.setScaleType(ImageView.ScaleType.CENTER);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ex) {
                Logger.e(TAG, "Error occurs while trying to close Banner Image Stream.");
            }
        }
    }

    setResult(Activity.RESULT_OK);
}

From source file:github.popeen.dsub.util.SongDBHandler.java

public synchronized void setSongPlayed(DownloadFile downloadFile, boolean submission) {
    // TODO: In case of offline want to update all matches
    Pair<Integer, String> pair = getOnlineSongId(downloadFile);
    if (pair == null) {
        return;/*from   w  w  w  .j av a  2s . co  m*/
    }
    int serverKey = pair.getFirst();
    String id = pair.getSecond();

    // Open and make sure song is in db
    SQLiteDatabase db = this.getWritableDatabase();
    addSongImpl(db, serverKey, id, downloadFile.getSaveFile().getAbsolutePath());

    // Update song's last played
    ContentValues values = new ContentValues();
    values.put(submission ? SONGS_LAST_COMPLETED : SONGS_LAST_PLAYED, System.currentTimeMillis());
    db.update(TABLE_SONGS, values, SONGS_SERVER_KEY + " = ? AND " + SONGS_SERVER_ID + " = ?",
            new String[] { Integer.toString(serverKey), id });
    db.close();
}

From source file:org.akop.crosswords.Storage.java

public void write(long puzzleId, Crossword.State state) {
    long started = SystemClock.uptimeMillis();

    ContentValues cv = new ContentValues();

    cv.put(PuzzleState.PUZZLE_ID, puzzleId);
    cv.put(PuzzleState.CLASS, state.getClass().getName());
    cv.put(PuzzleState.OBJECT, mGson.toJson(state));
    cv.put(PuzzleState.OBJECT_VERSION, 1);
    cv.put(PuzzleState.PERCENT_SOLVED, state.getPercentSolved());
    cv.put(PuzzleState.PERCENT_CHEATED, state.getPercentCheated());
    cv.put(PuzzleState.PERCENT_WRONG, state.getPercentWrong());
    cv.put(PuzzleState.PLAY_TIME_MILLIS, state.getPlayTimeMillis());

    long lastPlayed = 0;
    if (state.getLastPlayed() != null) {
        lastPlayed = state.getLastPlayed().getMillis();
    }//from w w w .  j  a  v a 2 s .  c  o  m
    cv.put(PuzzleState.LAST_PLAYED, lastPlayed);

    cv.put(PuzzleState.LAST_UPDATED, System.currentTimeMillis());

    StorageHelper helper = getHelper();
    SQLiteDatabase db = helper.getWritableDatabase();

    try {
        // Delete any existing rows
        db.delete(PuzzleState.TABLE, PuzzleState.PUZZLE_ID + "=" + puzzleId, null);
        // Insert the new one
        db.insert(PuzzleState.TABLE, null, cv);
    } finally {
        db.close();
    }

    Crosswords.logv("Wrote state for %d (%dms)", puzzleId, SystemClock.uptimeMillis() - started);

    // Add a copy to the cache
    mStateCache.put((int) puzzleId, new Crossword.State(state));

    // Broadcast the change
    Intent intent = new Intent(ACTION_PUZZLE_STATE_CHANGE);
    intent.putExtra(INTENT_PUZZLE_ID, puzzleId);

    Context context = Crosswords.getInstance();
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

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

private List<String> getSelectedCategories(boolean isMuzei) {
    List<String> categories = new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();
    String column = isMuzei ? KEY_MUZEI_SELECTED : KEY_SELECTED;
    Cursor cursor = db.query(TABLE_CATEGORIES, new String[] { KEY_NAME }, column + " = ?", new String[] { "1" },
            null, null, KEY_NAME);//w  w w .  j  a  v a 2  s .co m
    if (cursor.moveToFirst()) {
        do {
            categories.add(cursor.getString(0));
        } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return categories;
}