Java Code Examples for android.database.sqlite.SQLiteDatabase.rawQuery()

The following are Jave code examples for showing how to use rawQuery() of the android.database.sqlite.SQLiteDatabase class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ShadowTravelor   File: DBHelper.java   View Source Code Vote up 7 votes
public void resetDB() {
    SQLiteDatabase db = this.getWritableDatabase();
    // query to obtain the names of all tables in your database
    Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
    List<String> tables = new ArrayList<>();

    // iterate over the result set, adding every table name to a list
    while (c.moveToNext()) {
        tables.add(c.getString(0));
    }

    // call DROP TABLE on every table name
    for (String table : tables) {
        String dropQuery = "DROP TABLE IF EXISTS " + table;
        db.execSQL(dropQuery);
    }
}
 
Example 2
Project: OSchina_resources_android   File: DBHelper.java   View Source Code Vote up 6 votes
public long getCount(Class<?> cls) {
    String tableName = getTableName(cls);
    if (!isExist(tableName))
        return -1;
    SQLiteDatabase db;
    Cursor cursor = null;
    try {
        db = getReadableDatabase();
        cursor = db.rawQuery(String.format("select count(*) from %s", tableName), null);
        cursor.moveToFirst();
        long count = cursor.getLong(0);
        cursor.close();
        return count;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
    }
    return 0;
}
 
