Android content provider, update with SUM - android

How can I use this query with Android content provider?
update tblTot set vMax = vMax + 15 where _id = 1;
Where vMax is a column of tblTot table.
I have tried to do this
Uri totUri = Uri.parse(DbProvider.TOT_CONTENT_URI + "/1");
ContentValues valoriTotali = new ContentValues();
valoriTotali.put(DbHelper.TBTOT_VMAX, DbHelper.TBTOT_VMAX + " + " + newVMax);
int rcdTot = resolver.update(totUri, valoriTotali, null, null);
But it does not work because this update set the value as string ("db column name + value") and not as integer inside my db row.
Thank you in advance

Its better to expose new URI for it(or pass additional argument in URI) and base on that take appropriate action in ContentProvider's update(), something like this -
case CASE_URI_INCREMENT_LIKE:
String sqlStatement = "UPDATE " + Table.TABLE_NAME + " SET " + Table.VALUE + " = " + Table.VALUE + " + 1 WHERE " + Table.ID + "=?";
mSQLiteDatabase.execSQL(sqlStatement, selectionArgs);
break;

You can get the value of vMax and cast it as Integer
// CAST((CAST(vMax as INTEGER) +15) AS text)
EDIT: How to use the above line
db = this.getReadableDatabase();
String selectQuery = "select vMax from tblTot "
+ " where _id = 1";
Cursor cursor = db.rawQuery(selectQuery, null);
int vMax = 0;
if (cursor.moveToFirst()) {
Log.i(Tag, "vMax: "+cursor.getString(0) );
vMax= Integer.parseInt(cursor.getString(0));
}
ContentValues values = new ContentValues();
values.put("vMax", Integer.toString(vMax+15));
db.update("tblTot ", values, _id + " = ?", new String[] { String.valueOf(_id ) });
db.Close();

Related

Android retrieve result after gives two parameter date and id

I have two parameter (tenant_id and dateIn). with my query below I always get -1 as result. I don't know where is the issue in query statement.
Kindly note that the date format in data base is dd/MM/yyyy
public final static String ID = "id";
public final static String TENANT_ID = "tenant_id";
public final static String DEBT_CURRENT_VALUE = "debt_current_value";
public final static String DEBT_SUM = "debt_sum_value";
public final static String DEBT_DATE = "debt_date";
public long getTenantDateDebtByIdandDate(long id, String dateIn) {
long idout = -1;
String[] columns = {ID, TENANT_ID, DEBT_CURRENT_VALUE,DEBT_SUM, DEBT_DATE };
String selection = "TENANT_ID = " + id + " AND " + "DEBT_DATE < " + "date("+ dateIn+")";
Cursor cursor = mDatabase.query(TABLE_TENANT_DEBT, columns, selection, null, null, null, null);
if (cursor.moveToNext()) {
idout = cursor.getLong(cursor.getColumnIndex(DEBT_DATE));
}
cursor.close();
return idout;
}
I think there is a mistake with the column names at least
Isn't this: String selection = "TENANT_ID = " + id + " AND " + "DEBT_DATE < " + "date("+ dateIn+")"; checking columns named TENANT_ID and DEBT_DATE, when actually you want to check columns "tenant_id" and "debt_date".
So I think the selection should be instead: String selection = TENANT_ID + " = " + id + " AND " + DEBT_DATE + " < " + "date("+ dateIn+")";
I'm not so familiar with dates in sqlite, but if the date function is not working in this case, maybe you should look into the strftime function of sqlite
Also, I would recommend using the where arguments. So basically instead of saying TENANT_ID + " = " + id, you would say TENANT_ID + " = ?", and change the DEBT_DATE in similar way. Then you would give the query function one more array having the values that are then used in the places of the questionmarks in the order they are in the array. The query is safer that way, see more details why to use the where args and a complete example in this Stackoverflow thread in case you are interested.
Finally with the feedback of Peter and some resaerch I found the solution
public String getTenantDateDebtByIdandDate(long id, String dateIn) {
String idout = "";
String[] columns = {TENANT_ID, DEBT_DATE };
String selection = TENANT_ID + " = '" + id + "' AND " + DEBT_DATE + " < " + "'"+ dateIn + "'";
Cursor cursor = mDatabase.query(TABLE_TENANT_DEBT, columns, selection, null, null, null, null);
while (cursor.moveToNext()) {
idout = cursor.getString(cursor.getColumnIndex(DEBT_DATE));
}
cursor.close();
return idout;
}

