Retrive specific data in row from SQLite database - android

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.

Related

Android SQLite: How to retrieve data from a table using the id's retrieved from other table

I have two tables say
TableA
________________________
|ADTMeasurement|ADTid |
|--------------|----- |
|measurement |1~1~3 |
|measurement |1~1~12 |
|measurement |1~1~7 |
|measurement |1~1~11 |
|measurement |1~1~99 |
------------------------
TableB
________________________________
|ADTName |ADTid |ADTType |
|------------|-------|---------|
|ADTName_1 |1~1~3 |DTType_1 |
|ADTName_2 |1~1~12 |DTType_2 |
|ADTName_4 |1~1~7 |DTType_3 |
|ADTName_4 |1~1~11 |DTType_4 |
|ADTName_5 |1~1~99 |DTType_5 |
|ADTName_6 |1~1~10 |DTType_3 |
|ADTName_7 |1~1~4 |DTType_4 |
|ADTName_7 |1~1~6 |DTType_5 |
--------------------------------
How do I retrieve selected rows from tableB; for all the "ADTid" from tableA. I need to save the result in a JSONarray so that I can send the it to the server.
Below is the code which I tired to use, which is wrong.
public Cursor getSavedMeasuremnet() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor mCursor = db.query("SELECT * FROM TableB WHERE ADTId IN (SELECT ADTId FROM TableA WHERE ADTMeasurment = 'measurement'");
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
I am getting an error msg - cannot resolve method “query(java.lang.string)”
There is not query method with String only as parameter,you have to pass all the parameter in method as mention below
public JSONArray getSavedMeasuremnet() {
JSONArray jsonArray=new JSONArray();
SQLiteDatabase db = this.getWritableDatabase();
Cursor mCursor = db.rawQuery("SELECT * FROM TableB JOIN TableA ON TableA.ADTid == TableB.ADTid where TableA.ADTMeasurement='measurement'",null)
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
try {
JSONObject jsonObject=new JSONObject();
jsonObject.put("ADTName",cursor.getString(cursor.getColumnIndex("ADTName")));
jsonObject.put("ADTid",cursor.getString(cursor.getColumnIndex("ADTid")));
jsonObject.put("ADTType",cursor.getString(cursor.getColumnIndex("ADTType")));
jsonArray.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
cursor.moveToNext();
}
return jsonArray;
}

Inserting an id of specific array value which did not exist in Table A and inserting in Table B

