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:net.olejon.mdapp.DiseasesAndTreatmentsSearchActivity.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 a v a 2  s .  co  m

        return;
    }

    // Intent
    final Intent intent = getIntent();

    mSearchLanguage = intent.getStringExtra("language");

    final String searchString = intent.getStringExtra("string");

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

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

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

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

    // Spinner
    mSpinner = (Spinner) findViewById(R.id.diseases_and_treatments_search_spinner);

    ArrayAdapter<CharSequence> arrayAdapter;

    if (mSearchLanguage.equals("")) {
        arrayAdapter = ArrayAdapter.createFromResource(mContext,
                R.array.diseases_and_treatments_search_spinner_items_english,
                R.layout.activity_diseases_and_treatments_search_spinner_header);
    } else {
        arrayAdapter = ArrayAdapter.createFromResource(mContext,
                R.array.diseases_and_treatments_search_spinner_items_norwegian,
                R.layout.activity_diseases_and_treatments_search_spinner_header);
    }

    arrayAdapter.setDropDownViewResource(R.layout.activity_diseases_and_treatments_search_spinner_item);

    mSpinner.setAdapter(arrayAdapter);
    mSpinner.setOnItemSelectedListener(this);

    // Refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(
            R.id.diseases_and_treatments_search_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(mSearchLanguage, searchString, false);
        }
    });

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

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

    // Search
    search(mSearchLanguage, 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(
                                                        DiseasesAndTreatmentsSQLiteHelper.COLUMN_STRING,
                                                        correctSearchString);

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

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

                                                sqLiteDatabase.close();

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

                                                mProgressBar.setVisibility(View.VISIBLE);

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

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

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

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

private void getManufacturer() {
    SQLiteDatabase sqLiteDatabase = new SlDataSQLiteHelper(mContext).getReadableDatabase();

    String[] queryColumns = { SlDataSQLiteHelper.MANUFACTURERS_COLUMN_ID };
    Cursor cursor = sqLiteDatabase.query(SlDataSQLiteHelper.TABLE_MANUFACTURERS, queryColumns,
            SlDataSQLiteHelper.MANUFACTURERS_COLUMN_NAME + " = " + mTools.sqe(medicationManufacturer), null,
            null, null, null);//from w  w  w  .  j ava  2 s . com

    if (cursor.moveToFirst()) {
        long id = cursor.getLong(cursor.getColumnIndexOrThrow(SlDataSQLiteHelper.MANUFACTURERS_COLUMN_ID));

        Intent intent = new Intent(mContext, ManufacturerActivity.class);
        intent.putExtra("id", id);
        startActivity(intent);
    }

    cursor.close();
    sqLiteDatabase.close();
}

From source file:cl.gisred.android.RepartoActivity.java

public void readData() {

    SQLiteDatabase db = sqlReparto.getReadableDatabase();
    String[] sValues = { "id", "codigo", "x", "y" };
    Cursor cData = db.query("repartos", sValues, null, null, null, null, null, null);
    arrayDatos = new ArrayList<>();

    if (cData != null && cData.getCount() > 0) {
        iContRep = cData.getCount();//from  w  w  w .j  av a  2 s .  co m

        cData.moveToFirst();

        do {
            RepartoClass oRep = new RepartoClass(cData.getInt(0), cData.getString(1), cData.getDouble(2),
                    cData.getDouble(3));

            arrayDatos.add(oRep);
        } while (cData.moveToNext());

        cData.close();
    }

    db.close();
}

From source file:net.smart_json_database.JSONDatabase.java

public boolean deleteAll() {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    boolean returnValue = false;
    try {//  w w  w.j a  v  a2 s .  c  o  m
        db.beginTransaction();
        db.delete(TABLE_REL_JSON_DATA_JSON_DATA, "", null);
        db.delete(TABLE_REL_JSON_DATA_JSON_DATA, "", null);
        db.delete(TABLE_REL_TAG_JSON_DATA, "", null);
        db.delete(TABLE_JSON_DATA, "", null);
        db.setTransactionSuccessful();
        returnValue = true;
    } catch (Exception e) {
        returnValue = false;
    } finally {
        db.endTransaction();
        db.close();
    }
    return returnValue;
}

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

public long saveFavorite(FavoritesData fd, Context context, boolean spawnThread) {
    SQLiteDatabase db = this.getWritableDatabase();
    if (db == null) {
        LOG.e("db is null in saveFavorite");
        return -1;
    }/*from w w w  . j a  va2  s  .  c o m*/
    long id;
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, fd.getName());
    values.put(KEY_ADDRESS, fd.getAdress());
    values.put(KEY_SOURCE, fd.getSource());
    values.put(KEY_SUBSOURCE, fd.getSubSource());
    values.put(KEY_LAT, Double.valueOf(fd.getLatitude()));
    values.put(KEY_LONG, Double.valueOf(fd.getLongitude()));
    values.put(KEY_API_ID, fd.getApiId());
    id = db.insert(TABLE_FAVORITES, null, values);
    fd.setId(id);
    db.close();
    if (context != null) {
        postFavoriteToServer(fd, context, spawnThread);
    }
    return id;
}

From source file:edu.asu.bscs.csiebler.waypointdatabase.MainActivity.java

