sqlite how to pass in 2 arguments to a query - android

I have the following query that returns a Cursor based on how many records have an awayreasontypeid of '2'. It works fine.
How can i run the same query but return a Cursor of all the records that have an awayreasontypeid of either '2' or '0'?
// table AwayReason column names
public static final String C_AWAYREASON_ID_INDEX = BaseColumns._ID;
public static final String C_AWAYREASON_ID = "awayreasonid";
public static final String C_AWAYREASON_NAME = "awayreasonname";
public static final String C_AWAYREASON_TYPE_ID = "awayreasontypeid";
public Cursor queryCarerAwayReasons(){
SQLiteDatabase db = dbhelper.getReadableDatabase();
String[] carer = { "2" };
Cursor c = db.rawQuery("SELECT * FROM " + DBHelper.TABLEAWAYREASON + " WHERE awayreasontypeid = ?", carer);
return c;
}
Thanks in advance
Matt

You can use IN:
String[] carer = { "2", "0" };
Cursor c = db.rawQuery("SELECT * FROM " + DBHelper.TABLEAWAYREASON + " WHERE awayreasontypeid IN (?,?)", carer);

Related

How to retrieve the sum of the selected category from SQLite category_column?

My table contains these columns:
1 - id integer
2 - car_model text`
3 - car_value int
4 - car_color
Code:
public static final String CREATE_query = "create table car" + "(id integer primary key autoincrement,carmodel text not null,carvalue integer not null,carcolor text not null)";
The problem I face is how to get the total value of selected car model in a Spinner and display the value using a TextView
I use this to query the database
public float getCarModelValue(SQLiteDatabase db, String selectedmodel) {
float amount = 0;
db = this.getReadableDatabase();
String query = "select sum(carvalue) from car where carmodel = '"+ selectedmodel;
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
amount = cursor.getInt(0);
}
while (cursor.moveToNext());
}
db.close();
return amount;
}
but it fails.
Also I tried the following code
public float getAccountValue(SQLiteDatabase db, String selected) {
float amount = 0;
db = this.getReadableDatabase();
String query = "select sum(carvalue) from car group by carmodel where carmodel = " + selected;
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
amount = cursor.getInt(0);
}
while (cursor.moveToNext());
}
db.close();
return amount;
}
And use this code to display value
dbhelper = new DbHelper(getApplicationContext());
sqlitedatabase = dbhelper.getReadableDatabase();
try {
valueofcar = dbhelper.getCarModelValue(sqlitedatabase, model_selected);
total_value.setText("" + valueofcar);
} catch (Exception e) {
e.printStackTrace();
}
any help appreciated
You need to close the string delimiter:
Wrong:
String query = "select sum(carvalue) from car where carmodel = '"+ selectedmodel;
Correct:
String query = "select sum(carvalue) from car where carmodel = '"+ selectedmodel + "'";
Similarily, in the other method, the correct query is
String query = "select sum(carvalue) from car group by carmodel where carmodel = '" + selected + "'";
In both methods, you don't need this: group by carmodel, nor the do ... while loop - since you are only retrieving a single value.
One way of doing this is to store result in a new column and read from it
and get the result
public float getCarModelValue(SQLiteDatabase db, String selectedmodel) {
float amount = 0;
db = this.getReadableDatabase();
String query = "select sum(carvalue) from car as totalcar where carmodel = '"+ selectedmodel + "'";
Cursor cursor = db.rawQuery(query, null);
String query = "select totalcar from car";
Cursor cursor = db.rawQuery(query, null);
cursor=cursor.moveToFirst();
amount=cursor.getInt(getColumnIndex(totalcar));
db.close();
return amount;
}

RxJava: Reduce or Combine or Merge

What I want to do is query the Android ContentProvider for Contacts.
The Cursor returns contains multiple duplicates for a contact where they may have more than one number registered against their contact_id)
So far, I have queried the DB, and am iterating through the Cursor rows.
I map() these rows and converting them into a ValueObjects
Next I want to go through all the list of VO’s and merge the ones that have the same contact_id (the VO would store an array of label & numbers)
But, I am stuck, I can not figure out how to perform the last part, how can I loop through the list of ValueObjects, merging the duplicates into one and then disposing the unneeded ones.
This is a sample of the Cursor returned by the ContentProvider:
86 {
_id=5190
contact_id=2167
display_name=John Doe
data1=+44 20 7123 7890
data2=3
data3=null
photo_thumb_uri=content://com.android.contacts/contacts/2167/photo
lookup=731i7g4b3e9879f40515
}
87 {
_id=5191
contact_id=2167
display_name=John Doe
data1=+44 7967 123 789
data2=2
data3=null
photo_thumb_uri=content://com.android.contacts/contacts/2167/photo
lookup=731i7g4b3e9879f40515
}
88 {
_id=5192
contact_id=2167
display_name=John Doe
data1=+44 208 123 7890
data2=1
data3=null
photo_thumb_uri=content://com.android.contacts/contacts/2167/photo
lookup=731i7g4b3e9879f40515
}
Sample of the function
public static Observable<List<ContactVO>> fetchAllContacts(final Context context) {
allContactsQuery(context);
return ContentObservable.fromCursor(allContactsQuery(context))
.map(mapToContactVO())
.toList()
// I am stuck
}
private static Cursor allContactsQuery(Context context) {
final String[] CONTACTS = new String[]{
Phone._ID, //.....0
Phone.CONTACT_ID, //.....1
Contacts.DISPLAY_NAME_PRIMARY, //.....2
Phone.NUMBER, //.....3
Phone.TYPE, //.....4
Phone.LABEL, //.....5
Contacts.PHOTO_THUMBNAIL_URI, //.....6
Contacts.LOOKUP_KEY, //.....7
};
String SELECTION = Contacts.DISPLAY_NAME_PRIMARY +
"<>''" + " AND " + Contacts.IN_VISIBLE_GROUP + "=1" +
" AND " + Contacts.HAS_PHONE_NUMBER + "=1";
final String[] SELECTION_ARGS = null;
final String SORT_ORDER = Contacts.SORT_KEY_PRIMARY;
Cursor cursor = context.getContentResolver().query(
Phone.CONTENT_URI,
CONTACTS,
SELECTION,
SELECTION_ARGS,
SORT_ORDER);
return cursor;
}
#NonNull
private static Func1<Cursor, ContactVO> mapToContactVO() {
return cursor -> {
int len = cursor.getCount();
final ContactVO contact = new ContactVO();
contact.contactId = cursor.getString(CONTACT_ID);
contact.displayName = cursor.getString(DISPLAY_NAME);
contact.photoThumbnailUri = cursor.getString(PHOTO_THUMBNAIL_URI);
contact.lookUp = cursor.getString(LOOK_UP);
contact.addData(
new Pair<String, String>(
cursor.getString(PHONE_TYPE),
cursor.getString(PHONE_NUMBER)
)
);
return contact;
};
}
public final static int CONTACT_ID = 1;
public final static int DISPLAY_NAME = 2;
public final static int PHONE_NUMBER = 3;
public final static int PHONE_TYPE = 4;
public final static int PHONE_LABEL = 5;
public final static int PHOTO_THUMBNAIL_URI = 6;
public final static int LOOK_UP = 7;
Use groupBy to get the records with the same contactId together then flatMap and reduce to merge the records
ContentObservable.fromCursor(allContactsQuery(context))
.map(mapToContactVO())
.groupBy(contact -> contact.contactId)
.flatMap(g -> g.reduce(mergeContacts()));

Android, sqlite database finding two values in the two columns and the resulting value

im constructing an android application which use a large pre populated datbase of 910,000 records which includes 4 columns. These columns are windspeed, latitude, longitude and _id. What im trying to do is construct an sqlite query that finds a lav value in the latitude column and long (longitude) value in the longitude and the windspeed at which these two columns meet.
So the table would look something like this:
_id..............Latitude..................Longitude..............WindSpeed
1..................-9.4869363.............61.3704805..............7
2.................-7.6257292...............60.9958851..............8
3.................-9.4869363................60.9958851..............10
so if i was use the above table the lat value i would want to find would -9.4869363 and the long value would be 60.9958851 and thus the windspeed would be the line that both of these meet e.g from the table line 3 and thus the wind speed is 10
To do this ive tried using this line of code but i dont think it is correct
public class MyDatabase extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "WindSpeed.sqlite";
private static final int DATABASE_VERSION = 1;
private static final String LAT_VAL = "Latitude";
private static final String LONG_VAL = "Longitude";
private static final String WIND_SPEED= "Speed10m";
private static final String ROW_ID= " _id";
double lat= 3.52;
double Long = 65.42;
public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public Cursor getWindSpeed2(){
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {WIND_SPEED,};
String sqlTables = "noabl_10m_out";
String whereClause = "LAT_VAL = ? AND LONG_VAL = ?";
String[] whereArgs = new String[] {
"lat",
"Long"
};
qb.setTables(sqlTables);
Cursor d = qb.query(db, sqlSelect, whereClause, whereArgs,
null, null, null);
d.moveToFirst();
return d;
}
}
Is this wrong, ive searched far and wind and i just keep getting confused tbh so any help would be massive thanks
It seems that you are not using the column names but instead the variable names.
Try to change the whereClause to:
String whereClause = LAT_VAL + "=? AND " + LONG_VAL + "=?";
Also the whereArgs to:
String[] whereArgs = new String[] {
String.valueOf(lat),
String.valueOf(Long)
};
There are many mistakes in your code and I'm starting to think that you have no idea what you're doing.. Unnecessary comma here:
String [] sqlSelect = {WIND_SPEED,};
Change
String whereClause = "LAT_VAL = ? AND LONG_VAL = ?";
to
String whereClause = LAT_VAL+" = ? AND "+LONG_VAL+" = ?";
and
String[] whereArgs = new String[]
{
"-9.4869363",
"60.9958851"
};
to
String[] whereArgs = new String[]
{
"lat",
"Long"
};
LAT_VAL and LONG_VAL are variable that you use to store the columns name so they should be outside the quotes and whereArgs needs to contain the values that you want to compare

Get data from database Android

I have a page which can retrieve user data from database
but after whole day of trying, I am only able to get the table column name but not the value inside.
this is my code to create database
public static final String LASTLOGIN = "lastuser";
public static final String USER_ID = "suser_id";
public static final String USER_NAME = "suser_name";
public static final String USER_PASSWORD = "spassword";
public static final String PRIME_ID = "id";
private static final String TABLE_USER =
"create table "+ LASTLOGIN+" ("
+PRIME_ID+" integer primary key autoincrement, "
+ USER_ID + " text, "
+ USER_NAME +" text, "
+USER_PASSWORD+" text); ";
and here is the function implemented to get user data
public Cursor getuser()
{
String[] columns = new String[]{PRIME_ID, USER_NAME, USER_PASSWORD};
Cursor cursor = sqLiteDatabase.query(
LASTLOGIN, columns, null, null, null, null, PRIME_ID +" DESC");
Log.d("TAG", columns[1]);
return cursor;
}
and here is my code to display the result
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.getuser();
String[] resultvalue = new String{
SQLiteAdapter.PRIME_ID,SQLiteAdapter.USER_NAME, SQLiteAdapter.USER_PASSWORD};
Toast.makeText(this, resultvalue[0]+resultvalue[1], Toast.LENGTH_LONG).show();
and the toast result only show the column name but not the value inside, is there any mistake i made? and I want to set limit to 1, but where to set it?
Thanks for helping me
the way you try reading the values is completly wrong.
you create an array
String[] resultvalue = new String[]{
SQLiteAdapter.PRIME_ID,
SQLiteAdapter.USER_NAME,
SQLiteAdapter.USER_PASSWORD};
after that you read the values 0 and 1 from this array.
Your toast works absolutly correctly becouse inside this array you define the column names!
If you want to show the values from your query do it this way:
while(cursor.moveToNext()){
Integer str1 = str 1 + cursor.getInteger(1);
String str2 =str2 + cursor.getString(2);
Toast.makeText(this, str1 + str2, Toast.LENGTH_LONG).show();
}
or a better way receiving the correct index:
cursor.getInteger( cursor.getColumnIndex(SQLiteAdapter.PRIME_ID) );
cursor.getString( cursor.getColumnIndex(SQLiteAdapter.USER_NAME) );
Please note when retrieving data from a database, you store it in a Cursor in the memory and hence can only access it using that particular Cursor object, which you have used in the following line of code.
Cursor cursor = mySQLiteAdapter.getuser();
The Following line retrieves the column names and not the values.
String[] resultvalue = new String[]{SQLiteAdapter.PRIME_ID,SQLiteAdapter.USER_NAME, SQLiteAdapter.USER_PASSWORD};
So the following is doing what you have asked it to do, retrieve column names not values
Toast.makeText(this, resultvalue[0]+resultvalue[1], Toast.LENGTH_LONG).show();
You need something like following:
if(cursor.getCount() != 0)
{
while(cursor.moveToNext())
{
resultvalue [0] = csr.getString(0);
resultvalue [1] = csr.getString(1);
//....
}
}
Hope this helps
here is my solution:
final String TABLE_NAME = "table_name";
String selectQuery = "SELECT Column FROM "+TABLE_NAME+" WHERE column='"+some_value+"'";
SQLiteDatabase db = this.openDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] data = new String[cursor.getCount()];;
int i = 0;
if (cursor.moveToFirst()) {
do {
i=Integer.parseInt(cursor.getString(cursor.getColumnIndex("value")));
} while (cursor.moveToNext());
}
cursor.close();

Failing to query the max number in database

I am trying to find the max number in a column of one of the tables in my database.
I thought I had this one sorted (I posted similar question previously), however after some testing I have realised my code isn't working as I thought.
The database consists of a table with the following columns:
_id, inspection_link, area_number, area_reference
I have created the following code in my database helper class:
public static final String AREAS_TABLE = "areas";
public static final String AREA_ID = "_id";
public static final String AREA_NUMBER = "area_number";
public static final String AREA_REF = "area_reference";
public static final String AREA_LINK = "area_link";
public static final String INSPECTION_LINK = "inspection_link";
public Cursor selectMaxAreaNumber (long inspectionId) {
String inspectionIdString = String.valueOf(inspectionId);
String[] tableColumns = new String[] {
AREA_NUMBER,
"(SELECT max(" + AREA_NUMBER + ") FROM " + AREAS_TABLE + ") AS max"
};
String whereClause = INSPECTION_LINK + " = ?";
String[] whereArgs = new String[] {
inspectionIdString
};
Cursor c = rmDb.query(AREAS_TABLE, tableColumns, whereClause, whereArgs,
null, null, null);
if (c != null) {
c.moveToFirst();
}
c.close();
return c;
}
Then in the activity where I want to query the database I have written the following:
public class AreaEdit extends Activity {
private EditText AreaNumber;
private EditText AreaReference;
private Button saveButton;
private Button cancelButton;
protected boolean changesMade;
private AlertDialog unsavedChangesDialog;
private RMDbAdapter rmDbHelper;
private long inspectionId;
private long areaId;
private int nextAreaNumber = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rmDbHelper = new RMDbAdapter(this);
rmDbHelper.open();
Intent i = getIntent();
inspectionId = i.getLongExtra("Intent_InspectionID", -1);
areaId = i.getLongExtra("Intent_AreaID", -1);
if (areaId == -1) {
Cursor c = rmDbHelper.selectMaxAreaNumber(inspectionId);
startManagingCursor(c);
c.moveToFirst();
nextAreaNumber = c.getInt(c.getColumnIndex("max")) + 1;
}
setContentView(R.layout.edit_area);
setUpViews();
populateFields();
setTextChangedListeners();
}
private void setUpViews() {
AreaNumber =(EditText)findViewById(R.id.area_number);
AreaReference =(EditText)findViewById(R.id.area_reference);
saveButton = (Button)findViewById(R.id.area_save_button);
cancelButton = (Button)findViewById(R.id.area_cancel_button);
}
private void populateFields() {
if (areaId > 0) {
Cursor c = rmDbHelper.fetchArea(areaId);
startManagingCursor(c);
c.moveToFirst();
AreaNumber.setText(c.getString(
c.getColumnIndexOrThrow(RMDbAdapter.AREA_NUMBER)));
AreaReference.setText(c.getString(
c.getColumnIndexOrThrow(RMDbAdapter.AREA_REF)));
c.close();
}
else {
AreaNumber.setText(String.valueOf(nextAreaNumber));
}
}
However, when it returns the wrong number - it seems to pick up the maximum number from the whole table which includes data from other inspections.
I guess this may be down to the conversion between Strings and Longs etc maybe, but I have a brickwall with this?
Any help much appreciated.
You can simply try below:
String sql = "SELECT MAX(ColumnNameHere) AS MaxValue FROM myTable WHERE AnotherColumn = 'SomValue'";
Cursor c = db.rawQuery(sql, null);
c.moveToFirst();
c.getInt(c.getColumnIndex("MaxValue"));
Detailed solution to this question found here:
Solution to this detailed in the following post: SELECT statement not returning MAX number
Basically, it was an issue with the query as thought and how I used the cursor.

Categories

Resources