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:org.akop.crosswords.Storage.java

public Crossword.State getPuzzleState(long puzzleId) {
    long started = SystemClock.uptimeMillis();

    Crossword.State state = mStateCache.get((int) puzzleId);
    if (state == null) {
        StorageHelper helper = getHelper();
        SQLiteDatabase db = helper.getReadableDatabase();

        try {/*from  w w  w.  j  av  a2 s .  co  m*/
            Cursor cursor = db.query(PuzzleState.TABLE, new String[] { PuzzleState.CLASS, PuzzleState.OBJECT, },
                    PuzzleState.PUZZLE_ID + "=" + puzzleId, null, null, null, null);

            if (cursor != null) {
                try {
                    if (cursor.moveToFirst()) {
                        state = mGson.fromJson(cursor.getString(1), Crossword.State.class);
                        mStateCache.put((int) puzzleId, new Crossword.State(state));
                    }
                } finally {
                    cursor.close();
                }
            }
        } finally {
            db.close();
        }
    }

    if (state != null) {
        Crosswords.logv("Loaded state for %d (%dms)", puzzleId, SystemClock.uptimeMillis() - started);
    }

    return state;
}

From source file:com.spoiledmilk.ibikecph.util.DB.java

public int getApiId(int id) {
    int ret = -1;
    SQLiteDatabase db = getWritableDatabase();
    if (db == null)
        return -1;
    String strFilter = "_id= ?";
    Cursor cur = db.query(TABLE_FAVORITES, new String[] { KEY_API_ID }, strFilter, new String[] { id + "" },
            null, null, null);/*from  w w  w  .ja va  2 s  .c om*/
    if (cur != null && cur.moveToFirst()) {
        if (cur != null && !cur.isAfterLast()) {
            ret = cur.getInt(cur.getColumnIndex(KEY_API_ID));
        }
    }
    db.close();
    return ret;
}

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

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

    // Connected?
    if (!mTools.isDeviceConnected()) {
        mTools.showToast(getString(R.string.device_not_connected), 1);

        finish();//from  w w w. j av a2  s. c  o  m

        return;
    }

    // Intent
    final Intent intent = getIntent();

    searchString = intent.getStringExtra("search");

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

    // Toolbar
    mToolbar = (Toolbar) findViewById(R.id.poisonings_cards_toolbar);
    mToolbar.setTitle(getString(R.string.poisonings_cards_search) + ": \"" + searchString + "\"");

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

    // Progress bar
    mProgressBar = (ProgressBar) findViewById(R.id.poisonings_cards_toolbar_progressbar);
    mProgressBar.setVisibility(View.VISIBLE);

    // Refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.poisonings_cards_swipe_refresh_layout);
    mSwipeRefreshLayout.setColorSchemeResources(R.color.accent_blue, R.color.accent_green,
            R.color.accent_purple, R.color.accent_orange);

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            search(searchString, false);
        }
    });

    // Recycler view
    mRecyclerView = (RecyclerView) findViewById(R.id.poisonings_cards_cards);

    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setAdapter(new PoisoningsCardsAdapter(mContext, new JSONArray()));
    mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

    // No poisonings
    mNoPoisoningsLayout = (LinearLayout) findViewById(R.id.poisonings_cards_no_poisonings);

    Button noPoisoningsHelsenorgeButton = (Button) findViewById(R.id.poisonings_cards_check_on_helsenorge);
    Button noPoisoningsHelsebiblioteketButton = (Button) findViewById(
            R.id.poisonings_cards_check_on_helsebiblioteket);

    noPoisoningsHelsenorgeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                Intent intent = new Intent(mContext, MainWebViewActivity.class);
                intent.putExtra("title",
                        getString(R.string.poisonings_cards_search) + ": \"" + searchString + "\"");
                intent.putExtra("uri", "https://helsenorge.no/sok/giftinformasjon/?k="
                        + URLEncoder.encode(searchString.toLowerCase(), "utf-8"));
                mContext.startActivity(intent);
            } catch (Exception e) {
                Log.e("PoisoningsCardsActivity", Log.getStackTraceString(e));
            }
        }
    });

    noPoisoningsHelsebiblioteketButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                Intent intent = new Intent(mContext, MainWebViewActivity.class);
                intent.putExtra("title",
                        getString(R.string.poisonings_cards_search) + ": \"" + searchString + "\"");
                intent.putExtra("uri",
                        "http://www.helsebiblioteket.no/forgiftninger/alle-anbefalinger?cx=005475784484624053973%3A3bnj2dj_uei&ie=UTF-8&q="
                                + URLEncoder.encode(searchString.toLowerCase(), "utf-8") + "&sa=S%C3%B8k");
                mContext.startActivity(intent);
            } catch (Exception e) {
                Log.e("PoisoningsCardsActivity", Log.getStackTraceString(e));
            }
        }
    });

    // Search
    search(searchString, true);

    // Correct
    RequestQueue requestQueue = Volley.newRequestQueue(mContext);

    try {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                getString(R.string.project_website_uri) + "api/1/correct/?search="
                        + URLEncoder.encode(searchString, "utf-8"),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            final String correctSearchString = response.getString("correct");

                            if (!correctSearchString.equals("")) {
                                new MaterialDialog.Builder(mContext)
                                        .title(getString(R.string.correct_dialog_title))
                                        .content(Html.fromHtml(getString(R.string.correct_dialog_message)
                                                + ":<br><br><b>" + correctSearchString + "</b>"))
                                        .positiveText(getString(R.string.correct_dialog_positive_button))
                                        .negativeText(getString(R.string.correct_dialog_negative_button))
                                        .callback(new MaterialDialog.ButtonCallback() {
                                            @Override
                                            public void onPositive(MaterialDialog dialog) {
                                                ContentValues contentValues = new ContentValues();
                                                contentValues.put(PoisoningsSQLiteHelper.COLUMN_STRING,
                                                        correctSearchString);

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

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

                                                sqLiteDatabase.close();

                                                mToolbar.setTitle(getString(R.string.poisonings_cards_search)
                                                        + ": \"" + correctSearchString + "\"");

                                                mProgressBar.setVisibility(View.VISIBLE);

                                                mNoPoisoningsLayout.setVisibility(View.GONE);
                                                mSwipeRefreshLayout.setVisibility(View.VISIBLE);

                                                search(correctSearchString, true);
                                            }
                                        }).contentColorRes(R.color.black).positiveColorRes(R.color.dark_blue)
                                        .negativeColorRes(R.color.black).show();
                            }
                        } catch (Exception e) {
                            Log.e("PoisoningsCardsActivity", Log.getStackTraceString(e));
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("PoisoningsCardsActivity", error.toString());
                    }
                });

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

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

