I have following table. I fetched this data from JSON and store it to SQLite table. I want to fetch all data from TABLE_MAC where meal_id = 12.
TABLE_MAC
| _id | meal_id | name |
----------------------------
| 1 | 12,16,17| mac veggi|
| 2 | 14,16 | mac allo |
| 3 | 16,12,14| mac egg |
| 4 | 112,1,14| fries |
Now, from a database, I want to fetch all data from meal_id = 12. I applied LIKE operator for fetching data from a database, but it adds fries in Android.
Call LIKE Operator
public List<Model> getAllResult(String getId)
{
List<Model> resultList = new ArrayList<Model>();
// Select All Query
String selectQuery = "SELECT * FROM "+ TABLE_MAC + " WHERE " + KEY_Meal_ID + " LIKE '%"+getId+"%'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do {
Model sg = new Model();
sg.set_id((cursor.getString(0)));
......
resultList.add(sg);
} while (cursor.moveToNext());
cursor.close();
db.close();
}
// return list
return resultList;
}
Try something like this to query your database
SQLiteDatabase database = this.getWritableDatabase();
String[] columns = new String[] {"_id", "meal_id", "name"};
String TABLE_NAME = "TABLE_MAC";
Cursor mCursor =
database.query(true, TABLE_NAME, columns,
"meal_id=12", null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
Then you will have to loop through your Cursor to retrieve your data.
Having comma separated id's in your meal_id column is not a good idea. You should implement a mapping table or rethink your database to avoid this.
Here is my sqlite table:
_ID | DATE_INSERTED | LATITUDE | LONGITUDE | TRACKER_ID | DATA
I need to get a Cursor with the last inserted row (by DATE_INSERTED) per TRACKER_ID, where LATITUDE and LONGITUDE are not equal to "0".
I'm doing it in a CursorLoader, this is where I could get:
public static CursorLoader getLoaderForLastMessages(Context context) {
String sel = MessageTable.LONGITUDE + " !=? and " + MessageTable.LATITUDE + " !=?";
String[] selArgs = {"0", "0"};
return new CursorLoader(context, GpsProvider.MESSAGE_CONTENT_URI, null, sel, selArgs, null);
}
I don't know how to select only the last row per TRACKER_ID. I guess DISTINCT and GROUP BY are good words, but I don't know how to use them correctly.
A raw SQLITE query is a good answer too, I'll adapt it to my code.
EDIT:
To clarify I need a Cursor like this:
_ID | DATE_INSERTED | LATITUDE | LONGITUDE | TRACKER_ID | DATA
3 | 23424123 | 13 | 43 | 1 | data
6 | 23563344 | 25 | 56 | 2 | data
19 | 56573473 | 37 | 12 | 3 | data
43 | 23635743 | 82 | 99 | 4 | data
You can query the Table for the last inserted RowID:
//Get the last inserted unique primary id (_id) of your table.
public int getPrimaryId() {
final String MY_QUERY = "SELECT MAX(_id) FROM " + DATABASE_TABLE0;
Cursor cur = mDb.rawQuery(MY_QUERY, null);
cur.moveToFirst();
int ID = cur.getInt(0);
cur.close();
return ID;
}
You can use this ID to specify in a query and load the results in your cursor.
Try this:
String selectQuery = "SELECT * FROM " + <TABLE_NAME> + " WHERE TRACKER_ID = \"" + <trackID> + "\" AND LATITUDE != '0' AND LONGITUDE != '0' AND DATE_INSERTED = \"" + <date>" ;
Cursor cursor = sqliteDatabase.rawQuery(selectQuery, null);
if(cursor.moveToLast()){
//Get the value here using cursor.getString(<column number>)
}
May be a Select Query like:
SELECT A._ID , A.DATE_INSERTED , A.LATITUDE , A.LONGITUDE , A.TRACKER_ID , A.DATA
FROM MY_TABLE A
JOIN
(
SELECT TRACKER_ID, MAX(DATE_INSERTED) MAX_DATE_INSERTED FROM MY_TABLE
WHERE LATITUDE <> '0' AND LONGITUDE <> '0'
) B
ON A.TRACKER_ID = B.TRACKER_ID
AND A.DATE_INSERTED = B.MAX_DATE_INSERTED
I have a sqlite table in my android app and I need to count how many items have the same date. Here is a simple schema of the table:
col1 | col2 | date_item |
xx | xx | 2012-04-12|
yy | er | 2012-05-12|
... ... ...
I suppose that to count how many row has the same date i need to do the query using group by. The problemm is that if I do as follow:
Cursor cursor = db.query("table_name", new String[] {"date_item"}, null, null, "date_item", null, null);
and i return cursor.getColumnCount();. I get only 1 column. So how can i do this to have 2 columns (one for date_item and one for count)?
Thanks, Mattia
I have a one table question_table and one ImageButton (Back). I need to get the last inserted record from the database after clicking on the Back.
My row contains the following columns: question, optionA, optionB, optionC, optionD, and I need the data for use on my Activity. I create one method in database but it's not working.
Here is code for reference:
MySQLiteHelper.java extract:
public List<ObjectiveWiseQuestion> getLastInsertQuestion()
{
// long index = 0;
List<ObjectiveWiseQuestion>LocwiseProfileList=new ArrayList<ObjectiveWiseQuestion>();
db = getReadableDatabase();
Cursor cursor = db.query(
"sqlite_sequence",
new String[]{"seq"},
"name = ?",
new String[]{TABLE_QUESTION},
null,
null,
null,
null );
if (cursor.moveToFirst())
{
do {
ObjectiveWiseQuestion owq= new ObjectiveWiseQuestion();
owq.setQuestion(cursor.getString(2));
owq.setOptionA(cursor.getString(3));
owq.setOptionB(cursor.getString(4));
owq.setOptionC(cursor.getString(5));
owq.setOptionD(cursor.getString(6));
owq.setCorrectOption(cursor.getString(7));
LocwiseProfileList.add(owq);
} while(cursor.moveToNext());
db.close();
}
return LocwiseProfileList;
}
OnClickListner from AddQuestionActivity.java
imgBack.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View v)
{
msg();
emptyFormField();
try {
final List<ObjectiveWiseQuestion> LocWiseProfile = db.getLastInsertQuestion();
for (final ObjectiveWiseQuestion cn : LocWiseProfile)
{
db=new MySQLiteHelper(getBaseContext());
db.getWritableDatabase();
txtQuestion.setText(cn.getQuestion());
txtOptionA.setText(cn.getOptionA());
txtOptionB.setText(cn.getOptionB());
txtOptionC.setText(cn.getOptionC());
txtOptionD.setText(cn.getOptionD());
txtCorrectOption.setText(cn.getCorrectOption());
db.close();
}
} catch(Exception e) {
e.printStackTrace();
}
}
});
Please give me some hint.
I think the top answer is a bit verbose, just use this
SELECT * FROM table ORDER BY column DESC LIMIT 1;
Try this:
SELECT *
FROM TABLE
WHERE ID = (SELECT MAX(ID) FROM TABLE);
OR
you can also used following solution:
SELECT * FROM tablename ORDER BY column DESC LIMIT 1;
To get last record from your table..
String selectQuery = "SELECT * FROM " + "sqlite_sequence";
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
Here's a simple example that simply returns the last line without need to sort anything from any column:
"SELECT * FROM TableName ORDER BY rowid DESC LIMIT 1;"
I think it would be better if you use the method query from SQLiteDatabase class instead of the whole SQL string, which would be:
Cursor cursor = sqLiteDatabase.query(TABLE, allColluns, null, null, null, null, ID +" DESC", "1");
The last two parameters are ORDER BY and LIMIT.
You can see more at:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
If you have already got the cursor, then this is how you may get the last record from cursor:
cursor.moveToPosition(cursor.getCount() - 1);
//then use cursor to read values
Another option is to use SQLites LAST_VALUE() function in the following way.
Given this table:
+--------+---------+-------+
| OBJECT | STATUS | TIME |
+--------+---------+-------+
| | | |
| 1 | ON | 100 |
| | | |
| 1 | OFF | 102 |
| | | |
| 1 | ON | 103 |
| | | |
| 2 | ON | 101 |
| | | |
| 2 | OFF | 102 |
| | | |
| 2 | ON | 103 |
| | | |
| 3 | OFF | 102 |
| | | |
| 3 | ON | 103 |
+--------+---------+-------+
You can get the last status of every object with the following query
SELECT
DISTINCT OBJECT, -- Only unique rows
LAST_VALUE(STATUS) OVER ( -- The last value of the status column
PARTITION BY OBJECT -- Taking into account rows with the same value in the object column
ORDER by time asc -- "Last" when sorting the rows of every object by the time column in ascending order
RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING -- Take all rows in the patition
) as lastStatus
FROM
TABLE
The result would look like:
+--------+--------------+
| OBJECT | LAST_STATUS |
+--------+--------------+
| | |
| 1 | ON |
| | |
| 2 | ON |
| | |
| 3 | ON |
+--------+--------------+
Suppose you are looking for last row of table dbstr.TABNAME, into an INTEGER column named "_ID" (for example BaseColumns._ID), but could be anyother column you want.
public int getLastId() {
int _id = 0;
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query(dbstr.TABNAME, new String[] {BaseColumns._ID}, null, null, null, null, null);
if (cursor.moveToLast()) {
_id = cursor.getInt(0);
}
cursor.close();
db.close();
return _id;
}
Just simple, you can move with Cursor moveToLast(); method provides to move to the last record
cursor.moveToLast();
I wanted to maintain my table while pulling in one row that gives me the last value in a particular column in the table. I essentially was looking to replace the LAST() function in excel and this worked.
, (Select column_name FROM report WHERE rowid = (select last_insert_rowid() from report))
in sqlite, there is a table called sqlite_sequence, this table contains the table name and it's last id number (if the id is auto incremented).
So, to get the last row in a table just put :
Select * from TABLENAME where id=(SELECT * from sqlite_sequence where name ='TABLENAME')
The previous answers assume that there is an incrementing integer ID column, so MAX(ID) gives the last row. But sometimes the keys are of text type, not ordered in a predictable way. So in order to take the last 1 or N rows (#Nrows#) we can follow a different approach:
Select * From [#TableName#] LIMIT #Nrows# offset cast((SELECT count(*) FROM [#TableName#]) AS INT)- #Nrows#
Also, if your table has no ID column, or sorting by id doesn't return you the last row, you can always use sqlite schema native 'rowid' field.
SELECT column
FROM table
WHERE rowid = (SELECT MAX(rowid) FROM table);
Sometimes there is no ID column and ROWID does not help.
You may use simple query, which is universal (IMHO):
Select * from TABLE_NAME limit 1 offset ((select count() from TABLE_NAME) - 1)
I have a doubt to be clarified. How can i fetch the last value inserted into sqlite DB. I need code for that.I tried using query like this:
SELECT uname,umessage,utime FROM chatmessage ORDER BY utime DESC limit 1;
Where am i doing wrong?? I need help in this issue.
Thanks in advance.
SQLiteDatabase returns id of inserted row. You can rememember this id in some value and use it.
long lastId = db.insert(......);
if the value is last its id should be maximum
you can fire the query like this
c = db.rawQuery("SELECT uname,umessage,utime FROM tablename WHERE " +
"Id = (SELECT MAX(Id) FROM tablename ); ",null);
for last message by particular user add user id column in the message table like
id | userid | message | utime
1 | 1 | wlhf | 3:10
2 | 3 | dfhhfjh | 2:15
3 | 1 | kjfedhr | 4:00
4 | 2 | hejhe | 1:15
5 | 3 | kegekr | 3:30
6 | 1 | wlhf | 3:10
7 | 3 | dfhhfjh | 2:15
8 | 1 | kjfedhr | 4:00
9 | 2 | hejhe | 1:15
10 | 3 | kegekr | 3:30
c = db.rawQuery("
select message from table1 where
userid = 1 ; ",null);
recieve like
ArrayList<String> listMessg = new ArrayList<String>();
cursor = dbm.columnValueofCourse();
cursor.moveToFirst();
startManagingCursor(cursor);
for (int i = 0; i < cursor.getCount(); i++) {
reciv = cursor.getString(cursor
.getColumnIndex("message"));
listMessg.add(reciv_Par);
}
int sizeoflist = listMessg.size();
because in ascending order , the last index
of array list will be the last message of the user
System.out.println("THE LAST MESSAGE BY USER IS " + listMessg.et(sizeoflist -1));