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.odoo.orm.OModel.java

/**
 * Creates the./* w  ww.j av  a 2s.  co  m*/
 * 
 * @param values
 *            the values
 * @return the int
 */
public int create(OValues values) {
    if (!values.contains("odoo_name")) {
        values.put("odoo_name", mUser.getAndroidName());
    }
    ContentValues vals = createValues(values);
    SQLiteDatabase db = getWritableDatabase();
    db.insert(getTableName(), null, vals);
    db.close();
    int newId = getCreateId();
    values.put(OColumn.ROW_ID, newId);
    updateRelationColumns(values);
    sendDatasetChangeBroadcast(newId);
    notifyDataChange(newId);
    return newId;
}

From source file:com.sina.weibo.sdk.demo.sample.activity.TestFragment.java

public void saveData(ArrayList<Status> statusList) {
    SQLiteDatabase databaseHelper = Utils.getDatabaseHelper().getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    for (Status status : statusList) {
        //            contentValues.put("id", Long.parseLong(status.idstr));
        contentValues.put("name", status.user.name);
        contentValues.put("gender", status.user.gender);
        contentValues.put("location", status.user.location);
        contentValues.put("description", status.user.description);
        contentValues.put("followers_count", status.user.followers_count);
        contentValues.put("friends_count", status.user.friends_count);
        contentValues.put("statuses_count", status.user.statuses_count);
        contentValues.put("main_content", status.text);
        contentValues.put("created_at", status.created_at);
        contentValues.put("source", status.source);
        if (status.retweeted_status != null) {
            contentValues.put("sub_status", status.retweeted_status != null ? 1 : 0);
            contentValues.put("sub_name", status.retweeted_status.user.name);
            contentValues.put("sub_content", status.retweeted_status.text);
        }/*from w ww.j a v  a 2s. c  o m*/
    }
    databaseHelper.insertWithOnConflict("Status", null, contentValues, SQLiteDatabase.CONFLICT_IGNORE);
    databaseHelper.close();

}

