Android sqlite Select Join Where - android

I am very new and trying to learn how to use Select, Join, and Where with sqlite in android. Ideally this is what I want to return from the Database:
People who have the role id of 4 (Ranged):
select people.[name]
from people
join people_role
on people.[id] = people_role.[people_id]
where role_id = 4
What would the code be for returning People that have the role_id of 4?

1- Create your database using SQLiteBrowser.
2- Keep the Database in assets folder
3- Follow this solution.
4- Find getTestData() in TestAdapter calss & replace it with :
public Cursor getTestData()
{
try
{
String sql ="select people.[name]
from people
join people_role
on people.[id] = people_role.[people_id]
where role_id = 4 ";
Cursor mCur = mDb.rawQuery(sql, null);
if (mCur!=null)
{
mCur.moveToNext();
}
return mCur;
}
catch (SQLException mSQLException)
{
Log.e(TAG, "getTestData >>"+ mSQLException.toString());
throw mSQLException;
}
}

Related

make sure cursor is initialized correctly before accessing data from it

Can anyone help me how to execute this query?
I am trying to fetch distinct supervisor from project table. supervisor is column name and its index is 5.
try {
String query = "select distinct supervisor from project ";
Cursor cursor= db.rawQuery(query,null);//query( query , null, null,null,null,null,null);
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(5));
} while (cursor.moveToNext());
}
// finish();
cursor.close();
db.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return labels;
}
Your query is wrong.
You have to query write like this.
select * from project where YOUR_CONDITION
I don't know what you exactly trying to do.
Example query.
select * from customers where LastName = 'Tremblay'
To get Distinct value of supervisor you should query like this.
select * from project group by supervisor
Hope it helps:)
You could use an if statement ie if cursor != null, do something.

Android - SQLiteException while deleting record

