android.database.sqlite.SQLiteDatabase Java Examples

The following examples show how to use android.database.sqlite.SQLiteDatabase. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DemoHelperClass.java    From Trivia-Knowledge with Apache License 2.0 6 votes vote down vote up
public void addAllQuestions(ArrayList<Questions> allQuestions) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.beginTransaction();
    try {
        ContentValues values = new ContentValues();
        for (Questions question : allQuestions) {
            values.put(QUESTION, question.getQUESTION());
            values.put(ANSWER, question.getANSWER());
            values.put(ANSWER2, question.getANSWER2());
            values.put(RANDOMANS1, question.getRANDOMANS1());
            values.put(RANDOMANS2, question.getRANDOMANS2());
            values.put(USELESSSTRING, question.getUSELESSSTRING());
            db.insert(TABLE_NAME, null, values);
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        db.close();
    }
}
 
Example #2
Source File: DataProvider.java    From narrate-android with Apache License 2.0 6 votes vote down vote up
@Override
public Uri insert(Uri uri, ContentValues values) {

    final int match = sUriMatcher.match(uri);
    SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();

    switch (match) {
        case ENTRIES: {
            db.insertOrThrow(Tables.ENTRIES, null, values);
            notifyChange(uri);
            return Entries.buildEntryUri(values.getAsString(Entries.UUID));
        }
        default: {
            throw new UnsupportedOperationException("Unknown insert uri: " + uri);
        }
    }
}
 
Example #3
Source File: SongPlayCount.java    From Muzesto with GNU General Public License v3.0 6 votes vote down vote up
public void onCreate(final SQLiteDatabase db) {
    // create the play count table
    // WARNING: If you change the order of these columns
    // please update getColumnIndexForWeek
    StringBuilder builder = new StringBuilder();
    builder.append("CREATE TABLE IF NOT EXISTS ");
    builder.append(SongPlayCountColumns.NAME);
    builder.append("(");
    builder.append(SongPlayCountColumns.ID);
    builder.append(" INT UNIQUE,");

    for (int i = 0; i < NUM_WEEKS; i++) {
        builder.append(getColumnNameForWeek(i));
        builder.append(" INT DEFAULT 0,");
    }

    builder.append(SongPlayCountColumns.LAST_UPDATED_WEEK_INDEX);
    builder.append(" INT NOT NULL,");

    builder.append(SongPlayCountColumns.PLAYCOUNTSCORE);
    builder.append(" REAL DEFAULT 0);");

    db.execSQL(builder.toString());
}
 
Example #4
Source File: DownloadsDB.java    From travelguide with Apache License 2.0 6 votes vote down vote up
private DownloadsDB(Context paramContext) {
    this.mHelper = new DownloadsContentDBHelper(paramContext);
    final SQLiteDatabase sqldb = mHelper.getReadableDatabase();
    // Query for the version code, the row ID of the metadata (for future
    // updating) the status and the flags
    Cursor cur = sqldb.rawQuery("SELECT " +
            MetadataColumns.APKVERSION + "," +
            BaseColumns._ID + "," +
            MetadataColumns.DOWNLOAD_STATUS + "," +
            MetadataColumns.FLAGS +
            " FROM "
            + MetadataColumns.TABLE_NAME + " LIMIT 1", null);
    if (null != cur && cur.moveToFirst()) {
        mVersionCode = cur.getInt(0);
        mMetadataRowID = cur.getLong(1);
        mStatus = cur.getInt(2);
        mFlags = cur.getInt(3);
        cur.close();
    }
    mDownloadsDB = this;
}
 
Example #5
Source File: DBUtils.java    From BaseProject with Apache License 2.0 6 votes vote down vote up
/**
 * SQLite数据库中一个特殊的名叫 SQLITE_MASTER 上执行一个SELECT查询以获得所有表的索引。每一个 SQLite 数据库都有一个叫 SQLITE_MASTER 的表, 它定义数据库的模式。
 * SQLITE_MASTER 表看起来如下:
 * CREATE TABLE sqlite_master (
 * type TEXT,
 * name TEXT,
 * tbl_name TEXT,
 * rootpage INTEGER,
 * sql TEXT
 * );
 * 对于表来说,type 字段永远是 ‘table’,name 字段永远是表的名字。
 */
