Single value from cursor to int - android

I can't seem to figure out how I get the result from my select query (which should be one number) into my int min. Found different solution using Google but none worked.
I need the min value in order to check if the score that the current player has is higher than the lowest score in order to get in the highscores.
public int getMin(){
System.out.println("in getmin");
String selectQuery = "SELECT MIN(score) FROM tblscore;";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
int min = "something here to put the result in the int"
cursor.close();
db.close();
return min;
}

You could read the value through a cursor, but for single-valued queries like this, there is helper function in the DatabaseUtils class which makes things simpler:
public int getMin(){
String selectQuery = "SELECT MIN(score) FROM tblscore";
SQLiteDatabase db = this.getReadableDatabase();
try {
return (int)DatabaseUtils.longForQuery(db, selectQuery, null);
} finally {
db.close();
}
}

First you need to point the cursor to the first line:
cursor.moveToFirst();
Then you can use Cursor.getInt to get the value:
int min = cursor.getInt(0);

Related

How to get specific value from DB by id

How to get specific value from DB by id.
This is my table: TABLE-RECORDS-(name of table) and KEY-ID , KEY-PRICE ... I'm trying to get KEY-PRICE by KEY-ID and can not. How to do it?
I don't know if this is exactly what you are looking for, but this is the query.
SELECT key-price FROM table-record WHERE key-id='id number you need';
// please change the column names of database if i have mistaken
public Cursor getCursor(int id) {
SQLiteDatabase db = this.getReadableDatabase();
String from[] = {"key-price"};//this is the edit1
String where = "key-id=?";//this is the edit2
String[] whereArgs = new String[]{String.valueOf(id)+""}; //this is the edit3
Cursor cursor = db.query(true, table-records, from, where, whereArgs, null, null, null, null);
return cursor;
}
//just call this function and see the magic
private int getPrice(int id) {
Cursor c = getCursor(id);
int price=-1;
if(c != null)
{
while(c.moveToNext){
//assuming price is an integer
price = c.getInt(0);//edit 4
// use these strings as you want
}
}
return price;
}

retrieve data from database what next?

ok I just followed an instruction that I should do this to retrieve sql data from database but it just cuts to there so far I have this inside my databasehelper class.
public void getIconResource(String tblName)
{
SQLiteDatabase db = this.getReadableDatabase();
String getresource = "Select * from " + tblName;
Cursor cursor = db.rawQuery(getresource,null); //null for conditions
if(cursor.moveToFirst())
{
do
{
int resource = cursor.getInt(3);
}
while (cursor.moveToNext());
}
db.close();
}
So somehow this does is it get all the values of my tables 4th column which contains an int... how do I retrieve the value in my MainActivity and save it in an array of integers?
just add everything in a ArrayList and return the arraylist
simply call the method in your main activty
public ArrayList<Integer> getIconResource(String tblName)
{
SQLiteDatabase db = this.getReadableDatabase();
String getresource = "Select * from " + tblName;
Cursor cursor = db.rawQuery(getresource,null); //null for conditions
ArrayList data= new ArrayList<>();
if(cursor.moveToFirst())
{
do
{
int resource = cursor.getInt(3);
data.add(resource);
}
while (cursor.moveToNext());
}
db.close();
}
return data;
}
Well, as you have it, the variable resource is scoped only to the while loop. Even if it wasn't it would constantly get overwritten on each loop iteration.
Instead, you should declare a collection higher up and Add each value to it during your while loop. You could also redefine your function to return the collection if integers.
public List<int> getIconResource(String tblName)
{
SQLiteDatabase db = this.getReadableDatabase();
List<int> myVals = new List<int>();
String getresource = "Select * from " + tblName;
Cursor cursor = db.rawQuery(getresource, null); //null for conditions
if (cursor.moveToFirst())
{
do
{
myVals.Add(cursor.getInt(3));
}
while (cursor.moveToNext());
}
db.close();
return myVals;
}
Also, as a note... string concatenation of a SQL query is a recipe for disaster. Look up SQL Injection and best practices to avoid it before continuing further. It is worth the time to get into good habits early on.
EDIT / ADDENDUM
Unless you also limit your result set returned from your table query, you will be getting every record. The function you have here really has no practical use and would likely cause more problems than any benefits it may have. I would suggest, as an example of a more usable function that returns a specific IconResource based on the IconId:
public int getIconResource(int iconId)
{
SQLiteDatabase db = this.getReadableDatabase();
String getresource = "select IconResource from IconTable where IconId = ?";
PreparedStatement pstmnt = db.prepareStatement(getresource);
pstrmnt.setString(1, iconId);
ResultSet rset = db.executeQuery();
int iconResource;
if (rset.next())
iconResource = rset.getInt("IconResource");
db.close();
return iconResource;
}
Of course, the above is making assumptions of your table structure.
Using the above, in your code elsewhere, you would simply call this function with the IconId and use the output however needed:
int iconResource = getIconResource(5); // returns the IconResource for IconId = 5
The above prevents any possible SQL Injection attacks by using a parameterized query and avoiding the use of dynamic concatenated strings sent to your SQL server.
You may try out the following code:
public List<Integer> getIconResource(String tblName)
{
List<Integer> list = new ArrayList<Integer>();
list.clear();
SQLiteDatabase db = this.getReadableDatabase();
String getresource = "Select * from " + tblName;
Cursor cursor = db.rawQuery(getresource,null); //null for conditions
if(cursor.moveToFirst())
{
do
{
int resource = cursor.getInt(3);
list.add(resource);
}
while (cursor.moveToNext());
}
db.close();
return list;
}
Then call this method in MainActivity and store the List in another Integer type list.
databasehelper dbhelper;
List<Integer> newList = dbhelper.getIconResource("Your tablename");
fot(int i = 0 ; i< newList.size() ; i++){
int yourValue = newList(i);
}