From source file:info.staticfree.android.units.UnitUsageDBHelper.java

@SuppressWarnings("unchecked")
public void loadUnitClassifications() {
    final SQLiteDatabase db = getWritableDatabase();
    final JSONObject jo = loadInitialWeights(R.raw.unit_classification);

    db.beginTransaction();/*  w w  w .j  a v a2 s.c o m*/
    final ContentValues cv = new ContentValues();
    for (final Iterator i = jo.keys(); i.hasNext();) {
        final String unit = (String) i.next();
        final String description = jo.optString(unit);
        final String fprint = getFingerprint(unit);
        cv.put(ClassificationEntry._FACTOR_FPRINT, fprint);
        cv.put(ClassificationEntry._DESCRIPTION, description);
        db.insert(DB_CLASSIFICATION_TABLE, null, cv);
    }
    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();
    Log.d(TAG, "Successfully added " + jo.length() + " classification entries.");
}

From source file:net.smart_json_database.JSONDatabase.java

public boolean deleteTag(String name) {
    boolean returnValue = false;
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    try {//from   www . j  a va  2  s.  c  o  m
        db.beginTransaction();
        returnValue = deleteTag(name, db);
        db.setTransactionSuccessful();
        notifyListenersOnTagChange(name, IDatabaseChangeListener.CHANGETYPE_DELETE);
    } catch (Exception e) {
    } finally {
        db.endTransaction();
        db.close();
    }
    return returnValue;
}

From source file:net.smart_json_database.JSONDatabase.java