public static boolean isTableExists(SQLiteDatabase db, String tableName) {
    if (tableName == null || db == null || !db.isOpen()) return false;

    Cursor cursor = null;
    int count = 0;
    try {
        cursor = db.rawQuery("SELECT COUNT(*) FROM sqlite_master WHERE type = ? AND name = ?", new String[]{"table", tableName});
        if (!cursor.moveToFirst()) {
            return false;
        }
        count = cursor.getInt(0);
    } catch (Exception e) {
        OkLogger.printStackTrace(e);
    } finally {
        if (cursor != null) cursor.close();
    }
    return count > 0;
}
 
Example #6
Source File: DownloadsDB.java    From UnityOBBDownloader with Apache License 2.0 6 votes vote down vote up
public DownloadInfo[] getDownloads() {
    final SQLiteDatabase sqldb = mHelper.getReadableDatabase();
    Cursor cur = null;
    try {
        cur = sqldb.query(DownloadColumns.TABLE_NAME, DC_PROJECTION, null,
                null, null, null, null);
        if (null != cur && cur.moveToFirst()) {
            DownloadInfo[] retInfos = new DownloadInfo[cur.getCount()];
            int idx = 0;
            do {
                DownloadInfo di = getDownloadInfoFromCursor(cur);
                retInfos[idx++] = di;
            } while (cur.moveToNext());
            return retInfos;
        }
        return null;
    } finally {
        if (null != cur) {
            cur.close();
        }
    }
}
 
Example #7
Source File: DelegateFind.java    From Aria with Apache License 2.0 6 votes vote down vote up
/**
 * 条件查寻数据
 */
<T extends DbEntity> List<T> findData(SQLiteDatabase db, Class<T> clazz, String... expression) {
  db = checkDb(db);
  if (!CommonUtil.checkSqlExpression(expression)) {
    return null;
  }
  String sql = String.format("SELECT rowid, * FROM %s WHERE %s", CommonUtil.getClassName(clazz),
      expression[0]);
  String[] params = new String[expression.length - 1];
  try {
    // 处理系统出现的问题:https://github.com/AriaLyy/Aria/issues/450
    System.arraycopy(expression, 1, params, 0, params.length);
  } catch (Exception e) {
    e.printStackTrace();
    return null;
  }

  return exeNormalDataSql(db, clazz, sql, params);
}
 
Example #8
Source File: HistoryManager.java    From incubator-weex-playground with Apache License 2.0 6 votes vote down vote up
public HistoryItem buildHistoryItem(int number) {
  SQLiteOpenHelper helper = new DBHelper(activity);
  SQLiteDatabase db = null;
  Cursor cursor = null;
  try {
    db = helper.getReadableDatabase();
    cursor = db.query(DBHelper.TABLE_NAME, COLUMNS, null, null, null, null, DBHelper.TIMESTAMP_COL + " DESC");
    cursor.move(number + 1);
    String text = cursor.getString(0);
    String display = cursor.getString(1);
    String format = cursor.getString(2);
    long timestamp = cursor.getLong(3);
    String details = cursor.getString(4);
    Result result = new Result(text, null, null, BarcodeFormat.valueOf(format), timestamp);
    return new HistoryItem(result, display, details);
  } finally {
    close(cursor, db);
  }
}
 
Example #9
Source File: DatabaseAdmin.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
private synchronized List<String> executeSQL(final String query) {
    final List<String> results = new ArrayList<>();
    final SQLiteDatabase db = Cache.openDatabase();
    final boolean transaction = !query.equals("vacuum");
    if (transaction) db.beginTransaction();
    try {
        final Cursor cursor = db.rawQuery(query, null);
        Log.d(TAG, "Got query results: " + query + " " + cursor.getCount());

        while (cursor.moveToNext()) {
            for (int c = 0; c < cursor.getColumnCount(); c++) {
                if (D) Log.d(TAG, "Column: " + cursor.getColumnName(c));
                results.add(cursor.getString(c));
            }
        }
        cursor.close();

        if (transaction) db.setTransactionSuccessful();
    } finally {
        if (transaction) db.endTransaction();
    }
    return results;
}
 
Example #10
Source File: ListValidatorProcessor.java    From opentasks-provider with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeInsert(SQLiteDatabase db, ListAdapter list, boolean isSyncAdapter)
{
	if (!isSyncAdapter)
	{
		throw new UnsupportedOperationException("Caller must be a sync adapter to create task lists");
	}

	if (TextUtils.isEmpty(list.valueOf(ListAdapter.ACCOUNT_NAME)))
	{
		throw new IllegalArgumentException("ACCOUNT_NAME is required on INSERT");
	}

	if (TextUtils.isEmpty(list.valueOf(ListAdapter.ACCOUNT_TYPE)))
	{
		throw new IllegalArgumentException("ACCOUNT_TYPE is required on INSERT");
	}

	verifyCommon(list, isSyncAdapter);
}
 