From source file:com.example.blackberry.agoodandroidsample.SqlFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_sql, container, false);

    final CheckBox blueBox = (CheckBox) view.findViewById(R.id.checkBlue);
    final CheckBox brownBox = (CheckBox) view.findViewById(R.id.checkBrown);
    final CheckBox greenBox = (CheckBox) view.findViewById(R.id.checkGreen);
    final CheckBox orangeBox = (CheckBox) view.findViewById(R.id.checkOrange);
    final CheckBox pinkBox = (CheckBox) view.findViewById(R.id.checkPink);
    final CheckBox purpleBox = (CheckBox) view.findViewById(R.id.checkPurple);
    final CheckBox redBox = (CheckBox) view.findViewById(R.id.checkRed);
    final CheckBox yellowBox = (CheckBox) view.findViewById(R.id.checkYellow);

    final Button clearButton = (Button) view.findViewById(R.id.clearButton);
    clearButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            blueBox.setChecked(false);/*from w ww.j  a v  a2 s  .  c om*/
            brownBox.setChecked(false);
            greenBox.setChecked(false);
            orangeBox.setChecked(false);
            pinkBox.setChecked(false);
            purpleBox.setChecked(false);
            redBox.setChecked(false);
            yellowBox.setChecked(false);
        }
    });

    final Button saveButton = (Button) view.findViewById(R.id.saveButton);
    saveButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            ColorDbHelper dbHelper = new ColorDbHelper(getContext());
            SQLiteDatabase db = dbHelper.getWritableDatabase();

            int size = Constants.COLORS_ALL.length;

            //Update the database for each color.
            for (int count = 0; count < size; count++) {
                switch (Constants.COLORS_ALL[count]) {
                case Constants.COLOR_BLUE:
                    updateDb(db, Constants.COLOR_BLUE, blueBox.isChecked());
                    break;

                case Constants.COLOR_BROWN:
                    updateDb(db, Constants.COLOR_BROWN, brownBox.isChecked());
                    break;

                case Constants.COLOR_GREEN:
                    updateDb(db, Constants.COLOR_GREEN, greenBox.isChecked());
                    break;

                case Constants.COLOR_ORANGE:
                    updateDb(db, Constants.COLOR_ORANGE, orangeBox.isChecked());
                    break;

                case Constants.COLOR_PINK:
                    updateDb(db, Constants.COLOR_PINK, pinkBox.isChecked());
                    break;

                case Constants.COLOR_PURPLE:
                    updateDb(db, Constants.COLOR_PURPLE, purpleBox.isChecked());
                    break;

                case Constants.COLOR_RED:
                    updateDb(db, Constants.COLOR_RED, redBox.isChecked());
                    break;

                case Constants.COLOR_YELLOW:
                    updateDb(db, Constants.COLOR_YELLOW, yellowBox.isChecked());
                    break;
                }
            }

            db.close();
        }

        //Update the database with the user's chosen colors.
        private void updateDb(SQLiteDatabase db, int theColor, boolean checked) {
            ContentValues values = new ContentValues();

            //Update the is favorite column based on the user's selection.
            if (checked) {
                values.put(ColorContract.ColorTable.COLUMN_NAME_ISFAVORITE, 1);
            } else {
                values.put(ColorContract.ColorTable.COLUMN_NAME_ISFAVORITE, 0);
            }

            //Update the row for the current color.
            String selection = ColorContract.ColorTable.COLUMN_NAME_COLOR_ID + " LIKE ?";
            String[] selectionArgs = { String.valueOf(theColor) };

            db.update(ColorContract.ColorTable.TABLE_NAME, values, selection, selectionArgs);
        }
    });

    final Button loadButton = (Button) view.findViewById(R.id.loadButton);
    loadButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            ColorDbHelper dbHelper = new ColorDbHelper(getContext());
            SQLiteDatabase db = dbHelper.getWritableDatabase();

            int size = Constants.COLORS_ALL.length;

            //Read the database for each color.
            for (int count = 0; count < size; count++) {
                switch (Constants.COLORS_ALL[count]) {
                case Constants.COLOR_BLUE:
                    blueBox.setChecked(isFavourite(db, Constants.COLOR_BLUE));
                    break;

                case Constants.COLOR_BROWN:
                    brownBox.setChecked(isFavourite(db, Constants.COLOR_BROWN));
                    break;

                case Constants.COLOR_GREEN:
                    greenBox.setChecked(isFavourite(db, Constants.COLOR_GREEN));
                    break;

                case Constants.COLOR_ORANGE:
                    orangeBox.setChecked(isFavourite(db, Constants.COLOR_ORANGE));
                    break;

                case Constants.COLOR_PINK:
                    pinkBox.setChecked(isFavourite(db, Constants.COLOR_PINK));
                    break;

                case Constants.COLOR_PURPLE:
                    purpleBox.setChecked(isFavourite(db, Constants.COLOR_PURPLE));
                    break;

                case Constants.COLOR_RED:
                    redBox.setChecked(isFavourite(db, Constants.COLOR_RED));
                    break;

                case Constants.COLOR_YELLOW:
                    yellowBox.setChecked(isFavourite(db, Constants.COLOR_YELLOW));
                    break;
                }
            }

            db.close();
        }

        private boolean isFavourite(SQLiteDatabase db, int theColor) {
            //Define the columns we want returned.
            String[] projection = { ColorContract.ColorTable.COLUMN_NAME_COLOR_ID,
                    ColorContract.ColorTable.COLUMN_NAME_ISFAVORITE };

            //Define the columns for the where clause.
            String selection = ColorContract.ColorTable.COLUMN_NAME_COLOR_ID + " = " + theColor;

            Cursor cur = db.query(ColorContract.ColorTable.TABLE_NAME, projection, selection, null, null, null,
                    null);

            cur.moveToFirst();

            int fav = cur.getInt(1);
            cur.close();

            if (fav == 0) {
                return false;
            } else {
                return true;
            }
        }
    });

    return view;
}

From source file:com.melchor629.musicote.MainActivity.java