public int insertTag(String name) {
    int returnValue = -1;
    SQLiteDatabase db = dbHelper.getWritableDatabase();

    try {/*from   w  w w.  jav  a 2s. co  m*/
        db.beginTransaction();
        returnValue = insertTag(name, db);
        db.setTransactionSuccessful();
        notifyListenersOnTagChange(name, IDatabaseChangeListener.CHANGETYPE_INSERT);
    } catch (Exception e) {
    } finally {
        db.endTransaction();
        db.close();
    }
    return returnValue;
}

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

public List<Wallpaper> getWallpapers() {
    List<Wallpaper> wallpapers = new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(TABLE_WALLPAPERS, null, null, null, null, null, KEY_CATEGORY);
    if (cursor.moveToFirst()) {
        do {/*from  w  w  w  .  j a  v a 2s. com*/
            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:net.potterpcs.recipebook.RecipeData.java

public int updateRecipe(long rid, ContentValues values) {
    synchronized (DB_LOCK) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int ret = -1;
        try {/*from  www. ja va2s .c  o  m*/
            ret = db.update(RECIPES_TABLE, values, RT_ID + " = ?", new String[] { Long.toString(rid) });
        } finally {
            db.close();
        }
        return ret;
    }
}

From source file:com.spoiledmilk.ibikecph.util.DB.java

private void postFavoriteToServer(final FavoritesData fd, Context context, boolean spawnThread) {
    if (IbikeApplication.isUserLogedIn()) {
        String authToken = IbikeApplication.getAuthToken();
        final JSONObject postObject = new JSONObject();
        try {//from  ww w  .jav a2 s. co  m
            JSONObject favouriteObject = new JSONObject();
            favouriteObject.put("name", fd.getName());
            favouriteObject.put("address", fd.getAdress());
            favouriteObject.put("lattitude", fd.getLatitude());
            favouriteObject.put("longitude", fd.getLongitude());
            favouriteObject.put("source", fd.getSource());
            favouriteObject.put("sub_source", fd.getSubSource());
            postObject.put("favourite", favouriteObject);
            postObject.put("auth_token", authToken);
            if (spawnThread) {
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        LOG.d("Server request: " + Config.serverUrl + "/favourites");
                        JsonNode responseNode = HttpUtils.postToServer(Config.serverUrl + "/favourites",
                                postObject);
                        if (responseNode != null && responseNode.has("data")
                                && responseNode.get("data").has("id")) {
                            int id = responseNode.get("data").get("id").asInt();
                            SQLiteDatabase db = getWritableDatabase();
                            if (db == null)
                                return;
                            String strFilter = "_id=" + fd.getId();
                            ContentValues args = new ContentValues();
                            args.put(KEY_API_ID, id);
                            db.update(TABLE_FAVORITES, args, strFilter, null);
                            db.close();
                        }
                    }
                });
                thread.start();
            } else {
                LOG.d("Server request: " + Config.serverUrl + "/favourites");
                JsonNode responseNode = HttpUtils.postToServer(Config.serverUrl + "/favourites", postObject);
                if (responseNode != null && responseNode.has("data") && responseNode.get("data").has("id")) {
                    int id = responseNode.get("data").get("id").asInt();
                    SQLiteDatabase db = getWritableDatabase();
                    if (db == null)
                        return;
                    String strFilter = "_id=" + fd.getId();
                    ContentValues args = new ContentValues();
                    args.put(KEY_API_ID, id);
                    db.update(TABLE_FAVORITES, args, strFilter, null);
                    db.close();
                }
            }
        } catch (Exception e) {
            LOG.e(e.getLocalizedMessage());
        }
    }

}

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

public List<Category> getCategories() {
    List<Category> categories = new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(TABLE_CATEGORIES, null, null, null, null, null, KEY_NAME);
    if (cursor.moveToFirst()) {
        do {/*  w w w .  j a  v  a 2s.  c  o m*/
            Category category = new Category(cursor.getInt(0), cursor.getString(1), cursor.getString(2),
                    cursor.getInt(3) == 1);
            int count = getWallpapersCountOfCatgegory(cursor.getString(1));
            category.setNumWallpapers(count);
            categories.add(category);
        } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return categories;
}