Example #11
Source File: SqliteHelper.java    From vault with Apache License 2.0 6 votes vote down vote up
private boolean isPendingCopy(File dbPath) {
  boolean result = false;
  if (dbPath.exists()) {
    SQLiteDatabase db =
        context.openOrCreateDatabase(spaceHelper.getDatabaseName(), Context.MODE_PRIVATE, null);
    try {
      if (spaceHelper.getDatabaseVersion() > db.getVersion()) {
        result = true;
      }
    } finally {
      db.close();
    }
  } else {
    result = true;
  }
  return result;
}
 
Example #12
Source File: BookModelHelper.java    From coolreader with MIT License 6 votes vote down vote up
public static BookModel getBookModel(SQLiteDatabase db, int id) {
	BookModel book = null;
	Cursor cursor = helper.rawQuery(db, "select * from " + DBHelper.TABLE_NOVEL_BOOK
									 + " where " + DBHelper.COLUMN_ID + " = ? ", new String[] {"" + id});
	try {
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			book = cursorToBookModel(cursor);
			//Log.d(TAG, "Found: " + book.getPage() + Constants.NOVEL_BOOK_DIVIDER + book.getTitle());
			break;
		}
	} finally{
		if(cursor != null) cursor.close();
	}
    return book;
}
 
Example #13
Source File: WaitlistDbHelper.java    From android-dev-challenge with Apache License 2.0 5 votes vote down vote up
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    // For now simply drop the table and create a new one. This means if you change the
    // DATABASE_VERSION the table will be dropped.
    // In a production app, this method might be modified to ALTER the table
    // instead of dropping it, so that existing data is not deleted.
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + WaitlistEntry.TABLE_NAME);
    onCreate(sqLiteDatabase);
}
 
Example #14
Source File: Database.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
@Override
  public final void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {
      /*PROTECTED REGION ID(DatabaseUpdate) ENABLED START*/

      // TODO Implement your database update functionality here and remove the following method call!
      onUpgradeDropTablesAndCreate(db);

/*PROTECTED REGION END*/
  }
 
Example #15
Source File: UploadDateStoreDb.java    From pearl with Apache License 2.0 5 votes vote down vote up
public String retrieveValue(){
    SQLiteDatabase db0 = this.getReadableDatabase();
    String query_params0 = "SELECT " + "*" + " FROM " + TABLE_DB_DATE;
    Cursor cSor0 = db0.rawQuery(query_params0, null);
    if(cSor0.moveToFirst()){
        do{
            return cSor0.getString(cSor0.getColumnIndexOrThrow(UploadDateStoreDb.COLUMN_LATEST_DATE));
        }while(cSor0.moveToNext());
    }else{
        return null;
    }
}
 
Example #16
Source File: DAOProgram.java    From fastnfitness with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void delete(long id) {
    open();

    // Should delete the Workout template

    // Delete the Workout
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_NAME, KEY + " = ?",
        new String[]{String.valueOf(id)});

    close();
}
 
Example #17
Source File: SQLIteKV.java    From FastSharedPreferences with Apache License 2.0 5 votes vote down vote up
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
    String sql = "DROP TABLE IF EXISTS " + TABLE_NAME_STR;
    sqLiteDatabase.execSQL(sql);
    sql = "DROP TABLE IF EXISTS " + TABLE_NAME_INT;
    sqLiteDatabase.execSQL(sql);
    onCreate(sqLiteDatabase);
}
 