@Override
public boolean onQueryTextSubmit(String query) {
    DB dbs = new DB(this);
    SQLiteDatabase db = dbs.getReadableDatabase();
    Cursor c = dbs.get(db, query);
    songList.clear();/* ww w. j  a  v a  2 s.  com*/
    c.moveToFirst();
    if (c.getCount() > 0) {
        do {
            // creating new HashMap
            LinkedTreeMap<String, String> map = new LinkedTreeMap<>();

            long id = c.getLong(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ID));
            String titulo = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_TITULO));
            String artista = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ARTISTA));
            String album = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ALBUM));
            String archivo = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ARCHIVO));
            String duracion = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_DURACION));
            String down = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_DOWNLOADED));
            boolean downloaded = down.equalsIgnoreCase("true");

            // adding each child node to HashMap key => value
            map.put("id", "" + id);
            map.put("titulo", titulo);
            map.put("artista", artista);
            map.put("album", album);
            map.put("archivo", archivo);
            map.put("duracion", duracion);
            map.put("downloaded", downloaded ? "{fa-mobile}" : "{fa-cloud}"); //TODO

            songList.add(map);
        } while (c.moveToNext());
    }
    sis();
    c.close();
    db.close();
    return false;
}

From source file:io.vit.vitio.Managers.ConnectDatabase.java

public List<Course> getCoursesList() {
    List<Course> courses = new ArrayList<>();
    String selectQuery = "SELECT  * FROM " + TABLE_COURSES;
    try {//  ww  w.  ja va 2  s.c o  m
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                Course course = new Course();
                course.setCLASS_NUMBER(cursor.getString(0));
                course.setCOURSE_TITLE(cursor.getString(1));
                course.setCOURSE_SLOT(cursor.getString(2));
                course.setCOURSE_TYPE(cursor.getString(3));
                course.setCOURSE_TYPE_SHORT(cursor.getString(4));
                course.setCOURSE_LTPC(cursor.getString(5));
                course.setCOURSE_CODE(cursor.getString(6));
                course.setCOURSE_MODE(cursor.getString(7));
                course.setCOURSE_OPTION(cursor.getString(8));
                course.setCOURSE_VENUE(cursor.getString(9));
                course.setCOURSE_FACULTY(cursor.getString(10));
                course.setCOURSE_REGISTRATIONSTATUS(cursor.getString(11));
                course.setCOURSE_BILL_DATE(cursor.getString(12));
                course.setCOURSE_BILL_NUMBER(cursor.getString(13));
                course.setCOURSE_PROJECT_TITLE(cursor.getString(14));
                course.setJson(new JSONObject(cursor.getString(15)));
                course.setCOURSE_ATTENDANCE(ParseCourses.getAttendance(new JSONObject(cursor.getString(16))));
                course.setCOURSE_TIMING(ParseCourses.getTimings(new JSONArray(cursor.getString(17))));
                course.setCOURSE_MARKS(ParseCourses.getCouseMarks(new JSONObject(cursor.getString(18))));
                courses.add(course);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
    } catch (Exception e) {
        e.printStackTrace();
        SQLiteDatabase _db = this.getWritableDatabase();
        if (_db != null && _db.isOpen()) {
            _db.close();
        }
    }
    return courses;
}

From source file:com.fan3cn.fishrecorder.ContentFragment.java

/**
 * ??//from   w  w  w  .j a  v a  2  s.c om
 * @param view
 */