Example 3
Project: QuranAndroid   File: DatabaseAccess.java   View Source Code Vote up 6 votes
public int getPageHezb(int pageNumber) {
    int hezbNumber = 0;
    try {
        SQLiteDatabase db = openDB(MAIN_DATABASE);
        String sql = "select hezb from aya where page = " + pageNumber + " ;";
        Cursor cursor = db.rawQuery(sql, null);

        if(cursor.moveToLast()){
            hezbNumber = cursor.getInt(0);
        }
        cursor.close();
        closeDB(db);
        return hezbNumber;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return hezbNumber;
}
 
Example 4
Project: HiBangClient   File: ChatMsgDB.java   View Source Code Vote up 6 votes
public MyChatMsg getChatMsgById(int id) {
		SQLiteDatabase db = this.getReadableDatabase();
		MyChatMsg myChatMsg = new MyChatMsg();
		Cursor cursor;
		cursor = db.rawQuery("select * from " + TABLE_NAME + " where msgID =?",
				new String[] { id + " " });

		myChatMsg.setMsgId(cursor.getInt(cursor.getColumnIndex("msgID")));
		myChatMsg.setFriendId(cursor.getInt(cursor.getColumnIndex("friendId")));
		myChatMsg.setSenderId(cursor.getInt(cursor.getColumnIndex("sendId")));
		myChatMsg.setMsgContent(cursor.getString(cursor
				.getColumnIndex("content")));

//		Date d = new Date();
//		String string = cursor.getString(cursor.getColumnIndex("publishTime"));
//		SimpleDateFormat sDateFormat = new SimpleDateFormat();
//		try {
//			d = sDateFormat.parse(string);
//		} catch (ParseException e) {
//			e.printStackTrace();
//		}
//		myChatMsg.setChatTime(d);
		myChatMsg.setChatTime(cursor.getString(cursor.getColumnIndex("publishTime")));

		if (cursor.getInt(cursor.getColumnIndex("isNoRead")) == 1) {
			myChatMsg.setNoRead(true);
		} else
			myChatMsg.setNoRead(false);

		return myChatMsg;
	}
 
Example 5
Project: uidcore-android   File: Register.java   View Source Code Vote up 6 votes
/**
 * Return a {@code UserChannel} by the transaction identifier of the revoke contract
 * @param revokeTxId the transaction identifier of the revoke contract
 * @return {@code UserChannel} that involves the specified revokeTxId or null if there is no record with the specified revoketxId
 * @throws RegisterException id revokeTxid is null or empty, or an error occurs
 * */
@Override
public UserChannel getUserChannelByRevokeTxId(String revokeTxId) throws RegisterException {

    if(revokeTxId == null || revokeTxId.isEmpty())
        throw new RegisterException("revokeTxId is not valid");

    try {
        try (SQLiteHelperPool.SQLiteDatabaseWrapper sqLiteDatabaseWrapper =
                     androidDataSource.getSQLiteDatabaseWrapper()) {
            SQLiteDatabase db = sqLiteDatabaseWrapper.getSQLiteDatabase();
            try (Cursor cursor = db.rawQuery(
                    "select * from " + SQLiteHelper.TABLE_USER +
                            " where " + SQLiteHelper.USER_CLM_REVOKE_TX_ID + " = ?",
                    new String[]{revokeTxId})) {
                if (cursor.moveToFirst()) {
                    return createUserChannelFromCursor(cursor);
                } else {
                    return null;
                }
            }
        }
    } catch (Throwable t) {
        throw new RegisterException("Exception", t);
    }
}
 
Example 6
Project: XERUNG   File: GroupDb.java   View Source Code Vote up 6 votes
public int getMemberTableCount(String table) {
    int count = 0;
    try {
        String countQuery = "SELECT COUNT(*) as m FROM " + table;
        SQLiteDatabase sq = this.getReadableDatabase();
        Cursor cursor = sq.rawQuery(countQuery, null);
        count = cursor.getInt(0);
        cursor.close();
        sq.close();

    } catch (Exception e) {
        // TODO: handle exception
        //Log.e("GroupDBErro", "GetGroup Count "+e.getMessage());
        e.printStackTrace();
    }
    return count;
}
 
Example 7
Project: minu-poska-android   File: StuudiumDatabaseHelper.java   View Source Code Vote up 5 votes
public DataMap<String, Person> requestPeople() {
    SQLiteDatabase db = getReadableDatabase();
    Cursor c = db.rawQuery("SELECT * FROM " + TABLE_PEOPLE, null);
    DataMap<String, Person> events = new DataMap<>();
    if (c.moveToFirst()) do try {
        String id = c.getString(0);
        JSONObject json = new JSONObject(c.getString(1));
        events.put(id, new Person(json));
    } catch (JSONException e) {
        Log.e(TAG, "Failed to parse JSON", e);
    } while (c.moveToNext());
    c.close();
    return events;
}
 
Example 8
Project: Pocket-Plays-for-Twitch   File: Service.java   View Source Code Vote up 5 votes
/**
 * Determines whether or not the user is currently following a streamer.
 * This is done by looking in the SQLite database
 */
public static boolean isUserFollowingStreamer(String streamername, Context context) {
	SubscriptionsDbHelper mDbHelper = new SubscriptionsDbHelper(context);
	SQLiteDatabase db = mDbHelper.getReadableDatabase();
	String query = "SELECT * FROM " + SubscriptionsDbHelper.TABLE_NAME + " WHERE " + SubscriptionsDbHelper.COLUMN_STREAMER_NAME + "='" + streamername + "';";
	boolean result = false;
	Cursor cursor = db.rawQuery(query, null);
	if(cursor.getCount() > 0) {
		result = true;
	}
	cursor.close();
	db.close();
	return result;
}
 
Example 9
Project: UbiBike-client   File: MyDBHandler.java   View Source Code Vote up 5 votes
public ArrayList<TupleTrajectory> getAllTrajectories()
{
    ArrayList<TupleTrajectory> listOfTrajectories = new ArrayList<TupleTrajectory>();

    SQLiteDatabase db = getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_PENDING_TRAJECTORY ;
    Cursor c = db.rawQuery(query, null);

    while(c.moveToNext())
    {
        String jsonString = c.getString(c.getColumnIndex(COLUMN_POINT_LIST));

        //temos que converter o jsonString de volta a um String array
        String strSeparator = "__,__";
        String[] jsonArray = jsonString.split(strSeparator);

        JSONArray jsonArrayFinal = new JSONArray();
        //e agora convertemos de volta para um JSON Array
        for(int i = 0; i < jsonArray.length ; i++)
        {
            try {
                JSONObject jsonObject = new JSONObject(jsonArray[i]);
                jsonArrayFinal.put(jsonObject);
            } catch(JSONException e)
            {
                Log.d("Exception", "JSON Exception ");
                e.printStackTrace();
            }
        }
        TupleTrajectory entry = new TupleTrajectory(c.getInt(c.getColumnIndex(COLUMN_DISTANCE)), c.getInt(c.getColumnIndex(COLUMN_POINTS_EARNED)), c.getLong(c.getColumnIndex(COLUMN_TRAVEL_TIME)),jsonArrayFinal,c.getInt(c.getColumnIndex(COLUMN_ID)), c.getString(c.getColumnIndex(COLUMN_DATE)));
        listOfTrajectories.add(entry);
    }

    db.close();
    c.close();

    return listOfTrajectories;
}
 
Example 10
Project: q-mail   File: MigrationTo55.java   View Source Code Vote up 5 votes
private static List<Long> fetchFolders(SQLiteDatabase db) {
    List<Long> folders = new ArrayList<>();
    Cursor cursor = db.rawQuery("SELECT id FROM folders ORDER BY name ASC", null);
    while (cursor.moveToNext()) {
        folders.add(cursor.getLong(0));
    }
    cursor.close();
    return folders;
}
 
Example 11
Project: SlotNSlot_Android   File: DownloadsDB.java   View Source Code Vote up 5 votes
public boolean isDownloadRequired() {
    final SQLiteDatabase sqldb = mHelper.getReadableDatabase();
    Cursor cur = sqldb.rawQuery("SELECT Count(*) FROM "
            + DownloadColumns.TABLE_NAME + " WHERE "
            + DownloadColumns.STATUS + " <> 0", null);
    try {
        if (null != cur && cur.moveToFirst()) {
            return 0 == cur.getInt(0);
        }
    } finally {
        if (null != cur)
            cur.close();
    }
    return true;
}
 
Example 12
Project: Sherlock   File: SherlockDatabaseHelper.java   View Source Code Vote up 5 votes
public Crash getCrashById(int id) {
  SQLiteDatabase readableDatabase = getReadableDatabase();
  Cursor cursor = readableDatabase.rawQuery(CrashTable.selectById(id), null);
  Crash crash = null;

  if (isCursorPopulated(cursor)) {
    crash = toCrash(cursor);
    cursor.close();
    readableDatabase.close();
  }

  return crash;
}
 
Example 13
Project: Sanxing   File: TaskRepo.java   View Source Code Vote up 5 votes
public Long getCount(){

        String sql = "select count(*) from "+Task.TABLE;
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery(sql, null);
        cursor.moveToFirst();
        long count = cursor.getLong(0);
        cursor.close();
        return count;

    }
 
Example 14
Project: storj_hoststats_app   File: DatabaseManager.java   View Source Code Vote up 5 votes
public Cursor getNodeStoredBytes(String nodeID) {
    SQLiteDatabase db = mDbHelper.getReadableDatabase();

    Cursor cursor = db.rawQuery("SELECT * FROM " + NodeReaderContract.NodeStoredBytesEntry.TABLE_NAME + " WHERE " +
            NodeReaderContract.NodeStoredBytesEntry.NODE_ID+" = '"+ nodeID +"' limit 1000", null);

    cursor.moveToFirst();
    return cursor;
}
 
Example 15
Project: QuranAndroid   File: DatabaseAccess.java   View Source Code Vote up 5 votes
/**
 * Function to get the part start page
 *
 * @param partNumber Part Number
 * @return Page number
 */
public int getPartStartPage(int partNumber) {
    int pageNumber = 0;
    SQLiteDatabase db = openDB(MAIN_DATABASE);
    String sql = "select page from aya where joza = " + partNumber + " limit 1 ;";
    Cursor cursor = db.rawQuery(sql, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        pageNumber = cursor.getInt(0);
        cursor.moveToNext();
    }
    cursor.close();
    closeDB(db);
    return pageNumber;
}
 
Example 16
Project: FlickLauncher   File: LauncherProvider.java   View Source Code Vote up 5 votes
@Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
    db.beginTransaction();
    try {
        if (addRankColumn) {
            // Insert new column for holding rank
            db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
        }

        // Get a map for folder ID to folder width
        Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
                + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
                + " GROUP BY container;",
                new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});

        while (c.moveToNext()) {
            db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
                    + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
                    new Object[] {c.getLong(1) + 1, c.getLong(0)});
        }

        c.close();
        db.setTransactionSuccessful();
    } catch (SQLException ex) {
        // Old version remains, which means we wipe old data
        Log.e(TAG, ex.getMessage(), ex);
        return false;
    } finally {
        db.endTransaction();
    }
    return true;
}
 