Example #18
Source File: GroupDb.java    From XERUNG with Apache License 2.0 5 votes vote down vote up
public ArrayList<ContactBean> getAllMember(String tableName) {

        ArrayList<ContactBean> gbList = new ArrayList<ContactBean>();
        try {
            String selectQuery = "SELECT " + MEMBER_NAME + ", " + MEMBER_PHONE + ", " + MEMBER_SEARCHKEY + ", " + MEMBER_UID + ", " + MEMBER_FLAG + ", " + MEMBER_ORG_NAME + ", "
                    + MEMBER_PH_BOK_NAME + ", " + MEMBER_ISMY_CONTACT + ", " + MEMBER_BLOOD_GROUP + ", " + MEMBER_ADMIN_FLAG + ", " + MEMBER_CREATED_DATE + " FROM " + tableName;

            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);
            // looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do {
                    ContactBean contact = new ContactBean();
                    contact.setName(cursor.getString(0));
                    contact.setNumber(cursor.getString(1));
                    contact.setSearchKey(cursor.getString(2));
                    contact.setUID(cursor.getString(3));
                    contact.setRequestFlag(cursor.getString(4));
                    contact.setOrignalName(cursor.getString(5));
                    contact.setMyPhoneBookName(cursor.getString(6));
                    contact.setIsMyContact(cursor.getInt(7));
                    contact.setmBloodGroup(cursor.getString(8));
                    contact.setAdminFlag(cursor.getString(9));
                    contact.setmCreatedDate(cursor.getString(10));
                    gbList.add(contact);
                } while (cursor.moveToNext());
            }
            if (cursor != null)
                cursor.close();
            db.close();
            ;
        } catch (Exception e) {
            // TODO: handle exception
            //Log.e("GroupDBErro", "FetchAllDB "+e.getMessage());
            e.printStackTrace();
        }
        return gbList;
    }
 
Example #19
Source File: SQLiteLocationDAOTest.java    From background-geolocation-android with Apache License 2.0 5 votes vote down vote up
@Test
public void deletePendingLocations() {
    Context ctx = InstrumentationRegistry.getTargetContext();
    SQLiteDatabase db = new SQLiteOpenHelper(ctx).getWritableDatabase();
    SQLiteLocationDAO dao = new SQLiteLocationDAO(db);

    BackgroundLocation location = null;

    for (int i = 0; i < 5; i++) {
        location = new BackgroundLocation();
        location.setProvider("fake");
        location.setAccuracy(200 + i);
        location.setAltitude(900 + i);
        location.setBearing(2 + i);
        location.setLatitude(40.21 + i);
        location.setLongitude(23.45 + i);
        location.setSpeed(20 + i);
        location.setProvider("test");
        location.setTime(1000 + i);
        if (i < 3) {
            location.setStatus(BackgroundLocation.DELETED);
        }

        dao.persistLocation(location);
    }

    dao.deleteUnpostedLocations();
    Assert.assertEquals(0, dao.getUnpostedLocationsCount());
    Assert.assertEquals(2, dao.getLocationsForSyncCount(0));
}
 
Example #20
Source File: AlarmDatabase.java    From react-native-alarm-notification with MIT License 5 votes vote down vote up
void delete(int id) {
    SQLiteDatabase db = null;
    String where = COL_ID + "=" + id;

    try {
        db = this.getWritableDatabase();
        db.delete(TABLE_NAME, where, null);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (db != null) {
            db.close();
        }
    }
}
 
Example #21
Source File: DownloadDatabase.java    From OneTapVideoDownload with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate(SQLiteDatabase db) {
    String downloadListTable = "CREATE TABLE " + TABLE_VIDEO_DOWNLOAD_LIST + "("
            + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + KEY_TYPE + " INTEGER )";

    String browserDownloadListTable = "CREATE TABLE " + TABLE_BROWSER_DOWNLOAD_LIST + "("
            + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + KEY_VIDEO_ID + " INTEGER,"
            + KEY_URL + " TEXT,"
            + KEY_DOWNLOAD_LOCATION + " TEXT,"
            + KEY_FILENAME + " TEXT,"
            + KEY_STATUS + " INTEGER,"
            + KEY_CONTENT_LENGTH + " INTEGER,"
            + KEY_DOWNLOADED_LENGTH + " INTEGER,"
            + KEY_PACKAGE_NAME + " TEXT )";

    String youtubeDownloadListTable = "CREATE TABLE " + TABLE_YOUTUBE_DOWNLOAD_LIST + "("
            + KEY_PARAM + " TEXT, "
            + KEY_VIDEO_ID + " INTEGER,"
            + KEY_VIDEO_ITAG + " INTEGER,"
            + KEY_URL + " TEXT,"
            + KEY_FILENAME + " TEXT,"
            + KEY_DOWNLOAD_LOCATION + " TEXT,"
            + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + KEY_STATUS + " INTEGER,"
            + KEY_CONTENT_LENGTH + " INTEGER,"
            + KEY_DOWNLOADED_LENGTH + " INTEGER,"
            + KEY_PACKAGE_NAME + " TEXT )";

    db.execSQL(downloadListTable);
    db.execSQL(browserDownloadListTable);
    db.execSQL(youtubeDownloadListTable);
}
 
Example #22
Source File: DatabaseHandler.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
private void addUserItem(String table, Integer id)
{
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_USER_ID, id);
    db.insert(table, null, values);
    db.close();
}
 