private void handleShipEvent(final View view) {
    Button addButton = (Button) view.findViewById(R.id.button_add);
    addButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            EditText nameET = (EditText) view.findViewById(R.id.editText_ship_name);
            EditText nationET = (EditText) view.findViewById(R.id.editText_ship_nation);
            EditText registerET = (EditText) view.findViewById(R.id.editText_ship_register);
            EditText emailET = (EditText) view.findViewById(R.id.editText_ship_email);
            EditText ffaET = (EditText) view.findViewById(R.id.editText_ship_ffa);
            EditText wcpfcET = (EditText) view.findViewById(R.id.editText_ship_wcpfc);
            EditText radioET = (EditText) view.findViewById(R.id.editText_ship_radio);
            EditText licenseET = (EditText) view.findViewById(R.id.editText_ship_license);

            CheckBox ckBox = (CheckBox) view.findViewById(R.id.checkBox_is_default);

            int isDefault = ckBox.isChecked() ? 1 : 0;

            String name = nameET.getText().toString();
            String nation = nationET.getText().toString();
            String register = registerET.getText().toString();
            String email = emailET.getText().toString();
            String ffa = ffaET.getText().toString();
            String wcpfc = wcpfcET.getText().toString();
            String radio = radioET.getText().toString();
            String license = licenseET.getText().toString();

            if (name.isEmpty() || nation.isEmpty() || register.isEmpty() || email.isEmpty() || ffa.isEmpty()
                    || wcpfc.isEmpty() || radio.isEmpty() || license.isEmpty()) {
                new AlertDialog.Builder(getActivity()).setTitle("??").setPositiveButton("", null)
                        .setMessage("?").show();
                return;
            }

            SQLiteDatabase db = MainActivity.getDbHelper().getWritableDatabase();

            if (isDefault == 1) {
                Cursor cursor = db.query(Constants.table.get(menuId), null, "is_default=?",
                        new String[] { 1 + "" }, null, null, null);
                if (cursor.getCount() > 0) {
                    //?
                    ContentValues cv1 = new ContentValues();
                    cv1.put("is_default", 0);
                    db.update(Constants.table.get(menuId), cv1, "is_default=?", new String[] { 1 + "" });
                }
            }
            int companyId = 0;
            //?
            Cursor cursor = db.query("company", null, "is_default=?", new String[] { 1 + "" }, null, null,
                    null);
            if (cursor.getCount() > 0) {
                while (cursor.moveToNext()) {
                    companyId = cursor.getInt(cursor.getColumnIndex("id"));
                    break;
                }
            }

            ContentValues cv = new ContentValues();
            cv.put("name", name);
            cv.put("company_id", companyId);
            cv.put("nation", nation);
            cv.put("resgiter_no", register);
            cv.put("email", email);
            cv.put("ffa_no", ffa);
            cv.put("wcpfc_no", wcpfc);
            cv.put("radio_tel", radio);
            cv.put("license", license);
            cv.put("is_default", isDefault);
            db.insert(Constants.table.get(menuId), null, cv);
            //??  
            db.close();

            Toast.makeText(getActivity(), "?!", Toast.LENGTH_SHORT).show();
        }
    });

    Button clearButton = (Button) view.findViewById(R.id.button_clear);

    clearButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            EditText nameET = (EditText) view.findViewById(R.id.editText_ship_name);
            EditText nationET = (EditText) view.findViewById(R.id.editText_ship_nation);
            EditText registerET = (EditText) view.findViewById(R.id.editText_ship_register);
            EditText emailET = (EditText) view.findViewById(R.id.editText_ship_email);
            EditText ffaET = (EditText) view.findViewById(R.id.editText_ship_ffa);
            EditText wcpfcET = (EditText) view.findViewById(R.id.editText_ship_wcpfc);
            EditText radioET = (EditText) view.findViewById(R.id.editText_ship_radio);
            EditText licenseET = (EditText) view.findViewById(R.id.editText_ship_license);

            CheckBox ckBox = (CheckBox) view.findViewById(R.id.checkBox_is_default);

            nameET.setText("");
            nationET.setText("");
            registerET.setText("");
            emailET.setText("");
            ffaET.setText("");
            emailET.setText("");
            radioET.setText("");
            wcpfcET.setText("");
            licenseET.setText("");
            ckBox.setChecked(false);
        }
    });

}

From source file:com.openerp.orm.ORM.java

/**
 * Update m2 m records./*w  w w  .ja v  a 2  s. c o  m*/
 * 
 * @param id
 *            the id
 * @param values
 *            the values
 * @param key
 *            the key
 * @param dbHelper
 *            the db helper
 * @param m2m
 *            the m2m
 * @param rootRow
 *            the root row
 */
