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.spotcommander.MyTools.java

public String[] getComputer(final long id) {
    final SQLiteDatabase mDatabase = new MainSQLiteHelper(mContext).getReadableDatabase();

    final String[] queryColumns = { MainSQLiteHelper.COLUMN_URI, MainSQLiteHelper.COLUMN_USERNAME,
            MainSQLiteHelper.COLUMN_PASSWORD };
    final Cursor mCursor = mDatabase.query(MainSQLiteHelper.TABLE_COMPUTERS, queryColumns,
            MainSQLiteHelper.COLUMN_ID + " = " + id, null, null, null, null);

    String uri = "";
    String username = "";
    String password = "";

    if (mCursor.moveToFirst()) {
        uri = mCursor.getString(mCursor.getColumnIndexOrThrow(MainSQLiteHelper.COLUMN_URI));
        username = mCursor.getString(mCursor.getColumnIndexOrThrow(MainSQLiteHelper.COLUMN_USERNAME));
        password = mCursor.getString(mCursor.getColumnIndexOrThrow(MainSQLiteHelper.COLUMN_PASSWORD));
    }/*from w  ww .j a  v  a  2 s .  c o m*/

    mCursor.close();
    mDatabase.close();

    return new String[] { uri, username, password };
}

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

public void update(List<T> items, int conflictAlgorithm) {
    SQLiteDatabase db = mSqlHelper.getWritableDatabase();
    try {/* w  ww.  j av a  2s .  c  o  m*/
        db.beginTransaction();
        for (T item : items)
            db.updateWithOnConflict(mTableName, itemToRow(item), "id = ?",
                    new String[] { String.valueOf(item.id) }, conflictAlgorithm);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        db.endTransaction();
        db.close();
    }
}

