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.emergent.android.weave.syncadapter.SyncCache.java

public void reset() {
    SQLiteDatabase db = null;
    try {/*  ww  w  .j  ava 2s  .  c o  m*/
        db = m_helper.getWritableDatabase();
        int count = db.delete(KEY_HASH_TABLE_NAME, null, null);
        count += db.delete(META_GLOBAL_TABLE_NAME, null, null);
        Log.d(TAG, "SyncCacheKeyManager.resetCaches() : count = " + count);
    } finally {
        if (db != null)
            try {
                db.close();
            } catch (Exception ignored) {
            }
    }
}

From source file:edu.uillinois.wseemann.uicombatschedule.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    caldroidFragment = new CustomCaldroidFragment();

    if (savedInstanceState != null) {
        caldroidFragment.restoreStatesFromKey(savedInstanceState, "CALDROID_SAVED_STATE");
    } else {/*from ww  w  .j ava  2s.  co m*/
        Bundle args = new Bundle();
        Calendar cal = Calendar.getInstance();
        args.putInt(CaldroidFragment.MONTH, cal.get(Calendar.MONTH) + 1);
        args.putInt(CaldroidFragment.YEAR, cal.get(Calendar.YEAR));
        args.putBoolean(CaldroidFragment.ENABLE_SWIPE, true);
        args.putBoolean(CaldroidFragment.SIX_WEEKS_IN_CALENDAR, true);

        caldroidFragment.setArguments(args);
    }

    // Attach to the activity
    FragmentTransaction t = getSupportFragmentManager().beginTransaction();
    t.replace(android.R.id.content, caldroidFragment);
    t.commit();

    // Setup listener
    final CaldroidListener listener = new CaldroidListener() {

        @Override
        public void onSelectDate(Date date, View view) {
            String strDate = null;
            String info = null;

            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int month = cal.get(Calendar.MONTH) + 1;
            int day = cal.get(Calendar.DAY_OF_MONTH);
            int year = cal.get(Calendar.YEAR);

            String stringDate = month + "/" + day + "/" + year;

            Database database = new Database(MainActivity.this);
            SQLiteDatabase db = database.getReadableDatabase();

            Cursor cursor = db.query(Database.DATES_TABLE_NAME, null, Database.DATE + " = ?",
                    new String[] { stringDate }, null, null, null);

            if (cursor.moveToNext()) {
                strDate = cursor.getString(cursor.getColumnIndex(Database.DATE));
                info = cursor.getString(cursor.getColumnIndex(Database.INFO));
            }

            cursor.close();

            db.close();
            database.close();

            if (strDate != null && info != null) {
                ScheduleDialog dialog = ScheduleDialog.newInstance(strDate, info);
                dialog.show(getSupportFragmentManager(), "schedule");
            }
        }

        @Override
        public void onChangeMonth(int month, int year) {

        }

        @Override
        public void onLongClickDate(Date date, View view) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int month = cal.get(Calendar.MONTH) + 1;
            int day = cal.get(Calendar.DAY_OF_MONTH);
            int year = cal.get(Calendar.YEAR);

            if (month == 7 && day == 5) {
                String text = getString(R.string.butts);
                // show the easter egg for Katie :)
                Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
            }

            mDate = date;
            startActionMode();
        }

        @Override
        public void onCaldroidViewCreated() {

        }

    };

    caldroidFragment.setCaldroidListener(listener);
}

From source file:nz.co.wholemeal.christchurchmetro.Stop.java