Example 17
Project: NeteaseCloudMusic   File: PlaylistModel.java   View Source Code Vote up 5 votes
public boolean isInPlaylist(int playlistID,String path) {
    SQLiteDatabase db = mDBHelper.getWritableDatabase();
    Cursor cursor = db.rawQuery("select * from playlist_detail where (list_id==?) and (path==?);", new String[]{String.valueOf(playlistID), path});
    boolean value = cursor.moveToFirst();
    cursor.close();
    db.close();
    return value;
}
 
Example 18
Project: PeSanKita-android   File: MediaDatabase.java   View Source Code Vote up 4 votes
public Cursor getMediaForThread(long threadId) {
  SQLiteDatabase database = databaseHelper.getReadableDatabase();
  Cursor cursor = database.rawQuery(MEDIA_QUERY, new String[]{threadId+""});
  setNotifyConverationListeners(cursor, threadId);
  return cursor;
}
 
Example 19
Project: ChatKeyboard-master   File: EmoticonDBHelper.java   View Source Code Vote up 4 votes
public synchronized ArrayList<EmoticonSetBean> queryEmoticonSet(String sql) {
    SQLiteDatabase db = mOpenDbHelper.getReadableDatabase();
    Cursor cursor = null;
    try {
        cursor = db.rawQuery(sql, null);
        int count = cursor.getCount();
        ArrayList<EmoticonSetBean> beanList = new ArrayList<EmoticonSetBean>();
        if (count > 0) {
            cursor.moveToFirst();
            for (int i = 0; i < count; i++) {
                String name = cursor.getString(cursor.getColumnIndex(TableColumns.EmoticonSetColumns.NAME));
                int line = cursor.getInt(cursor.getColumnIndex(TableColumns.EmoticonSetColumns.LINE));
                int row = cursor.getInt(cursor.getColumnIndex(TableColumns.EmoticonSetColumns.ROW));
                String iconUri = cursor.getString(cursor.getColumnIndex(TableColumns.EmoticonSetColumns.ICON_URI));
                boolean isshowdelbtn = cursor.getInt(cursor.getColumnIndex(TableColumns.EmoticonSetColumns.IS_SHOW_DEL_BTN)) == 1;
                int itempadding = cursor.getInt(cursor.getColumnIndex(TableColumns.EmoticonSetColumns.ITEM_PADDING));
                int horizontalspacing = cursor.getInt(cursor.getColumnIndex(TableColumns.EmoticonSetColumns.HORIZONTAL_SPACING));
                int verticalSpacing = cursor.getInt(cursor.getColumnIndex(TableColumns.EmoticonSetColumns.VERTICAL_SPACING));
                boolean isShownName = cursor.getInt(cursor.getColumnIndex(TableColumns.EmoticonSetColumns.IS_SHOWN_NAME)) == 1;

                ArrayList<EmoticonBean> emoticonList = null;
                if (!TextUtils.isEmpty(name)) {
                    String sqlGetEmoticonBean = "select * from " + TABLE_NAME_EMOTICONS + " where " + TableColumns.EmoticonColumns.EMOTICON_SET_NAME + " = '" + name + "'";
                    emoticonList = queryEmoticonBeanList(sqlGetEmoticonBean);
                }

                int pageCount = 0;
                if (emoticonList != null) {
                    int del = isshowdelbtn ? 1 : 0;
                    int everyPageMaxSum = row * line - del;
                    pageCount = (int) Math.ceil((double) emoticonList.size() / everyPageMaxSum);
                }

                EmoticonSetBean bean = new EmoticonSetBean(name, line, row, iconUri, isshowdelbtn, isShownName, itempadding, horizontalspacing, verticalSpacing, emoticonList);
                beanList.add(bean);
                cursor.moveToNext();
            }
            return beanList;
        }
    } catch (SQLiteException e){
        Log.e(TAG, "query failed", e);
    } finally {
        if ( cursor != null ) cursor.close();
    }
    return null;
}
 
Example 20
Project: VennTracker   File: DatabaseHelper.java   View Source Code Vote up 4 votes
public Cursor getAllLocations() {
    SQLiteDatabase db = this.getReadableDatabase();
    return db.rawQuery("select * from " + TABLE_NAME, null);
}