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: