This is my method which return MAX(_id)
public static int getMaxId(Context context, Uri uri, String columnName) {
//it is all
String []projection = new String[]{"MAX("+ columnName +")"};
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
cursor.moveToFirst();
return cursor.getInt(0);
}
If count of records in database <127 everything is all right, but if count of records >127 (for example 250 or 500) this method returns 127.
The max() aggregate function returns the maximum value of all values in the group. The maximum value is the value that would be returned last in an ORDER BY on the same column. Aggregate max() returns NULL if and only if there are no non-NULL values in the group.
If you had a column like that, say name it 'myorder', then you could use a
query like this to get the last row:
select * from mytable
where myorder IN (select max(myorder) from mytable)
If you mean get the row that would sort last in a query, then you have
something like this at the end of the query, after the "ORDER BY":
LIMIT 1 OFFSET (select count(*) from mytable) - 1
from here
Related
I just started learning of android and come to section of Database and I inserted same record in it but now I want to fetch data from database only by name and display it in textview.
Help me
Thank You in advance
Please follow developer document.
https://developer.android.com/training/basics/data-storage/databases.html
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
FeedEntry._ID,
FeedEntry.COLUMN_NAME_TITLE,
FeedEntry.COLUMN_NAME_SUBTITLE
};
// Filter results WHERE "title" = 'My Title'
String selection = FeedEntry.COLUMN_NAME_TITLE + " = ?";
String[] selectionArgs = { "My Title" };
// How you want the results sorted in the resulting Cursor
String sortOrder =
FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";
Cursor cursor = db.query(
FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
You access data by using a query which returns a Cursor.
A Cursor is like a spreadsheet table that contains columns and rows.
You tell the query what columns you want and imply the rows that will be returned via an optional WHERE statement.
The simplest of queries is base upon the SQL SELECT * FROM <table>;. This will select all columns (i.e. * means all columns) from the table as specified by <table> ( where would be replaced by a valid table name).
If you want specific columns then ***`` should be replaced with a comma delimited list e.g.SELECT name, address FROM would return a **Cursor** containing all the rows from the table with only the **name** and **address** columns from the table specified by`.
If you want to filter the rows returned then you can add a WHERE clause. e.g. SELECT name,address FROM <table> WHERE name = 'Fred', would return a Cursor containing only the rows that have Fred as the name column with only the name and address columns.
You cannot just type the SQL statments you need to either use the SQLiteDatabase rawQuery or query methods if you need to return a cursor.
Using rawQuery
rawQuery takes two parameters, the first being the SQL as a string, the second optional arguments (not covered here, so null will be used).
To obtain a Cursor with columns name and address and with only rows that have Fred you could use, assuming the table is called mytable :-
`Cursor mycursor = db.rawQuery("SELECT name,address FROM mytable WHERE name = 'Fred'";);`
where db is an instance of an SQLiteDatabase object.
However, rawQuery is not recommended as it is open SQL injection. rather it is recommended only for situations where it has to be used.
Using query
query has a number of overload variations as can be found here SQLiteDatabase.
For this example query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) will be used.
String table, is the name of the table to be queried.
String[] columns, is an array of column names.
String selection is the where clause (null for no where clause).
String[] selectionArgs is an array of arguments that replace the ? placeholder.
The rest of the parameters will be null as these are features that are not being utilised.
As such the code could be :-
String tablename = "mytable";
String[] columns = {"name", "address"};
String whereclause = "name=?"; //note use of placeholder ?
String[] whereargs = {"Fred"};
Cursor mycursor = db.query(tablename,
columns,
whereclause,
whereargs,
null,null,null
);
where db is an instance of an SQLiteDatabase object.
Accessing the Cursor
mycursor contains the data or perhaps not if there isn't a column with the name Fred.
The number of rows in the cursor can be obtained by using:-
int rowsincursor = mycursor.getCount();
Note! A returned Cursor will not be null. (a very common mistake)
To access the data you have to move through the Cursor. Initially the Cursor is before the first row. If you only expect or want the only/first row then you can use the Cursor moveToFirst method.
See Cursor for more move... methods etc
Once the Cursor is appropriately positioned you can use Cursor get methods to get the data. e.g. getString(int columnindex) will return the data as a String. columnindex is a 0 based offset of the column to be accessed. Using the Cursor's getColumnIndex(String columnname) can be used to eliminate errors made by miscalculating offsets.
As such the following could be used to set a TextView (note intentionally over cautious)
if (mycursor.getCCount() > 0) {
if (mycursor.moveToFirst()) {
mytextview.setText(mycursor.getString(mycursor.getColumnIndex("name")));
}
}
mycursor.close() // You should always close a cursor when done with it.
I'm trying to get the number of entries my DB holds - in the most simple way possible.
I'm trying to use the rawQuery "SELECT Count(*) FROM Students" and then from the cursor to do an getInt method to get the number and use it later on.
this is my method
public int getNumberOfEntries() {
SQLiteDatabase db = helper.getWritableDatabase();
String query = ShaqedDB.NUMBER_OF_ENTRIES;
Cursor d = db.rawQuery(query, null);
d.moveToFirst();
while (!d.isAfterLast()) {
int numberReturned = d.getInt(0);
d.moveToNext();
return numberReturned;
}
return 0;
}
I've looked everywhere - and I cannot find a solution to why am I keep getting the cursor error that the cursor cannot read row 0, col 1... even though I think I point it to col 0
if you don't need to write, you should use getReadableDatabase(); instead of getWritableDatabase();. In
d.getInt(0);
0 is the index of column you want to retrieve the value. Don't hardcode the value. Ask the cursor to retrieve the column index
d.getInt(d.getColumnIndexOrThrow("COLUMN_NAME"));
about your query, you want to now the number of results returned by your query. You can retrieve this value asking the cursor's count:
public int getNumberOfEntries() {
SQLiteDatabase db = helper.getReadableDatabase();
String query = ShaqedDB.NUMBER_OF_ENTRIES;
Cursor d = db.rawQuery(query, null);
return d.getCount();
}
I have a table with this info:
i create table.
db.execSQL("CREATE TABLE IF NOT EXISTS income (id_income INTEGER
PRIMARY KEY AUTOINCREMENT, id_category INT(20), id_account INT(20),
Year INT(5), month INT(5), day INT(5) ,pay DOUBLE(20));");
then i insert a row in this table:
db.execSQL("INSERT INTO
income(id_category,id_account,Year,month,day,pay) VALUES
(1,1,2013,1,1,678);");
Then i select * from my table,
String selectQuery = "SELECT * FROM income ";
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
int count = cursor.getCount();
if(count>0){
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
int temp_acc1;
int temp_cat;
temp_acc1=(cursor1.getColumnIndex("id_account"));
temp_cat=(cursor1.getColumnIndex("id_category"));
}
}
But when i log temp_acc1 or temp_cat, it returns number of column.
For example temp_acc1 returns 3 // actually returns 1
or temp_cat returns 2 // actually returns 1
or if i use temp_year=cursor1.getColumnIndex("Year") it returns 5.//// actually returns 2013
What should i do?
Please help me.
Change this kind of codecursor1.getColumnIndex("Year") to this cursor1.getInteger(cursor1.getColumnIndex("Year")). So it will return the value
How can i get the last N elements of a table?
I have used this query but it does not seem to work.
Cursor c = database.rawQuery("select top 7 * from dailystats order by daily_ID desc;", null);
For earning the point, I make my comment as an answer as requested by the OP;)
use limit, select * from dailystats order by daily_ID desc LIMIT 7
Just use limit:
select * from dailystats order by daily_ID desc limit 7;
Top is for SQL Server You need to use Limit
select * from dailystats order by daily_ID desc limit 7;
OR to Select just the last row
select * from dailystats where daily_ID = (select max(daily_ID) from dailystats);
If you allow me to convert all those answers to more Android-code like:
SQLiteDatabase database = dbHelper.getReadableDatabase();
String tableName = "dailystats";
String orderBy = "daily_ID desc";
String limit = String.valueOf(5);
Cursor cursor = database.query(tableName,
null, //all columns
null, // no where clause
null, // no where arguments
null, // no grouping
null, // no having
orderBy,
limit);
From then on you use the cursor as any other cursor in Android. It will hold the top limit results with respect to the orderBy column in descending order.
I am using SQLite in Android.
I have the query, query executed and how to print count from cursor.
Cursor dataCount = mDb.rawQuery("select count(*) from " + DATABASE_JOURNAL_TABLE, null);
I have no record in table.
You already have the correct approach.
Cursor cursor = database.rawQuery("select count(*) from " + DATABASE_JOURNAL_TABLE, null);
// ensure there is at least one row and one column
if (cursor.getCount() > 0 && cursor.getColumnCount() > 0) {
cursor.close();
return cursor.getInt(0);
} else {
cursor.close();
return 0;
}
You must check that there is at least 1 row and 1 column, if you provide a table that does not yet exist there will be no column to access and cursor.getInt(0) will throw an exception.
source: https://github.com/samkirton/SQLKing
May be by getInt(index) as
cursor.getInt(1); // this is for example, you have to adjust index in your code
Also cursor has a built in function getCount() to return row number so can also do like this:
// assuming your table has `id` column as primary key or unique key.
Cursor dataCount = mDb.rawQuery("select id from " + DATABASE_JOURNAL_TABLE, null);
dataCount.getCount();
See android devloper's doc for Cursor for more information.