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.cuddlesoft.nori.database.APISettingsDatabase.java

/**
 * Update an existing {@link SearchClient.Settings} object in the database.
 *
 * @param id       Row ID.//from   ww  w  .  j av a  2 s .  c om
 * @param settings Settings object with data to update.
 * @return Number of rows affected.
 */
public int update(long id, SearchClient.Settings settings) {
    // Update data in the database.
    SQLiteDatabase db = getWritableDatabase();
    final int rows = db.update(TABLE_NAME, searchClientSettingsToContentValues(settings), COLUMN_ID + " = ?",
            new String[] { Long.toString(id) });
    db.close();

    sendUpdateNotification();
    return rows;
}

From source file:nerd.tuxmobil.fahrplan.congress.FahrplanMisc.java

public static void writeHighlight(Context context, Lecture lecture) {
    HighlightDBOpenHelper highlightDB = new HighlightDBOpenHelper(context);

    SQLiteDatabase db = highlightDB.getWritableDatabase();

    try {/*  w  w w  .j  a  v  a  2  s  . c o  m*/
        db.beginTransaction();
        db.delete(HighlightsTable.NAME, HighlightsTable.Columns.EVENT_ID + "=?",
                new String[] { lecture.lecture_id });

        ContentValues values = new ContentValues();

        values.put(HighlightsTable.Columns.EVENT_ID, Integer.parseInt(lecture.lecture_id));
        int highlightState = lecture.highlight ? HighlightsTable.Values.HIGHLIGHT_STATE_ON
                : HighlightsTable.Values.HIGHLIGHT_STATE_OFF;
        values.put(HighlightsTable.Columns.HIGHLIGHT, highlightState);

        db.insert(HighlightsTable.NAME, null, values);
        db.setTransactionSuccessful();
    } catch (SQLException e) {
    } finally {
        db.endTransaction();
        db.close();
    }
}

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

public static Vector<Long> getPendingOutgoingMessageIds(Context context) {

    Vector<Long> retVal = null;
    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbread = db.getReadableDatabase();

    Cursor c = dbread.rawQuery("SELECT _id FROM offline_sent_posts", null);
    int count = c.getCount();

    if (count == 0) {
        retVal = new Vector<Long>(0);
    } else {/*from  w  w  w.  j a  v a2s  . c  o  m*/
        retVal = new Vector<Long>(count);
        c.moveToFirst();

        for (int i = 0; i < count; i++) {
            retVal.add(c.getLong(0));
            c.moveToNext();
        }
    }

    c.close();
    dbread.close();
    db.close();
    return retVal;
}

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

public void saveArticle(String title, String uri, String webview) {
    String domain = uri.replaceAll("https?://", "").replaceAll("[w]{3}\\.", "").replaceAll("/.*", "");

    ContentValues savedArticlesContentValues = new ContentValues();
    savedArticlesContentValues.put(SavedArticlesSQLiteHelper.COLUMN_TITLE, title);
    savedArticlesContentValues.put(SavedArticlesSQLiteHelper.COLUMN_DOMAIN, domain);
    savedArticlesContentValues.put(SavedArticlesSQLiteHelper.COLUMN_URI, uri);
    savedArticlesContentValues.put(SavedArticlesSQLiteHelper.COLUMN_WEBVIEW, webview);

    SQLiteDatabase savedArticlesSqLiteDatabase = new SavedArticlesSQLiteHelper(mContext).getWritableDatabase();

    savedArticlesSqLiteDatabase.insert(SavedArticlesSQLiteHelper.TABLE, null, savedArticlesContentValues);

    savedArticlesSqLiteDatabase.close();

    showToast(mContext.getString(R.string.saved_articles_article_saved), 0);
}

From source file:com.example.google.touroflondon.data.TourDbHelper.java

/**
 * Extract POI data from a {@link JSONArray} of points of interest and add
 * it to the POI table.//from   ww w.ja  v  a 2 s  .  c  o  m
 * 
 * @param data
 */