private void updateM2MRecords(String id, JSONArray values, String key, BaseDBHelper dbHelper, Many2Many m2m,
        ContentValues rootRow) {
    // TODO Auto-generated method stub
    String table1 = modelToTable(dbHelper.getModelName());
    String table2 = "";
    BaseDBHelper tbl2Obj = null;
    if (m2m.isM2MObject()) {
        tbl2Obj = (BaseDBHelper) m2m.getM2mObject();
        table2 = modelToTable(tbl2Obj.getModelName());
    } else {
        table2 = modelToTable(m2m.getModel_name());
    }
    String rel_table = table1 + "_" + table2 + "_rel";
    String col1 = table1 + "_id";
    String col2 = table2 + "_id";
    String col3 = "oea_name";

    // Temp dummy helper
    BaseDBHelper newDb = generateM2MHelper(dbHelper, m2m);

    for (int i = 0; i < values.length(); i++) {
        try {
            int row_id = 0;

            if (values.get(i) instanceof JSONArray) {
                row_id = values.getJSONArray(i).getInt(0);
            }
            if (values.get(i) instanceof JSONObject) {
                JSONObject obj = (JSONObject) values.get(i);
                if (obj.has("id")) {
                    row_id = obj.getInt("id");
                }
            }
            if (values.get(i) instanceof Integer) {
                row_id = values.getInt(i);
            }

            ContentValues m2mvals = new ContentValues();
            m2mvals.put(col1, id);
            m2mvals.put(col2, row_id);
            m2mvals.put(col3, user_name);
            int res = (Integer) this
                    .search(newDb, new String[] { col1 + " = ?", "AND", col2 + "= ?", "AND", col3 + " = ?" },
                            new String[] { id, row_id + "", user_name })
                    .get("total");
            SQLiteDatabase db = getWritableDatabase();
            if (res == 0) {

                db.insert(rel_table, null, m2mvals);

                if (tbl2Obj != null) {
                    List<Integer> list = new ArrayList<Integer>();
                    list.add(row_id);
                    oe_obj.syncReferenceTables(tbl2Obj, list, false);
                }
            } else {
                db.update(rel_table, m2mvals, col1 + " = " + id + " AND " + col2 + " = " + row_id + " AND "
                        + col3 + " = '" + user_name + "' ", null);
            }
            db.close();

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

}

From source file:com.odoo.orm.OModel.java

/**
 * Handle many to many data.//  ww w  .  j a  v a  2 s  .c  o m
 * 
 * @param column
 *            the column
 * @param base_id
 *            the base_id
 * @param relation_record_ids
 *            the relation_record_ids
 * @param command
 *            the command
 */
private void handleManyToManyData(String column, Integer base_id, List<Integer> relation_record_ids,
        Command command) {
    OColumn col = getColumn(column);
    if (col.getRelationType() == RelationType.ManyToMany) {
        SQLiteDatabase db = getWritableDatabase();
        OModel rel_model = createInstance(col.getType());
        manageManyToManyRecords(db, rel_model, relation_record_ids, base_id, command);
        db.close();
    }
}

From source file:com.odoo.orm.OModel.java

/**
 * Delete.//from  w w  w .  j av  a  2 s  .c  o m
 * 
 * @param where
 *            the where
 * @param whereArgs
 *            the where args
 * @param removeFromLocal
 *            the remove from local
 * @return true, if successful
 */
public boolean delete(String where, Object[] whereArgs, boolean removeFromLocal) {
    Boolean deleted = false;
    if (removeFromLocal) {
        SQLiteDatabase db = getWritableDatabase();
        if (db.delete(getTableName(), getWhereClause(where), getWhereArgs(where, whereArgs)) > 0) {
            deleted = true;
        }
        db.close();
    } else {
        // Setting is_active to false.
        OValues values = new OValues();
        values.put("is_dirty", "true");
        values.put("is_active", "false");
        if (update(values, where, whereArgs) > 0)
            deleted = true;
    }
    return deleted;
}

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

public List<Object> getWallpapersUnified() {
    List<Object> wallpapers = new ArrayList<>();
    Map<String, Category> categoryMap = getCategoryMap();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(TABLE_WALLPAPERS, null, null, null, null, null, KEY_CATEGORY);
    if (cursor.moveToFirst()) {
        String categoryName = cursor.getString(5);
        Category category = new Category(0, categoryName, categoryMap.get(categoryName).getThumbUrl(), false);
        wallpapers.add(category);/*from  ww  w.ja v  a  2s. co  m*/
        int numWallpapers = 0;
        do {
            String newCategoryName = cursor.getString(5);
            if (!newCategoryName.equals(categoryName)) {
                category.setNumWallpapers(numWallpapers);
                numWallpapers = 0;
                categoryName = newCategoryName;
                category = new Category(0, newCategoryName, categoryMap.get(newCategoryName).getThumbUrl(),
                        false);
                wallpapers.add(category);
            }
            Wallpaper wallpaper = new Wallpaper(cursor.getInt(0), cursor.getString(1), cursor.getString(2),
                    cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getInt(6) == 1,
                    cursor.getLong(7));
            wallpapers.add(wallpaper);
            numWallpapers++;
        } while (cursor.moveToNext());
        category.setNumWallpapers(numWallpapers);
    }
    cursor.close();
    db.close();
    return wallpapers;
}