Example #23
Source File: DBAdapter.java    From video-tutorial-code with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
	Log.w(TAG, "Upgrading application's database from version " + oldVersion
			+ " to " + newVersion + ", which will destroy all old data!");
	
	// Destroy old database:
	_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
	
	// Recreate new database:
	onCreate(_db);
}
 
Example #24
Source File: DBHelper.java    From Database-Backup-Restore with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(SQLiteDatabase db) {

    //create tables
    db.execSQL(CREATE_TABLE_STUDENTS);
    db.execSQL(CREATE_TABLE_EXAMS);
}
 
Example #25
Source File: MetaDataSQLiteHelper.java    From privacy-friendly-passwordgenerator with GNU General Public License v3.0 5 votes vote down vote up
public List<MetaData> getAllMetaData() {
    List<MetaData> metaDataList = new ArrayList<MetaData>();

    SQLiteDatabase database = this.getWritableDatabase();
    Cursor cursor = database.rawQuery("SELECT  * FROM " + TABLE_METADATA, new String[]{});

    MetaData metaData = null;

    if (cursor.moveToFirst()) {
        do {
            metaData = new MetaData();
            metaData.setID(Integer.parseInt(cursor.getString(0)));
            metaData.setDOMAIN(cursor.getString(1));
            metaData.setUSERNAME(cursor.getString(2));
            metaData.setLENGTH(Integer.parseInt(cursor.getString(3)));
            metaData.setHAS_NUMBERS(Integer.parseInt(cursor.getString(4)));
            metaData.setHAS_SYMBOLS(Integer.parseInt(cursor.getString(5)));
            metaData.setHAS_LETTERS_UP(Integer.parseInt(cursor.getString(6)));
            metaData.setHAS_LETTERS_LOW(Integer.parseInt(cursor.getString(7)));
            metaData.setITERATION(Integer.parseInt(cursor.getString(8)));

            metaDataList.add(metaData);
        } while (cursor.moveToNext());
    }

    return metaDataList;
}
 
Example #26
Source File: PersistManager.java    From Man-Man with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
    try {
        TableUtils.createTable(connectionSource, ManSectionItem.class);
        TableUtils.createTable(connectionSource, ManSectionIndex.class);
        TableUtils.createTable(connectionSource, ManPage.class);
    } catch (SQLException e) {
        Log.e(TAG, "error creating DB " + DATABASE_NAME);
        throw new RuntimeException(e);
    }
}
 
Example #27
Source File: BufferProvider.java    From TimberLorry with Apache License 2.0 5 votes vote down vote up
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    SQLiteDatabase db = null;
    try {
        db = helper.getWritableDatabase();
        db.beginTransaction();
        String newSelection = buildSelection(uri, selection);
        int count = db.update(BufferScheme.TABLE_NAME, values, newSelection, selectionArgs);
        getContext().getContentResolver().notifyChange(CONTENT_URI, null, false);
        db.setTransactionSuccessful();
        return count;
    } finally {
        Utils.endTransaction(db);
    }
}
 
Example #28
Source File: PredatorDbHelper.java    From Capstone-Project with MIT License 5 votes vote down vote up
public Cursor getPosts(String[] columns, String selection, String[] selectionArgs, String sortOrder) {
    // Create and/or open the database for writing
    SQLiteDatabase db = getReadableDatabase();

    // It's a good idea to wrap our insert in a transaction. This helps with performance and ensures
    // consistency of the database.
    return db.query(PredatorContract.PostsEntry.TABLE_NAME,
            columns,
            selection,
            selectionArgs,
            null,
            null,
            sortOrder);
}
 
Example #29
Source File: LinkingDBAdapter.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
private void createHumidityTable(final SQLiteDatabase db) {
    String sql = "CREATE TABLE " + TABLE_HUMIDITY + " (_id INTEGER PRIMARY KEY,"
            + HumidityColumns.VENDOR_ID + " INTEGER,"
            + HumidityColumns.EXTRA_ID + " INTEGER,"
            + HumidityColumns.TIME_STAMP + " INTEGER,"
            + HumidityColumns.HUMIDITY + " REAL"
            + ");";
    db.execSQL(sql);
}
 
Example #30
Source File: LockSettingsStorage.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void createTable(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + TABLE + " (" +
            "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
            COLUMN_KEY + " TEXT," +
            COLUMN_USERID + " INTEGER," +
            COLUMN_VALUE + " TEXT" +
            ");");
}