private JSONArray getJsonResults() {
    JSONArray resultSet = new JSONArray();

    try {/*from w  ww  .  j  ava 2s  .  c o m*/
        WaypointDB db = new WaypointDB(this);
        db.copyDB();
        SQLiteDatabase waypointDB = db.openDB();
        waypointDB.beginTransaction();

        String searchQuery = "SELECT  * FROM waypoint";
        Cursor cursor = waypointDB.rawQuery(searchQuery, null);

        cursor.moveToFirst();

        while (cursor.isAfterLast() == false) {
            int totalColumn = cursor.getColumnCount();
            JSONObject rowObject = new JSONObject();

            for (int i = 0; i < totalColumn; i++) {
                if (cursor.getColumnName(i) != null) {
                    try {
                        if (cursor.getString(i) != null) {
                            Log.d("TAG_NAME", cursor.getString(i));
                            rowObject.put(cursor.getColumnName(i), cursor.getString(i));
                        } else {
                            rowObject.put(cursor.getColumnName(i), "");
                        }
                    } catch (Exception e) {
                        Log.d("TAG_NAME", e.getMessage());
                    }
                }
            }

            resultSet.put(rowObject);
            cursor.moveToNext();
        }

        cursor.close();
        waypointDB.endTransaction();
        waypointDB.close();
        db.close();

        Log.d("TAG_NAME", resultSet.toString());
    } catch (Exception ex) {
        Log.w(getClass().getSimpleName(), "Exception creating adapter: " + ex.getMessage());
    }

    return resultSet;
}

From source file:eu.rubenrosado.tinypasswordmanager.AllRows.java

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 0) {
        if (resultCode == Activity.RESULT_OK) {
            toastMessage(getString(R.string.saving));
            int position = data.getIntExtra("position", -1);
            int id = data.getIntExtra("id", -1);
            String site = data.getStringExtra("site");
            String user = data.getStringExtra("user");
            String password = data.getStringExtra("password");

            DBHelper dbhelper = new DBHelper(this);
            SQLiteDatabase sql = dbhelper.getWritableDatabase();

            try {
                ObjectRows sp = new ObjectRows(id, Encryption.decrypt(Main.MASTERPASSWORD, site),
                        Encryption.decrypt(Main.MASTERPASSWORD, user), HIDEPW);
                ContentValues cv = new ContentValues();
                cv.put(DBHelper.COLSITE, site);
                cv.put(DBHelper.COLUSER, user);
                cv.put(DBHelper.COLPASS, password);
                if (position != -1) {
                    sql.update(DBHelper.TABLENAME, cv, DBHelper.COLID + "=" + id, null);
                    spArray.set(position, sp);
                    decryptedPasswords.set(position, Encryption.decrypt(Main.MASTERPASSWORD, password));
                } else {
                    sql.insert(DBHelper.TABLENAME, null, cv);
                    spArray.add(sp);/*  w w w  .j a v  a  2s .c om*/
                    decryptedPasswords.add(Encryption.decrypt(Main.MASTERPASSWORD, password));
                }
                toastMessage(getString(R.string.saved));
            } catch (Exception e) {
                toastMessage(getString(R.string.internal_error));
            } finally {
                sql.close();
                dbhelper.close();
            }
            adapter.notifyDataSetChanged();
        }
    }
}

From source file:com.rs.TCOfflineStatementCollection.java

/**
 * return a list of all local statements from db
 * @return List of LocalStatementsItem//from  w  w w  .ja  v a 2s  .  co m
 */
public List<LocalStatementsItem> getCachedStatements() {
    List<LocalStatementsItem> statementArray = new ArrayList<LocalStatementsItem>();

    Cursor cursor;
    SQLiteDatabase database;
    TCLocalStorageDatabaseOpenHelper dbHelper;
    dbHelper = new TCLocalStorageDatabaseOpenHelper(appContext);
    database = dbHelper.getWritableDatabase();
    cursor = database.query(TCOfflineDataManager.LOCAL_STATEMENT_TABLE_NAME, null, null, null, null, null,
            LocalStatements.CREATE_DATE + " DESC"); //query for all the 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.mk4droid.IMC_Services.DatabaseHandler.java

/**
 * Get issue picture from SQlite according to issue id
 * //from ww  w  .ja  v  a2  s .c  om
 * @param IssueID
 * @return
 */
public IssuePic getIssuePic(int IssueID) {
    SQLiteDatabase db = this.getReadableDatabase();
    IssuePic mIssuePic;

    if (!db.isOpen())
        db = this.getWritableDatabase();

    Cursor cr = db.query(TABLE_IssuesPics, new String[] { KEY_IssueID, KEY_IssuePicData }, KEY_IssueID + "=?",
            new String[] { Integer.toString(IssueID) }, null, null, null, null);

    boolean ExistsRes = cr.moveToFirst();

    if (!ExistsRes) {
        mIssuePic = new IssuePic(-1, null);
    } else {

        mIssuePic = new IssuePic(cr.getInt(0), cr.getBlob(1));
    }
    cr.close();
    if (db.isOpen())
        db.close();

    return mIssuePic;
}

From source file:com.mk4droid.IMC_Services.DatabaseHandler.java

/**
 *  Get Issue Thumb from SQLite table according to issue id.
 * /*w  ww . jav  a 2 s . c  o  m*/
 * @param IssueID
 * @return
 */
public IssuePic getIssueThumb(int IssueID) {
    SQLiteDatabase db = this.getReadableDatabase();
    IssuePic mIssueThumb;

    if (!db.isOpen())
        db = this.getWritableDatabase();

    Cursor cr = db.query(TABLE_IssuesThumbs, new String[] { KEY_IssueID, KEY_IssueThumbData },
            KEY_IssueID + "=?", new String[] { Integer.toString(IssueID) }, null, null, null, null);

    boolean ExistsRes = cr.moveToFirst();

    if (!ExistsRes) {
        mIssueThumb = new IssuePic(-1, null);
    } else {
        mIssueThumb = new IssuePic(cr.getInt(0), cr.getBlob(1));
    }
    cr.close();

    if (db.isOpen())
        db.close();

    return mIssueThumb;
}