SQLite: How to get average of long type values

I'm making an app that records the timestamp of touchscreen actions made my the user.
Then, after recording the readings in an SQLite table, I take the average of each column at the end. However, I'm getting an error:
E/AndroidRuntime(1344): java.lang.NumberFormatException: Invalid long: "1.40024e+08"
This happens when I try to take the average of each column, which I'm doing like so:
public long[] getAvg()
{
String selectQuery = "SELECT AVG(dwell_1), AVG(dwell_2), AVG(dwell_3), AVG(dwell_4), AVG(dwell_5), AVG(dwell_6), AVG(dwell_7), AVG(dwell_8), AVG(dwell_9), AVG(flight_12), AVG(flight_23), AVG(flight_34), AVG(flight_45), AVG(flight_56), AVG(flight_67), AVG(flight_78), AVG(flight_89) FROM " + TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
long[] row = new long[17];
if (cursor.moveToFirst()) {
for (int j=0; j<17; j++)
row[j] = Long.parseLong(cursor.getString(j));
}
return row;
}
It seems to be a function of the way the SQLite query displays the results. Is there any way I can circumvent/solve this? I require the precision by the way, so I can't use int or something else instead.
Oddly enough, when I run a query to just straight up display every record in the table, it works fine.
Any help will be greatly appreciated. Thanks in advance!
I believe SQLiteAVG() function returns a float value which you are trying to parse it as Long, hence the exception.
Try this :
public long[] getAvg()
{
String selectQuery = "SELECT AVG(dwell_1), AVG(dwell_2), AVG(dwell_3), AVG(dwell_4), AVG(dwell_5), AVG(dwell_6), AVG(dwell_7), AVG(dwell_8), AVG(dwell_9), AVG(flight_12), AVG(flight_23), AVG(flight_34), AVG(flight_45), AVG(flight_56), AVG(flight_67), AVG(flight_78), AVG(flight_89) FROM " + TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
long[] row = new long[17];
if (cursor.moveToFirst()) {
for (int j=0; j<17; j++)
row[j] = cursor.getLong(j);
}
return row;
}
SQLite returns float result, which you are trying to save to long.
Possible solutions:
Use float/double variables on Java side.
Or force SQLite to output integer/long using
SELECT CAST(avg(field) AS INTEGER) AS avg_field...
In your case, result should still fit into Java long if original was SQLite INTEGER.
Consider a simple method that fetches the average rating of an entity. The rating float value is stored between 0.0 to 5.0.
public static float getAverageReviews(SQLiteDatabase db) {
String selectQuery = "SELECT SUM(stars) * FROM " + DatabaseHelper.TABLE_STORE_REVIEWS;
Cursor c = db.rawQuery(selectQuery, null);
int count = c.getCount();
float totalSum = 0;
if(count > 0 && c.moveToFirst())
{
do {
String result = c.getString(c.getColumnIndex(StoreReviews.KEY_STARS));
totalSum += Float.parseFloat(result);
} while (c.moveToNext());
}
else {
return 0;
}
return totalSum/count;
}

How to get the row count of a query in Android using SQLite?