public void loadPois(JSONArray data) throws JSONException {

    SQLiteDatabase db = this.getWritableDatabase();

    // empty the POI table to remove all existing data
    db.delete(TourContract.PoiEntry.TABLE_NAME, null, null);

    // need to complete transaction first to clear data
    db.close();

    // begin the insert transaction
    db = this.getWritableDatabase();
    db.beginTransaction();

    // Loop over each point of interest in array
    for (int i = 0; i < data.length(); i++) {
        JSONObject poi = data.getJSONObject(i);

        // Extract POI properties
        final String title = poi.getString("title");
        final String type = poi.getString("type");
        final String description = poi.getString("description");
        final String pictureUrl = poi.getString("pictureUrl");
        final String pictureAttr = poi.getString("pictureAttr");

        // Location
        JSONObject location = poi.getJSONObject("location");
        final double lat = location.getDouble("lat");
        final double lng = location.getDouble("lng");

        // Create content values object for insert
        ContentValues cv = new ContentValues();
        cv.put(TourContract.PoiEntry.COLUMN_NAME_TITLE, title);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_TYPE, type);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_DESCRIPTION, description);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_PICTURE_URL, pictureUrl);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_LOCATION_LAT, lat);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_LOCATION_LNG, lng);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_PICTURE_ATTR, pictureAttr);

        // Insert data
        db.insert(TourContract.PoiEntry.TABLE_NAME, null, cv);
    }

    // All insert statement have been submitted, mark transaction as
    // successful
    db.setTransactionSuccessful();

    if (db != null) {
        db.endTransaction();
    }

}

From source file:org.egov.android.data.SQLiteHelper.java

/**
 * Get total records in particular table
 * //w ww .  ja  v  a  2 s .c o  m
 * @param table
 * @param selection
 * @param selectionArgs
 * @param limit
 * @return int
 */

public int getRecordCount(String table, String selection, String[] selectionArgs, String limit) {
    try {
        String[] columns = { " count(*) as totalRows" };
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.query(table, columns, selection, selectionArgs, null, null, null, limit);
        cursor.moveToFirst();
        int rows = cursor.getInt(0);
        cursor.close();
        db.close();
        return rows;
    } catch (Exception ex) {
        ex.printStackTrace();
        return 0;
    }
}

From source file:asu.edu.msse.gpeddabu.moviedescriptions.AddMovie.java

public void getGenreList() {
    genreArr = new ArrayList<>();
    try {/*  ww  w.  j ava 2 s.c  om*/
        MovieDB db = new MovieDB(con);
        SQLiteDatabase crsDB = db.openDB();
        Cursor cur = crsDB.rawQuery("select distinct genre from movie;", null);
        while (cur.moveToNext()) {
            genreArr.add(cur.getString(0));
        }
        cur.close();
        crsDB.close();
        db.close();
    } catch (Exception ex) {
        android.util.Log.w(this.getClass().getSimpleName(), "Exception getting genre info: " + ex.getMessage());
    }
}

From source file:com.example.android.touroflondon.data.TourDbHelper.java

/**
 * Extract POI data from a {@link JSONArray} of points of interest and add it to the POI table.
 *
 * @param data/*from w  w  w  .j  a  v  a 2s. c  o  m*/
 */
public void loadPois(JSONArray data) throws JSONException {

    SQLiteDatabase db = this.getWritableDatabase();

    // empty the POI table to remove all existing data
    db.delete(TourContract.PoiEntry.TABLE_NAME, null, null);

    // need to complete transaction first to clear data
    db.close();

    // begin the insert transaction
    db = this.getWritableDatabase();
    db.beginTransaction();

    // Loop over each point of interest in array
    for (int i = 0; i < DataStore.getAllCoupons().size(); i++) {
        Coupon coupon = DataStore.getAllCoupons().get(i);
        //Extract POI properties
        final String storeName = coupon.getStoreName();
        String details = coupon.getTitle();
        details = details.replace("<h1>", "").replace("</h1>", "");

        final Double lat = coupon.getLatitude();
        final Double lng = coupon.getLongitude();
        /* 
        /final String type = poi.getString("type");
         final String description = poi.getString("description");
         final String pictureUrl = poi.getString("pictureUrl");
         final String pictureAttr = poi.getString("pictureAttr");
                
         // Location
         JSONObject location = poi.getJSONObject("location");
         final double lat = location.getDouble("lat");
         final double lng = location.getDouble("lng");
         */
        // Create content values object for insert
        ContentValues cv = new ContentValues();
        cv.put(TourContract.PoiEntry.COLUMN_NAME_TITLE, storeName);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_TYPE, "LANDMARK");
        cv.put(TourContract.PoiEntry.COLUMN_NAME_DESCRIPTION, details);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_LOCATION_LAT, lat);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_LOCATION_LNG, lng);

        // Insert data
        db.insert(TourContract.PoiEntry.TABLE_NAME, null, cv);
    }

    // All insert statement have been submitted, mark transaction as successful
    db.setTransactionSuccessful();

    if (db != null) {
        db.endTransaction();
    }

}