public Stop(String platformTag, String platformNumber, Context context) throws InvalidPlatformNumberException {

    String queryBase = "SELECT platform_tag, platform_number, name, road_name, latitude, longitude FROM platforms ";
    String whereClause;/*from   ww w  .  j av  a2s.c  om*/
    String whereParameter;

    if (platformTag == null) {
        whereClause = "WHERE platform_number = ?";
        whereParameter = platformNumber;
    } else {
        whereClause = "WHERE platform_tag = ?";
        whereParameter = platformTag;
    }

    DatabaseHelper databaseHelper = new DatabaseHelper(context);
    SQLiteDatabase database = databaseHelper.getWritableDatabase();

    Cursor cursor = database.rawQuery(queryBase + whereClause, new String[] { whereParameter });

    if (cursor.moveToFirst()) {
        this.platformTag = cursor.getString(0);
        this.platformNumber = cursor.getString(1);
        this.name = cursor.getString(2);
        this.roadName = cursor.getString(3);
        this.latitude = cursor.getDouble(4);
        this.longitude = cursor.getDouble(5);
        cursor.close();
        database.close();
    } else {
        cursor.close();
        database.close();
        throw new InvalidPlatformNumberException("Invalid platform");
    }
}

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

public static void addAlarm(Context context, Lecture lecture, int alarmTimesIndex) {
    int[] alarm_times = { 0, 5, 10, 15, 30, 45, 60 };
    long when;/*from w w w  . j a  va  2  s  .c o  m*/
    Time time;
    long startTime;
    long startTimeInSeconds = lecture.dateUTC;

    if (startTimeInSeconds > 0) {
        when = startTimeInSeconds;
        startTime = startTimeInSeconds;
        time = new Time();
    } else {
        time = lecture.getTime();
        startTime = time.normalize(true);
        when = time.normalize(true);
    }
    long alarmTimeDiffInSeconds = alarm_times[alarmTimesIndex] * 60 * 1000;
    when -= alarmTimeDiffInSeconds;

    // DEBUG
    // when = System.currentTimeMillis() + (30 * 1000);

    time.set(when);
    MyApp.LogDebug("addAlarm", "Alarm time: " + time.format("%Y-%m-%dT%H:%M:%S%z") + ", in seconds: " + when);

    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra(BundleKeys.ALARM_LECTURE_ID, lecture.lecture_id);
    intent.putExtra(BundleKeys.ALARM_DAY, lecture.day);
    intent.putExtra(BundleKeys.ALARM_TITLE, lecture.title);
    intent.putExtra(BundleKeys.ALARM_START_TIME, startTime);
    intent.setAction(AlarmReceiver.ALARM_LECTURE);

    intent.setData(Uri.parse("alarm://" + lecture.lecture_id));

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingintent = PendingIntent.getBroadcast(context, Integer.parseInt(lecture.lecture_id),
            intent, 0);

    // Cancel any existing alarms for this lecture
    alarmManager.cancel(pendingintent);

    // Set new alarm
    alarmManager.set(AlarmManager.RTC_WAKEUP, when, pendingintent);

    int alarmTimeInMin = alarm_times[alarmTimesIndex];

    // write to DB

    AlarmsDBOpenHelper alarmDB = new AlarmsDBOpenHelper(context);

    SQLiteDatabase db = alarmDB.getWritableDatabase();

    // delete any previous alarms of this lecture
    try {
        db.beginTransaction();
        db.delete(AlarmsTable.NAME, AlarmsTable.Columns.EVENT_ID + "=?", new String[] { lecture.lecture_id });

        ContentValues values = new ContentValues();

        values.put(AlarmsTable.Columns.EVENT_ID, Integer.parseInt(lecture.lecture_id));
        values.put(AlarmsTable.Columns.EVENT_TITLE, lecture.title);
        values.put(AlarmsTable.Columns.ALARM_TIME_IN_MIN, alarmTimeInMin);
        values.put(AlarmsTable.Columns.TIME, when);
        DateFormat df = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT);
        values.put(AlarmsTable.Columns.TIME_TEXT, df.format(new Date(when)));
        values.put(AlarmsTable.Columns.DISPLAY_TIME, startTime);
        values.put(AlarmsTable.Columns.DAY, lecture.day);

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

    lecture.has_alarm = true;
}