getting values from column in database

I am getting values from the column "threadid" in the database.Problem is that it gets the value from the previous record/row. and when I try to get the first record my app crashes,, How to tackle this problem and whats the issue?
long id;
long threadid = datasource.getthreadid(id);
Toast.makeText(getActivity(), String.valueOf(threadid), Toast.LENGTH_SHORT).show();
public long getthreadid(long id)
{
String ide=String.valueOf(id);
String queryz = "SELECT " + MySQLiteHelper.COLUMN_THREADID
+ " FROM " + MySQLiteHelper.TABLE_NAME
+ " WHERE " + MySQLiteHelper.COLUMN_ID + "=" + ide;
Cursor cursor = database.rawQuery(queryz, null);
cursor.moveToFirst();
// cursor.moveToPosition(Integer.parseInt(String.valueOf(id)));
long threadid= cursor.getLong(cursor.getColumnIndex("threadid"));
cursor.close();
return threadid;
}
If you are only expecting one row. Then it might be useful to do something like this.
long threadid;
if (cursor.moveToFirst())
{
threadid = cursor.getLong(cursor.getColumnIndex("threadid"));
}
else
{
// ah oh, we do not have this id!
// do something here if you need to
}
Also, if you are going to use strings, I recommend you bind the parameters. I know you had a long beforehand, but for strings you can do this.
String queryz = "SELECT " + MySQLiteHelper.COLUMN_THREADID
+ " FROM " + MySQLiteHelper.TABLE_NAME
+ " WHERE " + MySQLiteHelper.COLUMN_ID + " = ?";
Cursor cursor = database.rawQuery(queryz, new String[]{ide});
To get all the records, you first need to move to the first one, then you iterate through the rest.
if (cursor.moveToFirst()) {
do {
// get row values
} while (cursor.moveToNext());
}
cursor.close();

Query on ContactsContract.data for RAW_CONTACT_ID returns 0 rows

I'm trying to get get data from from DATA table for specific RAW_CONTACT_IDs, but all I get are empty query outputs.
The logic seems quite simple but I just can't figure out why this happens. Googled it but couldn't find anything similar.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
String where = RawContacts.DELETED + "<> 0 and " + RawContacts.ACCOUNT_TYPE + "=?";
Cursor c = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI,
new String[] {RawContacts._ID,
RawContacts.ACCOUNT_NAME,
RawContacts.ACCOUNT_TYPE,
RawContacts.DISPLAY_NAME_PRIMARY
},
where,
new String[] {"Local Phone Account"},
null);
int i = 0;
if (c.getCount() > 0) {
while (c.moveToNext() && i < 10) {
i = i + 1;
// get the id from RawContacts cursor
String rawID = c.getString(c.getColumnIndex(RawContacts._ID));
tv.append("searching RawID " + rawID + "\n" +
"account name: " + c.getString((c.getColumnIndex(RawContacts.ACCOUNT_NAME))) + "\n" +
"account type: " + c.getString(c.getColumnIndex(RawContacts.ACCOUNT_TYPE)) + "\n" +
"display name: " + c.getString(c.getColumnIndex(RawContacts.DISPLAY_NAME_PRIMARY)) + "\n"
);
// create a cursor from Data table for the RawContacts ID
Cursor cur = getContentResolver().query(Data.CONTENT_URI,
new String[] {Data._ID},
Data.RAW_CONTACT_ID + "=?",
new String[] {String.valueOf(rawID)},
null
);
tv.append("found " + cur.getCount() + " matches for id " + String.valueOf(rawID) + "\n");
cur.close();
}
}
setContentView(tv);
}