From source file:com.develop.autorus.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Fabric.with(this, new Crashlytics());
    super.onCreate(savedInstanceState);
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);

    AnalyticsApplication application = (AnalyticsApplication) getApplication();
    mTracker = application.getDefaultTracker();
    mTracker.setScreenName("Main activity");
    mTracker.send(new HitBuilders.ScreenViewBuilder().build());

    if (pref.getBoolean("notificationIsActive", true)) {
        Intent checkIntent = new Intent(getApplicationContext(), MonitoringWork.class);
        Boolean alrarmIsActive = false;
        if (PendingIntent.getService(getApplicationContext(), 0, checkIntent,
                PendingIntent.FLAG_NO_CREATE) != null)
            alrarmIsActive = true;//from  ww  w.ja v a  2 s.c o  m
        am = (AlarmManager) getSystemService(ALARM_SERVICE);

        if (!alrarmIsActive) {
            Intent serviceIntent = new Intent(getApplicationContext(), MonitoringWork.class);
            PendingIntent pIntent = PendingIntent.getService(getApplicationContext(), 0, serviceIntent, 0);

            int period = pref.getInt("numberOfActiveMonitors", 0) * 180000;

            if (period != 0)
                am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + period,
                        period, pIntent);
        }
    }

    /*ForEasyDelete
            
    //Danger! Auchtung! ?, !!!
    String base64EncodedPublicKey =
        "<your license key here>";//?   . !!! ? ,    
    // github ?  .         ?!!!
            
    mHelper = new IabHelper(this, base64EncodedPublicKey);
            
    mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
    public void onIabSetupFinished(IabResult result) {
        if (!result.isSuccess()) {
            Log.d(TAG, "In-app Billing setup failed: " +
                    result);
        } else {
            Log.d(TAG, "In-app Billing is set up OK");
        }
    }
    });
    */

    //Service inapp
    Intent intent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
    intent.setPackage("com.android.vending");
    blnBind = bindService(intent, mServiceConn, Context.BIND_AUTO_CREATE);

    String themeName = pref.getString("theme", "1");

    if (themeName.equals("1")) {
        setTheme(R.style.AppTheme);
        if (android.os.Build.VERSION.SDK_INT >= 21) {
            Window statusBar = getWindow();
            statusBar.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            statusBar.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            statusBar.setStatusBarColor(getResources().getColor(R.color.myPrimaryDarkColor));
        }
    } else if (themeName.equals("2")) {
        setTheme(R.style.AppTheme2);
        if (android.os.Build.VERSION.SDK_INT >= 21) {
            Window statusBar = getWindow();
            statusBar.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            statusBar.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            statusBar.setStatusBarColor(getResources().getColor(R.color.myPrimaryDarkColor2));
        }
    }
    ThemeManager.init(this, 2, 0, null);

    if (isFirstLaunch) {
        SQLiteDatabase db = new DbHelper(this).getWritableDatabase();
        Cursor cursorMonitors = db.query("monitors", null, null, null, null, null, null);
        Boolean monitorsExist = cursorMonitors != null && cursorMonitors.getCount() > 0;
        db.close();

        if (getSupportFragmentManager().findFragmentByTag("MAIN") == null) {
            FragmentTransaction fTrans = getSupportFragmentManager().beginTransaction();
            if (monitorsExist)
                mainFragment = SearchAndMonitorsFragment.newInstance(0);
            else
                mainFragment = SearchAndMonitorsFragment.newInstance(1);
            fTrans.add(R.id.container, mainFragment, "MAIN").commit();
        } else {
            mainFragment = (SearchAndMonitorsFragment) getSupportFragmentManager().findFragmentByTag("MAIN");
            if (getSupportFragmentManager().findFragmentByTag("Second") != null) {
                FragmentTransaction fTrans = getSupportFragmentManager().beginTransaction();
                fTrans.remove(getSupportFragmentManager().findFragmentByTag("Second")).commit();
            }
            pref.edit().remove("NumberOfCallingFragment");
        }
    }

    backToast = Toast.makeText(this, "?   ? ", Toast.LENGTH_SHORT);
    setContentView(R.layout.main_activity);
    mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
    mSnackBar = (SnackBar) findViewById(R.id.main_sn);
    setSupportActionBar(mToolbar);

    addMonitorButton = (Button) findViewById(R.id.toolbar_add_monitor_button);

    mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
            .findFragmentById(R.id.fragment_drawer);
    mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);

    Thread threadAvito = new Thread(new Runnable() {
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        public void run() {
            Document doc;
            SharedPreferences sPref;
            try {
                String packageName = getApplicationContext().getPackageName();
                doc = Jsoup.connect("https://play.google.com/store/apps/details?id=" + packageName).userAgent(
                        "Mozilla/5.0 (Windows; U; WindowsNT 5.1; ru-RU; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                        .timeout(12000).get();
                //"")

                PackageManager packageManager;
                PackageInfo packageInfo;
                packageManager = getPackageManager();

                packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
                Element mainElems = doc.select(
                        "#body-content > div > div > div.main-content > div.details-wrapper.apps-secondary-color > div > div.details-section-contents > div:nth-child(4) > div.content")
                        .first();

                if (!packageInfo.versionName.equals(mainElems.text())) {
                    sPref = getPreferences(MODE_PRIVATE);
                    SharedPreferences.Editor ed = sPref.edit();
                    ed.putBoolean(SAVED_TEXT_WITH_VERSION, false);
                    ed.commit();
                } else {
                    sPref = getPreferences(MODE_PRIVATE);
                    SharedPreferences.Editor ed = sPref.edit();
                    ed.putBoolean(SAVED_TEXT_WITH_VERSION, true);
                    ed.commit();

                }
                //SharedPreferences sPrefRemind;
                //sPrefRemind = getPreferences(MODE_PRIVATE);
                //sPrefRemind.edit().putBoolean(DO_NOT_REMIND, false).commit();
            } catch (HttpStatusException e) {
                return;
            } catch (IOException e) {
                return;
            } catch (PackageManager.NameNotFoundException e) {

                e.printStackTrace();
            }
        }
    });

    SharedPreferences sPrefVersion;
    sPrefVersion = getPreferences(MODE_PRIVATE);
    Boolean isNewVersion;
    isNewVersion = sPrefVersion.getBoolean(SAVED_TEXT_WITH_VERSION, true);

    threadAvito.start();
    boolean remind = true;
    if (!isNewVersion) {
        Log.d("affa", "isNewVersion= " + isNewVersion);
        SharedPreferences sPref12;
        sPref12 = getPreferences(MODE_PRIVATE);
        String isNewVersion12;

        PackageManager packageManager;
        PackageInfo packageInfo;
        packageManager = getPackageManager();

        try {
            packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            isNewVersion12 = sPref12.getString("OldVersionName", packageInfo.versionName);

            if (!isNewVersion12.equals(packageInfo.versionName)) {
                SharedPreferences sPref;
                sPref = getPreferences(MODE_PRIVATE);
                SharedPreferences.Editor ed = sPref.edit();
                ed.putBoolean(SAVED_TEXT_WITH_VERSION, false);
                ed.commit();

                SharedPreferences sPrefRemind;
                sPrefRemind = getPreferences(MODE_PRIVATE);
                sPrefRemind.edit().putBoolean(DO_NOT_REMIND, false).commit();
            } else
                remind = false;

            SharedPreferences sPrefRemind;
            sPrefRemind = getPreferences(MODE_PRIVATE);
            sPrefRemind.edit().putString("OldVersionName", packageInfo.versionName).commit();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        SharedPreferences sPrefRemind;
        sPrefRemind = getPreferences(MODE_PRIVATE);
        Boolean dontRemind;
        dontRemind = sPrefRemind.getBoolean(DO_NOT_REMIND, false);
        Log.d("affa", "dontRemind= " + dontRemind.toString());
        Log.d("affa", "remind= " + remind);
        Log.d("affa", "44444444444444444444444= ");
        if ((!dontRemind) && (!remind)) {
            Log.d("affa", "5555555555555555555555555= ");
            SimpleDialog.Builder builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
                @Override
                public void onPositiveActionClicked(DialogFragment fragment) {
                    super.onPositiveActionClicked(fragment);
                    String packageName = getApplicationContext().getPackageName();
                    Intent intent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse("https://play.google.com/store/apps/details?id=" + packageName));
                    startActivity(intent);
                }

                @Override
                public void onNegativeActionClicked(DialogFragment fragment) {
                    super.onNegativeActionClicked(fragment);
                }

                @Override
                public void onNeutralActionClicked(DialogFragment fragment) {
                    super.onNegativeActionClicked(fragment);
                    SharedPreferences sPrefRemind;
                    sPrefRemind = getPreferences(MODE_PRIVATE);
                    sPrefRemind.edit().putBoolean(DO_NOT_REMIND, true).commit();
                }
            };

            builder.message(
                    "  ??   ? ? ?")
                    .title(" !").positiveAction("")
                    .negativeAction("").neutralAction("? ");
            DialogFragment fragment = DialogFragment.newInstance(builder);
            fragment.show(getSupportFragmentManager(), null);
        }
    }
}