From source file:com.raspi.chatapp.util.storage.MessageHistory.java

public void updateMessageStatus(String chatId, long _ID, String newStatus) {
    //Log.d("DATABASE", "Changing MessageStatus");
    int index = chatId.indexOf('@');
    if (index >= 0) {
        chatId = chatId.substring(0, index);
    }/*  www .j a va 2  s .com*/
    SQLiteDatabase db = mDbHelper.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_STATUS, newStatus);
    String whereClause = MessageHistoryContract.MessageEntry._ID + " == ?";
    db.update(chatId, values, whereClause, new String[] { Long.toString(_ID) });
    db.close();
}

From source file:github.popeen.dsub.util.SongDBHandler.java

public synchronized Pair<Integer, String> getIdFromPath(int serverKey, String path) {
    SQLiteDatabase db = this.getReadableDatabase();

    String[] columns = { SONGS_SERVER_KEY, SONGS_SERVER_ID };
    Cursor cursor = db.query(TABLE_SONGS, columns,
            SONGS_SERVER_KEY + " = ? AND " + SONGS_COMPLETE_PATH + " = ?",
            new String[] { Integer.toString(serverKey), path }, null, null, null, null);

    try {//from   w w w .  j  av  a 2s  . co m
        cursor.moveToFirst();
        return new Pair(cursor.getInt(0), cursor.getString(1));
    } catch (Exception e) {
        return null;
    } finally {
        db.close();
    }
}

From source file:com.dm.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 {/* ww  w .  ja  v  a  2s .c o  m*/
            Category category = new Category(cursor.getInt(0), cursor.getString(1), cursor.getString(2),
                    cursor.getInt(3) == 1, cursor.getInt(4) == 1, 0);
            categories.add(category);
        } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return categories;
}

From source file:com.example.jesse.barscan.BarcodeCaptureActivity.java

/**
 * onTap returns the tapped barcode result to the calling Activity.
 *//*from   w  ww.  ja  va  2 s. co m*/
public boolean onTap(float rawX, float rawY) {
    // Find tap point in preview frame coordinates.
    int[] location = new int[2];
    mGraphicOverlay.getLocationOnScreen(location);
    float x = (rawX - location[0]) / mGraphicOverlay.getWidthScaleFactor();
    float y = (rawY - location[1]) / mGraphicOverlay.getHeightScaleFactor();

    // Find the barcode whose center is closest to the tapped point.
    Barcode best = null;
    float bestDistance = Float.MAX_VALUE;
    for (BarcodeGraphic graphic : mGraphicOverlay.getGraphics()) {
        Barcode barcode = graphic.getBarcode();
        if (barcode.getBoundingBox().contains((int) x, (int) y)) {
            // Exact hit, no need to keep looking.
            best = barcode;
            break;
        }
        float dx = x - barcode.getBoundingBox().centerX();
        float dy = y - barcode.getBoundingBox().centerY();
        float distance = (dx * dx) + (dy * dy); // actually squared distance
        if (distance < bestDistance) {
            best = barcode;
            bestDistance = distance;
        }
    }

    if (best != null) {
        Intent data = new Intent();
        data.putExtra(BarcodeObject, best);
        setResult(CommonStatusCodes.SUCCESS, data);

        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.barcode_toast,
                (ViewGroup) findViewById(R.id.custom_toast_container));

        Barcode barcode = data.getParcelableExtra(BarcodeCaptureActivity.BarcodeObject);
        //Barcode.DriverLicense dlBarcode = barcode.driverLicense;

        Barcode.DriverLicense sample = barcode.driverLicense;

        TextView name = (TextView) layout.findViewById(R.id.name);
        TextView address = (TextView) layout.findViewById(R.id.address);
        TextView cityStateZip = (TextView) layout.findViewById(R.id.cityStateZip);
        TextView gender = (TextView) layout.findViewById(R.id.gender);
        TextView dob = (TextView) layout.findViewById(R.id.dob);
        TableLayout tbl = (TableLayout) layout.findViewById(R.id.tableLayout);

        try {
            int age = DateDifference.generateAge(sample.birthDate);
            if (age < minAge)
                tbl.setBackgroundColor(Color.parseColor("#980517"));
            else
                tbl.setBackgroundColor(Color.parseColor("#617C17"));

        } catch (ParseException e) {
            e.printStackTrace();
        }

        String cityContent = new String(
                sample.addressCity + ", " + sample.addressState + " " + (sample.addressZip).substring(0, 5));

        address.setText(sample.addressStreet);
        cityStateZip.setText(cityContent);

        String genderString;
        if ((sample.gender).equals("1"))
            genderString = "Male";
        else if ((sample.gender).equals("2"))
            genderString = "Female";
        else
            genderString = "Other";

        gender.setText(genderString);

        dob.setText((sample.birthDate).substring(0, 2) + "/" + (sample.birthDate).substring(2, 4) + "/"
                + (sample.birthDate).substring(4, 8));

        String nameString = new String(sample.firstName + " " + sample.middleName + " " + sample.lastName);

        name.setText(nameString);

        Toast toast = new Toast(getApplicationContext());
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();

        Date today = Calendar.getInstance().getTime();
        String reportDate = df.format(today);
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues row = new ContentValues();
        row.put("dateVar", reportDate);
        row.put("dobVar", sample.birthDate);
        row.put("zipVar", sample.addressZip);
        row.put("genderVar", genderString);
        db.insert("test", null, row);
        db.close();

        return true;
    }
    return false;
}