From source file:com.evandroid.musica.broadcastReceiver.MusicBroadcastReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    /** Google Play Music
     //bool streaming            long position
     //long albumId               String album
     //bool currentSongLoaded      String track
     //long ListPosition         long ListSize
     //long id                  bool playing
     //long duration            int previewPlayType
     //bool supportsRating         int domain
     //bool albumArtFromService      String artist
     //int rating               bool local
     //bool preparing            bool inErrorState
     *///from www. ja  va2 s . c o  m

    Bundle extras = intent.getExtras();
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
    boolean lengthFilter = sharedPref.getBoolean("pref_filter_20min", true);

    if (extras != null)
        try {
            extras.getInt("state");
        } catch (BadParcelableException e) {
            return;
        }

    if (extras == null || extras.getInt("state") > 1 //Tracks longer than 20min are presumably not songs
            || (lengthFilter && (extras.get("duration") instanceof Long && extras.getLong("duration") > 1200000)
                    || (extras.get("duration") instanceof Double && extras.getDouble("duration") > 1200000)
                    || (extras.get("duration") instanceof Integer && extras.getInt("duration") > 1200))
            || (lengthFilter && (extras.get("secs") instanceof Long && extras.getLong("secs") > 1200000)
                    || (extras.get("secs") instanceof Double && extras.getDouble("secs") > 1200000)
                    || (extras.get("secs") instanceof Integer && extras.getInt("secs") > 1200)))
        return;

    String artist = extras.getString("artist");
    String track = extras.getString("track");
    long position = extras.containsKey("position") ? extras.getLong("position") : -1;
    if (extras.get("position") instanceof Double)
        position = Double.valueOf(extras.getDouble("position")).longValue();
    boolean isPlaying = extras.getBoolean("playing", true);

    if (intent.getAction().equals("com.amazon.mp3.metachanged")) {
        artist = extras.getString("com.amazon.mp3.artist");
        track = extras.getString("com.amazon.mp3.track");
    } else if (intent.getAction().equals("com.spotify.music.metadatachanged"))
        isPlaying = spotifyPlaying;
    else if (intent.getAction().equals("com.spotify.music.playbackstatechanged"))
        spotifyPlaying = isPlaying;

    if ((artist == null || "".equals(artist)) //Could be problematic
            || (track == null || "".equals(track) || track.startsWith("DTNS"))) // Ignore one of my favorite podcasts
        return;

    SharedPreferences current = context.getSharedPreferences("current_music", Context.MODE_PRIVATE);
    String currentArtist = current.getString("artist", "");
    String currentTrack = current.getString("track", "");

    SharedPreferences.Editor editor = current.edit();
    editor.putString("artist", artist);
    editor.putString("track", track);
    editor.putLong("position", position);
    editor.putBoolean("playing", isPlaying);
    if (isPlaying) {
        long currentTime = System.currentTimeMillis();
        editor.putLong("startTime", currentTime);
    }
    editor.apply();

    autoUpdate = autoUpdate || sharedPref.getBoolean("pref_auto_refresh", false);
    int notificationPref = Integer.valueOf(sharedPref.getString("pref_notifications", "0"));

    if (autoUpdate && App.isActivityVisible()) {
        Intent internalIntent = new Intent("Broadcast");
        internalIntent.putExtra("artist", artist).putExtra("track", track);
        LyricsViewFragment.sendIntent(context, internalIntent);
        forceAutoUpdate(false);
    }

    SQLiteDatabase db = new DatabaseHelper(context).getReadableDatabase();
    boolean inDatabase = DatabaseHelper.presenceCheck(db, new String[] { artist, track, artist, track });
    db.close();

    if (notificationPref != 0 && isPlaying && (inDatabase || OnlineAccessVerifier.check(context))) {
        Intent activityIntent = new Intent("com.geecko.QuickLyric.getLyrics").putExtra("TAGS",
                new String[] { artist, track });
        Intent wearableIntent = new Intent("com.geecko.QuickLyric.SEND_TO_WEARABLE").putExtra("artist", artist)
                .putExtra("track", track);
        PendingIntent openAppPending = PendingIntent.getActivity(context, 0, activityIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        PendingIntent wearablePending = PendingIntent.getBroadcast(context, 8, wearableIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        NotificationCompat.Action wearableAction = new NotificationCompat.Action.Builder(R.drawable.ic_watch,
                context.getString(R.string.wearable_prompt), wearablePending).build();

        NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(context);
        NotificationCompat.Builder wearableNotifBuilder = new NotificationCompat.Builder(context);

        if ("0".equals(sharedPref.getString("pref_theme", "0")))
            notifBuilder.setColor(context.getResources().getColor(R.color.primary));

        notifBuilder.setSmallIcon(R.drawable.ic_notif).setContentTitle(context.getString(R.string.app_name))
                .setContentText(String.format("%s - %s", artist, track)).setContentIntent(openAppPending)
                .setVisibility(-1) // Notification.VISIBILITY_SECRET
                .setGroup("Lyrics_Notification").setGroupSummary(true);

        wearableNotifBuilder.setSmallIcon(R.drawable.ic_notif)
                .setContentTitle(context.getString(R.string.app_name))
                .setContentText(String.format("%s - %s", artist, track)).setContentIntent(openAppPending)
                .setVisibility(-1) // Notification.VISIBILITY_SECRET
                .setGroup("Lyrics_Notification").setOngoing(false).setGroupSummary(false)
                .extend(new NotificationCompat.WearableExtender().addAction(wearableAction));

        if (notificationPref == 2) {
            notifBuilder.setOngoing(true).setPriority(-2); // Notification.PRIORITY_MIN
        } else
            notifBuilder.setPriority(-1); // Notification.PRIORITY_LOW

        Notification notif = notifBuilder.build();
        Notification wearableNotif = wearableNotifBuilder.build();

        if (notificationPref == 2)
            notif.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
        else
            notif.flags |= Notification.FLAG_AUTO_CANCEL;

        NotificationManagerCompat.from(context).notify(0, notif);
        try {
            context.getPackageManager().getPackageInfo("com.google.android.wearable.app",
                    PackageManager.GET_META_DATA);
            NotificationManagerCompat.from(context).notify(8, wearableNotif);
        } catch (PackageManager.NameNotFoundException ignored) {
        }
    } else if (track.equals(current.getString("track", "")))
        NotificationManagerCompat.from(context).cancel(0);
}

From source file:asu.edu.msse.gpeddabu.moviedescriptions.AddMovie.java

public void onAddButtonClick(View view) throws JSONException {

    // Adding movie title
    EditText tempText = (EditText) findViewById(R.id.titleET);
    String title = tempText.getText().toString();

    // Adding movie Year
    tempText = (EditText) findViewById(R.id.yearET);
    String year = tempText.getText().toString();

    // Adding movie Rated
    tempText = (EditText) findViewById(R.id.ratedET);
    String rated = tempText.getText().toString();

    // Adding movie Released On
    tempText = (EditText) findViewById(R.id.releasedOnET);
    String released = tempText.getText().toString();

    // Adding movie Runtime
    tempText = (EditText) findViewById(R.id.runtimeET);
    String runtime = tempText.getText().toString();

    // Adding movie Genre
    String genre = (String) spinner.getSelectedItem();

    // Adding movie Actors
    tempText = (EditText) findViewById(R.id.actorsET);
    String actors = tempText.getText().toString();

    // Adding movie plot
    tempText = (EditText) findViewById(R.id.plotET);
    String plot = tempText.getText().toString();

    // Adding movie poster url
    tempText = (EditText) findViewById(R.id.posterET);
    String poster = tempText.getText().toString();
    try {//from www . j  ava 2 s.  c o  m
        MovieDB db = new MovieDB(con);
        SQLiteDatabase crsDB = db.openDB();
        crsDB.execSQL("insert into movie values(?,?,?,?,?,?,?,?,?);",
                new String[] { title, year, rated, released, runtime, genre, actors, plot, poster });
        crsDB.close();
        db.close();
    } catch (Exception ex) {
        android.util.Log.w(this.getClass().getSimpleName(), "Exception adding movie info: " + ex.getMessage());
    }
    Intent ni = new Intent(this, MainActivity.class);
    startActivity(ni);
}