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.dm.material.dashboard.candybar.databases.Database.java

public SparseArrayCompat<Wallpaper> getWallpapers() {
    SparseArrayCompat<Wallpaper> wallpapers = new SparseArrayCompat<>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(TABLE_WALLPAPERS, null, null, null, null, null, KEY_ADDED_ON + " DESC, " + KEY_ID);
    if (cursor.moveToFirst()) {
        do {//from w  ww  . j  ava  2s  .  com
            Wallpaper wallpaper = new Wallpaper(cursor.getString(1), cursor.getString(2), cursor.getString(3),
                    cursor.getString(4));
            wallpapers.append(wallpapers.size(), wallpaper);
        } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return wallpapers;
}

From source file:com.esri.squadleader.model.GeoPackageReader.java

/**
 * Reads the tables in a GeoPackage, makes a layer from each table, and returns a list containing
 * those layers.//from  w  w w  . j ava  2  s .c om
 *
 * @param gpkgPath       the full path to the .gpkg file.
 * @param sr             the spatial reference to which any raster layers should be projected, typically the
 *                       spatial reference of your map.
 * @param showVectors    if true, this method will include the GeoPackage's vector layers.
 * @param showRasters    if true, this method will include the GeoPackage's raster layer.
 * @param rasterRenderer the renderer to be used for raster layers. One simple option is an RGBRenderer.
 * @param markerRenderer the renderer to be used for point layers.
 * @param lineRenderer   the renderer to be used for polyline layers.
 * @param fillRenderer   the renderer to be used for polygon layers.
 * @return a list of the layers created for all tables in the GeoPackage.
 * @throws IOException if gpkgPath cannot be read. Possible reasons include the file not
 *                     existing, failure to request READ_EXTERNAL_STORAGE or
 *                     WRITE_EXTERNAL_STORAGE permission, or the GeoPackage containing an
 *                     invalid spatial reference.
 */
public List<Layer> readGeoPackageToLayerList(String gpkgPath, SpatialReference sr, boolean showVectors,
        boolean showRasters, RasterRenderer rasterRenderer, Renderer markerRenderer, Renderer lineRenderer,
        Renderer fillRenderer) throws IOException {
    List<Layer> layers = new ArrayList<Layer>();

    if (showRasters) {
        // Check to see if there are any rasters before loading them
        SQLiteDatabase sqliteDb = null;
        Cursor cursor = null;
        try {
            sqliteDb = SQLiteDatabase.openDatabase(gpkgPath, null, SQLiteDatabase.OPEN_READONLY);
            cursor = sqliteDb.rawQuery("SELECT COUNT(*) FROM gpkg_contents WHERE data_type = ?",
                    new String[] { "tiles" });
            if (cursor.moveToNext()) {
                if (0 < cursor.getInt(0)) {
                    cursor.close();
                    sqliteDb.close();
                    FileRasterSource src = new FileRasterSource(gpkgPath);
                    rasterSources.add(src);
                    if (null != sr) {
                        src.project(sr);
                    }
                    RasterLayer rasterLayer = new RasterLayer(src);
                    rasterLayer.setRenderer(rasterRenderer);
                    rasterLayer
                            .setName((gpkgPath.contains("/") ? gpkgPath.substring(gpkgPath.lastIndexOf("/") + 1)
                                    : gpkgPath) + " (raster)");
                    layers.add(rasterLayer);
                }
            }
        } catch (Throwable t) {
            Log.e(TAG, "Could not read raster(s) from GeoPackage", t);
        } finally {
            if (null != cursor) {
                cursor.close();
            }
            if (null != sqliteDb) {
                sqliteDb.close();
            }
        }
    }

    if (showVectors) {
        Geopackage gpkg;
        try {
            gpkg = new Geopackage(gpkgPath);
        } catch (RuntimeException ex) {
            throw new IOException(null != ex.getMessage() && ex.getMessage().contains("unknown wkt")
                    ? "Geopackage " + gpkgPath + " contains an invalid spatial reference."
                    : null, ex);
        }
        geopackages.add(gpkg);
        List<GeopackageFeatureTable> tables = gpkg.getGeopackageFeatureTables();
        if (0 < tables.size()) {
            //First pass: polygons and unknowns
            HashSet<Geometry.Type> types = new HashSet<Geometry.Type>();
            types.add(Geometry.Type.ENVELOPE);
            types.add(Geometry.Type.POLYGON);
            types.add(Geometry.Type.UNKNOWN);
            layers.addAll(getTablesAsLayers(tables, types, fillRenderer));

            //Second pass: lines
            types.clear();
            types.add(Geometry.Type.LINE);
            types.add(Geometry.Type.POLYLINE);
            layers.addAll(getTablesAsLayers(tables, types, lineRenderer));

            //Third pass: points
            types.clear();
            types.add(Geometry.Type.MULTIPOINT);
            types.add(Geometry.Type.POINT);
            layers.addAll(getTablesAsLayers(tables, types, markerRenderer));
        }
    }

    return layers;
}

From source file:com.onesignal.OneSignal.java

static boolean isDuplicateNotification(String id, Context context) {
    if (id == null || "".equals(id))
        return false;

    OneSignalDbHelper dbHelper = new OneSignalDbHelper(context);
    SQLiteDatabase readableDb = dbHelper.getReadableDatabase();

    String[] retColumn = { NotificationTable.COLUMN_NAME_NOTIFICATION_ID };
    String[] whereArgs = { id };/*from  w  w  w .  ja va  2s . c  o m*/

    Cursor cursor = readableDb.query(NotificationTable.TABLE_NAME, retColumn,
            NotificationTable.COLUMN_NAME_NOTIFICATION_ID + " = ?", // Where String
            whereArgs, null, null, null);

    boolean exists = cursor.moveToFirst();
    cursor.close();
    readableDb.close();

    if (exists) {
        Log(LOG_LEVEL.DEBUG, "Duplicate GCM message received, skipping processing. " + id);
        return true;
    }

    return false;
}

From source file:heartware.com.heartware_master.DBAdapter.java

public void createMeetup(HashMap<String, String> queryValues) {
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(USER_ID, queryValues.get(USER_ID));
    values.put(NOTE, queryValues.get(NOTE));
    values.put(EXERCISE, queryValues.get(EXERCISE));
    values.put(LOCATION, queryValues.get(LOCATION));
    values.put(DATE, queryValues.get(DATE));
    values.put(PEOPLE, queryValues.get(PEOPLE));
    database.insert(MEETUPS_TABLE, null, values);
    database.close();
}

From source file:com.almarsoft.GroundhogReader.lib.DBUtils.java

public static void banUser(String decodedfrom, Context context) {
    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbwrite = db.getWritableDatabase();

    Cursor c = dbwrite.rawQuery("SELECT _id FROM banned_users " + " WHERE name=" + esc(decodedfrom), null);

    if (c.getCount() > 0) {
        c.moveToFirst();/*from   ww  w . ja  v  a2  s.  c  o m*/
        dbwrite.execSQL("UPDATE banned_users SET bandisabled=0 WHERE _id=" + c.getInt(0));
    } else {
        ContentValues cv = new ContentValues();
        cv.put("name", decodedfrom);
        cv.put("bandisabled", 0);
        dbwrite.insert("banned_users", null, cv);
    }

    // Mark all the user posts as read, so they get deleted later
    dbwrite.execSQL("UPDATE headers SET read=1, read_unixdate=" + System.currentTimeMillis()
            + " WHERE from_header=" + esc(decodedfrom));

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

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

private void getNotes() {
    //Log.d("MainActivity", "getYesterday() called: " + owner);

    DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    cursor = db.rawQuery("select goals_note from goals", null);
    if (cursor.getCount() > 0) {
        cursor.moveToNext();//from   w ww.  j  a va 2  s  .  co  m
        int notesColumn = cursor.getColumnIndex(Goals.NOTE);
        //Log.d("MainActivity.getYesterday()", "notesColumn: " + notesColumn);
        note.setText(cursor.getString(notesColumn));

    } else {
        note.setText("");
    }
    cursor.close();
    db.close();
}

From source file:com.almarsoft.GroundhogReader.lib.DBUtils.java

public static long insertArticleToGroupID(int groupID, Article articleInfo, String finalRefs, String finalFrom,
        String finalSubject, Context context, SQLiteDatabase catchedDB) {

    // The called can create a single SQLiteDatabase object to avoid too many object
    // creations if we're inside a loop
    DBHelper db = null;//from  w  w w. ja v a  2s. co m
    SQLiteDatabase dbwrite = null;

    if (catchedDB == null) {
        db = new DBHelper(context);
        dbwrite = db.getWritableDatabase();
    } else {
        dbwrite = catchedDB;
    }

    ContentValues cv = new ContentValues();
    cv.put("subscribed_group_id", groupID);
    cv.put("reference_list", finalRefs);
    cv.put("server_article_id", articleInfo.getArticleId());
    cv.put("date", articleInfo.getDate());
    cv.put("server_article_number", articleInfo.getArticleNumber());
    cv.put("from_header", finalFrom);
    cv.put("subject_header", finalSubject);
    cv.put("read", 0);
    cv.put("catched", 0);

    long ret = dbwrite.insert("headers", null, cv);

    if (catchedDB == null) {
        dbwrite.close();
        db.close();
    }
    return ret;
}

From source file:com.matthewmitchell.wakeifyplus.database.AlarmCursorAdapter.java

@Override
public void bindView(View v, Context context, Cursor c) {

    final String name = c.getString(c.getColumnIndex("name"));
    final long time = c.getLong(c.getColumnIndex("time"));

    TextView time_text = (TextView) v.findViewById(R.id.time);
    if (time_text != null) {
        time_text.setText(date_format.format(new Date(time)));
    }//from   w  ww. j  a  v a 2  s .com

    TextView name_text = (TextView) v.findViewById(R.id.name);
    if (name_text != null) {
        name_text.setText(name);
    }

    // Do on/off button alarm code

    CompoundButton onOff = (CompoundButton) v.findViewById(R.id.alarm_switch);
    // Make sure the change listener is not set for setting value from database.
    onOff.setOnCheckedChangeListener(null);
    onOff.setChecked(c.getInt(c.getColumnIndex("onOff")) == 1);
    final Context contextl = context;
    final long id = c.getInt(c.getColumnIndex("_id"));
    onOff.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            AlarmDatabase database = new AlarmDatabase(contextl);
            SQLiteDatabase write = database.getWritableDatabase();
            ContentValues values = new ContentValues(1);
            if (isChecked) {
                // Alarm has been turned on
                values.put("onOff", 1);
                // Add system alarm
                AlarmReceiver.scheduleAlarm(contextl, id, false);
            } else {
                // Alarm has been switched off
                values.put("onOff", 0);
                AlarmReceiver.removeAlarm(contextl, id);
            }
            write.update(AlarmDatabase.ALARMS_TABLE, values, "_id = " + id, null);
            write.close();
            database.close();
            // Reload cursor
            main.getSupportLoaderManager().restartLoader(0, null, main);
        }

    });
}