Currently We have one application in which we are receiving many crash reports while deleting record from database .
Here is method in which app is crashing.
public int deleteGroupMap(String nickName) {
SQLiteDatabase database = this.getWritableDatabase();
try {
return database.delete(TABLE_NAME_GROUP_MAP, COLUMN_GMAP_NICK_NAME + " = '" + nickName + "'", null);
} catch (Exception e) {
e.printStackTrace();
} finally {
database.close();
}
return 0;
}
but we am getting following exception:
android.database.sqlite.SQLiteException: near "adz": syntax error
(code 1): , while compiling: DELETE FROM groups_map WHERE
gmap_nick_name = ''adz.'
Any help will be appreciated.
Look at delete signature:
int delete (String table, String whereClause, String[] whereArgs)
Third argument is where args:
You may include ?s in the where clause, which will be replaced by the
values from whereArgs. The values will be bound as Strings.
It's automatically escaped, so there is no need to put quotes (', ") manually.
Use where args instead of strings concating:
database.delete(TABLE_NAME_GROUP_MAP, COLUMN_GMAP_NICK_NAME + " = ?", new String[] { nickName });
Try Like This
public int deleteGroupMap(String nickName) {
SQLiteDatabase database = this.getWritableDatabase();
try {
database .execSQL("DELETE FROM "+ TABLE_NAME_GROUP_MAP + " WHERE " + COLUMN_GMAP_NICK_NAME + " = "+nickName+"");
database .close();
} catch (Exception e) {
e.printStackTrace();
} finally {
database.close();
}
return 0;
}
Try this
return database.delete(TABLE_NAME_GROUP_MAP, COLUMN_GMAP_NICK_NAME + "= ?" , new String[]{Long.toString(nickName)});
You should also use parameter markers because appending values directly is error prone when the source contains special characters.
try following because it will also prevent SQL injections to your app
database.delete(TABLE_NAME_GROUP_MAP, COLUMN_GMAP_NICK_NAME + "=?", new String[]{String.valueOf(nickName));

SQLite select all tables DESC

I have found the solution to get all tables in SQLite here.
How to list the tables in an SQLite database file that was opened with ATTACH?
However, when I change:
SELECT name FROM sqlite_master WHERE type='table';
into:
SELECT name FROM sqlite_master WHERE type='table' ORDER BY name DESC;
the output is completely weird.
The first query gives me:
tbl201306 --> only 1 table so far, for June 2013.
The second query gives me:
android_metadata --> the name is not changed, but it returns this name.
I want to have these tables in descending order because in the future, the newest table would be on the top then.
My complete code:
public ArrayList<String> getDBTables() {
ArrayList<String> toReturn = new ArrayList<String>();
try {
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name DESC", null);
c.moveToFirst();
while (c.moveToNext()) {
toReturn.add(c.getString(c.getColumnIndex("name")));
}
c.close();
}
catch(SQLiteException e) {
e.printStackTrace();
}
return toReturn;
}
Your code skips over the first returned record.
You can either
keep the call to moveToFirst(), and change the loop into a do { ... } while (); loop, or
just remove the call to moveToFirst().
This is the ultimate solution I used:
public ArrayList<String> getDBTables() {
ArrayList<String> toReturn = new ArrayList<String>();
try {
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'tbl%' ORDER BY name DESC", null);
while(c.moveToNext()) {
toReturn.add(c.getString(c.getColumnIndex("name")));
}
c.close();
}
catch(SQLiteException e) {
e.printStackTrace();
}
return toReturn;
}

Get data Sorted by descending size according units of measurement in SQLite

I have a table with these column
|Name|Quantity|Unit
And I want to get the data sorted by descending size according units of measurement
for example:
|Bread|1.2|Kg
|Pasta|600.21|g
|Flour|200.18|g
|Salt|70.12|mg
|Pepper|60.3|mg
|Venom|700.15|mcg
1.2 is minor than 600.21 but the unit is Kg so in the order priority is before according scale Kg > g > mg >mcg etc.
(assuming that the table doesn't contains 6000g because the notation is 6Kg)
This code clearly doesn't works
public Cursor allDataSorted() {
try {
Cursor c = mDb.rawQuery(
"SELECT * FROM myTable order by Quantity desc", null);
if (c != null) {
c.moveToNext();
}
return c;
} catch (SQLException mSQLException) {
Log.e(TAG, "allDataSorted>>" + mSQLException.toString());
throw mSQLException;
}
}
}
And all data in my table are text String so 956 for example is wrongly showed after 99, so I have no idea of How I could solve this problem and the result is totally unsorted.
Any suggestion?
NB
I cannot convert and reconvert the tables,
these are too big, and the adapter is used for too many kind of units to use only a general base unit.
EDIT
Following the suggestion of Ryan Griggs I have included mapperTb table in the same db file
Unit|Multipler
hg|100
g|1
dg|0.1
cg|0.01
mg|0.001
mcg|0.000001
And I have edit the allDataSorted() method in this way:
public Cursor allDataSorted() {
try {
Cursor c = mDb.rawQuery("SELECT *, (CAST(myTable.Quantity as FLOAT) * mapperTb.Multipler) as Quantity FROM myTable INNER JOIN mapperTb ON myTable.Unit = mapperTb.Unit ORDER BY Quantity desc", null);
if (c != null) {
c.moveToNext();
}
return c;
} catch (SQLException mSQLException) {
Log.e(TAG, "allDataSorted>>" + mSQLException.toString());
throw mSQLException;
}
}
}
but doesn't works and the Cursor results empty
I recommend that in your sorting routine, you convert all values to a base unit (i.e. Grams). Then you can properly sort. You could create another table which maps each unit to the proper multiplier (i.e Kg = 1000, g = 1) and then calculate the base unit for each entry, and sort by that value. Then you don't have to worry about things like 6000g vs 6Kg.
Example: create mapping table "unit_map" with fields 'unit' and 'multiplier'. Add all applicable units and multipliers.
So the new query becomes:
SELECT *, (CAST(myTable.Quantity as FLOAT) * unit_map.multiplier) as sort_field FROM myTable INNER JOIN unit_map ON myTable.Unit = unit_map.unit ORDER BY sort_field

Database insert not working on Android

Hi I'm doing an Android application and I have a database. I'm able to do queries but the inserts don't seem to be working. I have a table named profile with the fields "id", "name" and "original".
This is the method:
public void addProfile(String name)
{
myDataBase.rawQuery("INSERT INTO profile(name, original) values('"+name+"', '0')", null);
}
And what I'm doing:
DataBaseHelper myDbHelper = new DataBaseHelper(activity);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
for(Profile p : profiles){
myDbHelper.addProfile(p.getName());
System.out.println("Commiting profile "+ p.getName());
In LogCat it correctly appears "Commiting profile test".
I'm opening the database with:
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
I've searched everywhere for the erro and I can't seem to find it. Is it because I have an "id" instead of "_id" on the table? Wouldn't that only affect the SELECTs? In my Selects I use select id as _id but in insert I don't know how to do it.
It is not allowed to use rawQuery to insert data. You should use execSQL

Categories

Resources