Method query db to return results [duplicate]

This question already has an answer here:
Method to excute query and return results
(1 answer)
Closed 9 years ago.
App won't run. This occurs recurrently:
04-05 21:29:09.570: E/AndroidRuntime(1069): Caused by: java.lang.IllegalArgumentException:
Cannot bind argument at index 1 because the index is out of range.
The statement has 0 parameters.
Main - Calling method
Cursor wow = db.trying("Gold");
text = (TextView) findViewById(R.id.textView13);
String quantity = wow.getString(0); //
text.setText(quantity);
DB Handler - Method
public Cursor trying(String vg){
String q = "SELECT quantity FROM " + TABLE_CONTACTS + " WHERE name=" + "'" + vg +"'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(q, new String[] {vg});
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
The problem is
String q = "SELECT quantity FROM " + TABLE_CONTACTS + " WHERE name=" + "'" + vg +"'";
In your query you had already specify the parameter for where condition .After that you are again passing it to query
Cursor cursor = db.rawQuery(q, new String[] {vg});
This makes the confusion .So try to change your query
String q = "SELECT quantity FROM " + TABLE_CONTACTS + " WHERE name = ?";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(q, new String[] {vg});
OR you go for another approach
String q = "SELECT quantity FROM " + TABLE_CONTACTS + " WHERE name=" + "'" + vg +"'";
Cursor cursor = db.rawQuery(q, null);
if(cursor != null && cursor.getCount()>0){
cursor.moveToFirst();
//do your action
//Fetch your data
}
else {
Toast.makeText(getBaseContext(), "No records yet!", Toast.LENGTH_SHORT).show();
return;
}
Refer

retrieve all data from all columns from an inner join result

How do I retrieve the data on all columns from an INNER JOIN result? I use this query:
SELECT course.course_title,
course.course_body,
course. course_image,
instructor.instructor_title,
instructor.instructor_body,
instructor.instructor_photo
FROM course
INNER JOIN instructor
ON course.course_instructor1=instructor.instructor_nid
WHERE course_id=4
and this is the equivalent variable COURSE_OUTLINE that i'll be using to execute
String COURSE_OUTLINE =
"SELECT " + Qualified.COURSE_TITLE + ", "
+ Qualified.COURSE_BODY + ", "
+ Qualified.COURSE_IMAGE + ", "
+ Qualified.INSTRUCTOR_TITLE + ", "
+ Qualified.INSTRUCTOR_BODY + ", "
+ Qualified.INSTRUCTOR_IMAGE + ", " +
"FROM " + Tables.COURSE_JOIN_INSTRUCTOR +
"WHERE " + CourseColumns.COURSE_ID +
"=?";
In my code,
Cursor cur = mSqliteDb.rawQuery(SubQuery.COURSE_OUTLINE, new String[] {position});
This gives 1 record. I know how to retrieve data from a specific column but I'm not sure how to retrieve it from all columns.
this is the code I use to retrieve data from a specific column
public String getCourseImage(int position) {
String image = "";
String pos = Integer.toString(position);
Cursor cur = mSqliteDb.rawQuery(SelectQuery.ALL_COURSES, new String[] {pos});
if (cur != null) {
if (cur.moveToFirst()) {
do {
image = cur.getString(cur.getColumnIndex(CourseColumns.COURSE_IMAGE));
} while (cur.moveToNext());
}
cur.close();
}
return image;
}
My intention is mapping each data in a column to a View
getColumnNames gives you an array with all columns... if that's what you're asking. It's kind of hard to tell.

Categories

Resources