From source file:tk.android.client.activity.Activity_client.java

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.button_version: {
        try {//from  w  w  w . ja v  a 2 s  . c  om
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(PLAY_STORE_URL)));
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
        break;
    }
    case R.id.layout_support: {
        startActivity(new Intent(activity, Activity_user.class)
                .setData(Uri.parse("https://twitter.com/OrangeSphereApp")));
        break;
    }
    case R.id.layout_pro: {
        if (PropertyManager.getInstance().isProUser()) {
            Toast.makeText(activity, "You alreadry Pro User :)", Toast.LENGTH_SHORT).show();
            break;
        }
        String TAG = "EditDialog-Pro";
        final EditDialog dialog = new EditDialog();
        dialog.newInstance(activity);
        dialog.setTitle(R.string.advertisement);
        dialog.setOnFinishEditListener(new OnFinishEditListener() {

            @Override
            public void onFinishEdit(final String text) {
                int length = text.length();
                if (length > 100 || length == 0) {
                    Toast.makeText(activity, R.string.bad_string_length, Toast.LENGTH_SHORT).show();
                    return;
                }
                dialog.dismiss();
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            Twitter twitter = core.getTwitter();
                            if (twitter == null) {
                                throw new Exception();
                            }
                            twitter.updateStatus(text + " " + PLAY_STORE_URL + " #OrangeSphere");
                            PropertyManager.getInstance().toBeProUser();
                            SQLiteManager manager = new SQLiteManager(activity);
                            SQLiteDatabase db = manager.getWritableDatabase();
                            ContentValues values = new ContentValues();
                            values.put("client_name", "OrangeSpherePro");
                            values.put("consumer_key", "b1NEqKgA8CGudo6yhkg");
                            values.put("consumer_secret", "awqnQwi3BXUqkyjlMZHlDIvad3bV3cVO03MxRTV4s");
                            db.insert("client_table", null, values);
                            db.close();
                            new UiHandler() {

                                @Override
                                public void run() {
                                    Toast.makeText(activity, R.string.be_pro_user, Toast.LENGTH_SHORT).show();
                                }

                            }.post();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                }).start();
            }

        });
        dialog.show(getSupportFragmentManager(), TAG);
        break;
    }
    case R.id.layout_license: {
        new LicenseDialog().show(getSupportFragmentManager(), "LicenseDialog");
        break;
    }
    }
}

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

private void search(final String string, boolean cache) {
    try {/*from ww  w .  j  a  v a 2 s. co m*/
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);

        String apiUri = getString(R.string.project_website_uri) + "api/1/interactions/?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);
                    mNoInteractionsLayout.setVisibility(View.VISIBLE);
                } else {
                    if (mTools.isTablet()) {
                        int spanCount = (response.length() == 1) ? 1 : 2;

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

                    mRecyclerView.setAdapter(new InteractionsCardsAdapter(mContext, mProgressBar, response));

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

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

                    sqLiteDatabase.delete(InteractionsSQLiteHelper.TABLE, InteractionsSQLiteHelper.COLUMN_STRING
                            + " = " + mTools.sqe(string) + " COLLATE NOCASE", null);
                    sqLiteDatabase.insert(InteractionsSQLiteHelper.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.interactions_cards_something_went_wrong), 1);

                finish();

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

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