From source file:com.acrylicgoat.devchat.MainActivity.java

private void saveNote() {
    ContentValues values = new ContentValues();

    String text = today.getText().toString() + " ";
    //Log.d("NoteEditorActivity", "note: " + text);
    int length = text.length();

    if (length == 0 || text.contains("To get started, select Tools") || text.equals("") || text.equals(" ")) {
        //Toast.makeText(this, "Nothing to save.", Toast.LENGTH_SHORT).show();
        return;// w  ww  .j av  a  2 s .c  om
    }

    values.put(Notes.NOTE, text);
    values.put(Notes.OWNER, currentOwner);

    //check if a note already exists for today
    DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    cursor = db.rawQuery(getTodaySQL(), null);
    if (cursor.getCount() > 0) {
        //Log.d("MainActivity", "saveNote(): doing update ");
        StringBuilder sb = new StringBuilder();
        sb.append("update notes set notes_note = '");
        sb.append(escape(text));
        sb.append("' where notes_owner='");
        sb.append(currentOwner);
        sb.append("' and date(notes_date) = date('now','localtime')");
        dbHelper.getReadableDatabase().execSQL(sb.toString());
    } else {
        getContentResolver().insert(Notes.CONTENT_URI, values);
    }
    cursor.close();
    db.close();

}

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

public void selectAllRows() {
    DBHelper dbhelper;//from ww w  .j av  a 2s . c  o m
    SQLiteDatabase sql;
    dbhelper = new DBHelper(this);
    sql = dbhelper.getWritableDatabase();
    spArray = new ArrayList<ObjectRows>();
    decryptedPasswords = new ArrayList<String>();
    String[] columnes = { DBHelper.COLID, DBHelper.COLSITE, DBHelper.COLUSER, DBHelper.COLPASS };
    Cursor curs = sql.query(DBHelper.TABLENAME, columnes, null, null, null, null, null);
    try {
        while (curs.moveToNext()) {
            spArray.add(
                    new ObjectRows(curs.getInt(0), Encryption.decrypt(Main.MASTERPASSWORD, curs.getString(1)),
                            Encryption.decrypt(Main.MASTERPASSWORD, curs.getString(2)), HIDEPW));
            decryptedPasswords.add(Encryption.decrypt(Main.MASTERPASSWORD, curs.getString(3)));
        }
    } catch (Exception e) {
        toastMessage(getString(R.string.internal_error));
    } finally {
        sql.close();
        dbhelper.close();
    }
}

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

private boolean insertData(String sValue) {

    SQLiteDatabase db = sqlReparto.getWritableDatabase();
    long nIns = -1;

    if (db != null) {

        ContentValues valores = new ContentValues();
        valores.put("codigo", sValue);
        valores.put("x", oUbicActual.getX());
        valores.put("y", oUbicActual.getY());
        nIns = db.insert("repartos", null, valores);

        db.close();
    }/*w ww.  j  av  a2s  . c  o m*/

    return nIns > 0;
}

From source file:com.concentricsky.android.khanacademy.data.remote.LibraryUpdaterTask.java