I have three table: symptoms, disease, symDisease
| Disease | | Symptoms | | symDisease |
--------------- -------------- ----------------
| id(pk) | | id(pk) | | diseaseId(fk)|
| name | | symp | | symptomId(fk)|
Code that checks existence of value in array and inserts into Database:
public Cursor checkExistence(){
Cursor c=null;
String[] values={"headache","heartburns"};
SQLiteDatabase db= getReadableDatabase();
db.beginTransaction();
try {
for (String value : values) {
long count = DatabaseUtils.queryNumEntries(db,
TABLE_SYMPTOMS, COLUMN_SYMP+" = ?", new String[] { value });
if (count == 0) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_SYMP, value);
db.insert(TABLE_SYMPTOMS, null, cv);
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
return c;
}
The code above checks to see if values in String[] values={"headache","heartburns"}; exist in table symptoms. In this case headache exist but heartburns doesn't exist in table symptoms,so it is inserted into the table.
Now would like to get the id of heartburns and insert it in to table symDisease along with a diseaseid. Example the diseaseid of Malaria = 1.
So at the end of the insertion in Table symDisease it should be like (idOfMalaria, idOfHeartburns).
You can get de ID of the row inserted with:
long rowInserted = db.insert(TABLE_SYMPTOMS, null, cv);
if (rowInserted != -1) {
//New row was added correctly, and the id of the inserted
//value is in rowInserted.
}else{
//Error on inserted
}

SQLite on Android return wrong result

I'm having some troubles querying my SQLite DB from my Android APP.
This is the table I'm querying:
id | customerCode | invoiceNumber | openAmount | grossAmount
and this are the datas:
1 | 1 | 1 | -1.00 | -1.00
2 | 1 | 1 | 1.00 | 1.00
3 | 1 | 1 | 10.00 | 10.00
4 | 1 | 2 | 0.00 | 20.00
5 | 1 | 3 | 0.00 | 30.00
I'm trying to fetch only the lines which have openAmount != "0.00" and the query is:
String whereClause = MyTable.CUSTOMER_CODE + " = ? "
+ "and " + MyTable.OPEN_AMOUNT + " != \"0.00\"";
Cursor cur = mDb.query(MyTable.TABLE, null, whereClause, new String[]{customerId}, null, null, null);
The result I expect is that the query fetch the first 3 lines from my table, and this is the result I obtain if I query the DB from an external application (like SQLite Magic).
BUT... when I run the query from my Application, I obtain only the line with openAmount = -1.00.
I've tried a lot of solutions, like changing the where condition to fetch all the lines, but it seems that querying from my App not reads line 2 and 3.
I can't figure out a solution.
A little help would be appreciated.
EDIT
All columns are TEXT.
It's not relevant how I iterate trhough the
datas, in fact the cursor altready returns a wrong number of lines.
EDIT 2
I'm cycling though the result Cursor, and this is how i do it:
List<MyObject> list = new ArrayList<>();
MyObject obj;
//initialization of columnsIndex
//int idx1 = cur.getColumnIndex(columnName);
if (cur.moveToFirst()) {
do {
obj = new MyObject();
//set obj data
list.add(obj);
} while (cur.moveToNext());
}
cur.close();
Try like this:
String whereClause = MyTable.CUSTOMER_CODE + " = ? "
+ "and " + MyTable.OPEN_AMOUNT + " NOT LIKE '0.00'";
Cursor cur = mDb.query(MyTable.TABLE, null, whereClause, new String[]{customerId}, null, null, null);

Select only last inserted row per parent_id

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

SQLite query to update some (not all) date formats

My database currently has a column which looks like this:
id | timestamp
-- | ---------
1 | 07/29/2014
2 | 07/30/2014
3 | 07/30/2014
4 | 2014-07-30
5 | 2014-07-30
I am trying to format any rows of timestamp in the old format, to the new format
in this example, rows 1-3 need to be reformatted
07/29/2014 -> 2014-07-29
07/30/2014 -> 2014-07-30
07/30/2014 -> 2014-07-30
I am not that familiar with SQL/SQLite but and from to come up with some sql i can execute once to see if there are any rows in the old format, and if they are, replace them with the equivalent of the new format.
any help would be greatly appreciated.
I believe I am trying to do what this user here wrote but couldn't get it to work
https://stackoverflow.com/a/7781473/433866
Thanks!
Here are the results I am getting with some real data:
timestamp column old / timestamp converted
07/25/2014 -> 01/04/0031
05/21/2014 -> 11/04/0026
01/25/2013 -> 07/06/0030
09/25/2000 -> 02/21/0031
07/25/2015 -> 01/05/0031
07/25/2016 -> 01/06/0031
07/25/1999 -> 12/20/0030
07/25/1986 -> 12/07/0030
and here is the method i am using
// REFORMAT DATES
public void reformatDates(String table){
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT * FROM " + table;
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
db.execSQL("update Food set timestamp = substr(timestamp,4,2) || '-' || substr(timestamp, 1,2) || '-' || substr(timestamp, 7) where timestamp LIKE '%/%'");
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
}
Got it this time!
// REFORMAT DATES
public void reformatDates(String table){
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT * FROM " + table;
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
db.execSQL("update " + table + " set timestamp = substr(timestamp, 7) || '-' || substr(timestamp, 1,2) || '-' || substr(timestamp,4,2) WHERE timestamp LIKE '%/%'");
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
}

Categories

Resources