From source file:com.openatk.rockapp.MainActivity.java

private void addRock() {
    Location myLoc = map.getMyLocation();
    LatLng where = null;//  w  w w .ja v  a 2  s  . c  o  m
    if (myLoc == null) {
        where = map.getCameraPosition().target;
    } else {
        // See if location is on screen
        LatLng myLatLng = new LatLng(myLoc.getLatitude(), myLoc.getLongitude());
        if (map.getProjection().getVisibleRegion().latLngBounds.contains(myLatLng)) {
            // Location is on screen set marker there
            where = myLatLng;
        } else {
            // Location is off screen, use center of screen
            where = map.getCameraPosition().target;
        }
    }
    Log.d("MainActivity", "Add rock");
    // Rock and save in DB (triggering it to display on the map)
    Rock rock = new Rock(this, where.latitude, where.longitude, false);
    rock.setTrelloId("");
    rock.setHasSynced(false);
    rock.setPosChanged(new Date());

    SQLiteDatabase database = dbHelper.getWritableDatabase();
    rock.save(database);
    database.close();
    dbHelper.close();

    slideMenu.editRock(rock);
    setState(STATE_ROCK_EDIT);
    selectRock(rock.getId());
}

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

private String getYesterday(String owner) {
    //Log.d("MainActivity", "getYesterday() called: " + owner);
    StringBuilder sb = new StringBuilder();
    String results = "";
    sb.append("select notes_note from notes where notes_owner='");
    sb.append(currentOwner);/*  www . j  a v  a  2s  . com*/

    Calendar calendar = new GregorianCalendar();
    int day = calendar.get(Calendar.DAY_OF_WEEK);
    if (day == 2) {
        //it is Monday so retrieve Friday
        sb.append("' and date(notes_date)=date('now','localtime','-3 day')");
    } else {
        //not Monday
        sb.append("' and date(notes_date)=date('now','localtime','-1 day')");
    }

    DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    cursor = db.rawQuery(sb.toString(), null);
    if (cursor.getCount() > 0) {
        cursor.moveToNext();
        int notesColumn = cursor.getColumnIndex(Notes.NOTE);
        //Log.d("MainActivity.getYesterday()", "notesColumn: " + notesColumn);
        results = cursor.getString(notesColumn);

    }

    cursor.close();
    db.close();
    return results;
}