@Override
protected Integer doInBackground(Void... params) {

    SharedPreferences prefs = dataService.getSharedPreferences(SETTINGS_NAME, Context.MODE_PRIVATE);

    // Connectivity receiver.
    final NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
    ComponentName receiver = new ComponentName(dataService, WifiReceiver.class);
    PackageManager pm = dataService.getPackageManager();
    if (activeNetwork == null || !activeNetwork.isConnected()) {
        // We've missed a scheduled update. Enable the receiver so it can launch an update when we reconnect.
        Log.d(LOG_TAG, "Missed library update: not connected. Enabling connectivity receiver.");
        pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
        return RESULT_CODE_FAILURE;
    } else {//from w  w w  .  ja v a2 s .  co  m
        // We are connected. Disable the receiver.
        Log.d(LOG_TAG, "Library updater connected. Disabling connectivity receiver.");
        pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
    }

    InputStream in = null;
    String etag = prefs.getString(SETTING_LIBRARY_ETAG, null);

    try {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        if (etag != null && !force) {
            conn.setRequestProperty("If-None-Match", etag);
        }

        int code = conn.getResponseCode();
        switch (code) {
        case HttpStatus.SC_NOT_MODIFIED:
            // If we got a 304, we're done.
            // Use failure code to indicate there is no temp db to copy over.
            Log.d(LOG_TAG, "304 in library response.");
            return RESULT_CODE_FAILURE;
        default:
            // Odd, but on 1/3/13 I received correct json responses with a -1 for responseCode. Fall through.
            Log.w(LOG_TAG, "Error code in library response: " + code);
        case HttpStatus.SC_OK:
            // Parse response.
            in = conn.getInputStream();
            JsonFactory factory = new JsonFactory();
            final JsonParser parser = factory.createJsonParser(in);

            SQLiteDatabase tempDb = tempDbHelper.getWritableDatabase();
            tempDb.beginTransaction();
            try {
                tempDb.execSQL("delete from topic");
                tempDb.execSQL("delete from topicvideo");
                tempDb.execSQL("delete from video");

                parseObject(parser, tempDb, null, 0);
                tempDb.setTransactionSuccessful();
            } catch (Exception e) {
                e.printStackTrace();
                return RESULT_CODE_FAILURE;
            } finally {
                tempDb.endTransaction();
                tempDb.close();
            }

            // Save etag once we've successfully parsed the response.
            etag = conn.getHeaderField("ETag");
            prefs.edit().putString(SETTING_LIBRARY_ETAG, etag).apply();

            // Move this new content from the temp db into the main one.
            mergeDbs();

            return RESULT_CODE_SUCCESS;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        tempDbHelper.close();
    }

    return RESULT_CODE_FAILURE;
}

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

public Map<String, Category> getCategoryMap() {
    Map<String, Category> categories = new HashMap<>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(TABLE_CATEGORIES, null, null, null, null, null, KEY_NAME);
    if (cursor.moveToFirst()) {
        do {/* ww  w  . j a  v  a2s.  c om*/
            Category category = new Category(cursor.getInt(0), cursor.getString(1), cursor.getString(2),
                    cursor.getInt(3) == 1);
            categories.put(cursor.getString(1), category);
        } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return categories;
}

From source file:com.acrylicgoat.scrumnotes.MainActivity.java

private void saveNote() {
    ContentValues values = new ContentValues();

    String text = today.getText().toString() + " ";
    //Log.d("NoteEditorActivity", "note: " + text);
    int length = text.length();

    if (length == 0 || text.contains("To get started, select Tools") || text.equals("Yesterday: \n\nToday: ")) {
        //Toast.makeText(this, "Nothing to save.", Toast.LENGTH_SHORT).show();
        return;/*from ww w .  j  av  a2s. co m*/
    }

    values.put(Notes.NOTE, text);
    values.put(Notes.OWNER, currentOwner);

    //check if a note already exists for today
    DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    cursor = db.rawQuery(getTodaySQL(), null);
    if (cursor.getCount() > 0) {
        //Log.d("MainActivity", "saveNote(): doing update ");
        StringBuilder sb = new StringBuilder();
        sb.append("update notes set notes_note = '");
        sb.append(ScrumNotesUtil.escape(text));
        sb.append("' where notes_owner='");
        sb.append(currentOwner);
        sb.append("' and date(notes_date) = date('now','localtime')");
        dbHelper.getReadableDatabase().execSQL(sb.toString());
    } else {
        getContentResolver().insert(Notes.CONTENT_URI, values);
    }
    cursor.close();
    db.close();

}

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

public void deleteById(List<Integer> ids) {
    if (ids.isEmpty())
        return;//from   w  w  w  .  j  a  v  a  2  s. c o  m

    SQLiteDatabase db = mSqlHelper.getWritableDatabase();
    try {
        db.beginTransaction();

        String args[] = DbHelper.makeArguments(ids.toArray(new Integer[ids.size()]));
        String params = DbHelper.makePlaceholders(args.length);
        db.delete(mTableName, "id IN (" + params + ")", args);

        db.setTransactionSuccessful();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        db.endTransaction();
        db.close();
    }
}