How do I get the row count of a query in Android using SQLite? It seems my following method does not work.
public int getFragmentCountByMixId(int mixId) {
int count = 0;
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
Cursor cursor = db.rawQuery(
"select count(*) from downloadedFragement where mixId=?",
new String[]{String.valueOf(mixId)});
while(cursor.moveToFirst()){
count = cursor.getInt(0);
}
return count;
}
Cursor.getCount()
cursor.moveToNext();
cursor.getCount();
If the moveToNext() is not called, the cursorIndexOutOfBoundException may arise.
This would be more efficient because work for all versions:
int numRows = DatabaseUtils.longForQuery(db, "SELECT COUNT(*) FROM table_name", null);
or
int numRows = DatabaseUtils.queryNumEntries(db, "table_name");
or if you want to get number of rows which specific selection then you should go with (added in API 11)
public static long queryNumEntries (SQLiteDatabase db, String table, String selection)
Thanks :)
use String instead of int
String strCount = "";
int count = 0;
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
Cursor cursor = db.rawQuery(
"select count(*) from downloadedFragement where mixId=?",
new String[]{String.valueOf(mixId)});
while(cursor.moveToFirst()){
strCount = cursor.getString(cursor.getColumnIndex("COUNT(*)"));
}
count = Integer.valueOf(strCount).intValue();
Query for _ID column in table and then call getCount on cursor. Here is a link I am doing in one of my project. Look at line number 110.
In DatabaseUtils
public static long queryNumEntries(SQLiteDatabase db, String table)
public long getRecords() {
return DatabaseUtils.longForQuery(db, "SELECT COUNT(*) FROM contacts", null);
}
You can use this as a method or use this if your database uses auto increment
public long getRecords() {
return DatabaseUtils.longForQuery(db, "SELECT seq FROM sqlite_sequence", null);
}
val query = "SELECT * FROM $TABLE_NAME ;"
val result = db.rawQuery(query,null)
Toast.makeText(ctx,result.count,Toast.LENGTH_SHORT).show()

Get last inserted value from sqlite database Android

I am trying to get the last inserted rowid from a sqlite database in Android. I have read a lot of posts about it, but can't get one to work.
This is my method:
public Cursor getLastId() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_WID}, KEY_WID + "=" + MAX(_id), null, null, null, null, null);}
I have tried with MAX, but I must be using it wrong. Is there another way?
Well actually the SQLiteDatabase class has its own insert method which returns the id of the newly created row. I think this is the best way to get the new ID.
You can check its documentation here.
I hope this helps.
Use
SELECT last_insert_rowid();
to get the last inserted rowid.
If you are using AUTOINCREMENT keyword then
SELECT * from SQLITE_SEQUENCE;
will tell you the values for every table.
To get the last row from the table..
Cursor cursor = theDatabase.query(DATABASE_TABLE, columns,null, null, null, null, null);
cursor.moveToLast();
Use moveToLast() in Cursor interface.
From android.googlesource.com
/**
* Move the cursor to the last row.
*
* <p>This method will return false if the cursor is empty.
*
* #return whether the move succeeded.
*/
boolean moveToLast();
Simple example:
final static String TABLE_NAME = "table_name";
String name;
int id;
//....
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
if(cursor.moveToLast()){
//name = cursor.getString(column_index);//to get other values
id = cursor.getInt(0);//to get id, 0 is the column index
}
Or you can get the last row when insertion(Which is #GorgiRankovski have mentioned):
long row = 0;//to get last row
//.....
SQLiteDatabase db= this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NAME, name);
row = db.insert(TABLE_NAME, null, contentValues);
//insert() returns the row ID of the newly inserted row, or -1 if an error occurred
Also their is a multiple ways you can do this using query:
One is expressed by #DiegoTorresMilano
SELECT MAX(id) FROM table_name. or to get all columns values SELECT * FROM table_name WHERE id = (SELECT MAX(id) FROM table_name).
If your PRiMARY KEY have sat to AUTOINCREMENT, you can SELECT vaules occording to max to min and limit the rows to 1 using SELECT id FROM table ORDER BY column DESC LIMIT 1
(If you want each and every value, use * instead of id)
If you want the last_insert_id just afert a insert you can use that :
public long insert(String table, String[] fields, String[] vals )
{
String nullColumnHack = null;
ContentValues values = new ContentValues();
for (int i = 0; i < fields.length; i++)
{
values.put(fields[i], vals[i]);
}
return myDataBase.insert(table, nullColumnHack, values);
}
The insert method returns the id of row just inserted or -1 if there was an error during insertion.
long id = db.insert("your insertion statement");
db is an instance of your SQLiteDatabase.
Try this:
public Cursor getLastId() {
return mDb.query(DATABASE_TABLE, new String[] { **MAX(id)** }, null, null, null, null, null, null);}
/**
* #return
*/
public long getLastInsertId() {
long index = 0;
SQLiteDatabase sdb = getReadableDatabase();
Cursor cursor = sdb.query(
"sqlite_sequence",
new String[]{"seq"},
"name = ?",
new String[]{TABLENAME},
null,
null,
null,
null
);
if (cursor.moveToFirst()) {
index = cursor.getLong(cursor.getColumnIndex("seq"));
}
cursor.close();
return index;
}
I use this
public int lastId(){
SQLiteDatabase db =
this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from resep", null );
res.moveToLast();
return res.getInt(0);
}
In your DbHelper class,
public long getLastIdFromMyTable()
{
SQLiteDatabase db = this.getReadableDatabase();
SQLiteStatement st = db.compileStatement("SELECT last_insert_rowid() from " + MY_TABLE);
return st.simpleQueryForLong();
}

Categories

Resources