SQLite Today_date - date - android

Good day!
I've got a problem of counting the date. I have one date (the number of a day in the year) and today's date. I need to get the result of subtraction (Today_date - COLUMN_DATE = COLUMN_LAST)
Here's my code. Obviously, it contains some mistakes.
Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
Cursor cursor = mDB.query(DB_TABLE, new String[] {COLUMN_DATE} , null, null, null, null, null);
while(cursor.moveToNext())
{
ContentValues cv = new ContentValues();
cv.put(COLUMN_LAST, localCalendar.get(Calendar.DAY_OF_YEAR) - cursor.getInt( cursor.getColumnIndex(COLUMN_DATE) ));
mDB.update(DB_TABLE, cv, COLUMN_ID + " = " + cursor.getPosition(), null);
}
What should I do this thing to work? Thank's for your answers.

You're assuming that cursor position is equal to row id, it may not be true. When you're updating row you should pass column_id not cursor position.
Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
Cursor cursor = mDB.query(DB_TABLE, new String[] {COLUMN_ID, COLUMN_DATE} , null, null, null, null, null);
while(cursor.moveToNext())
{
ContentValues cv = new ContentValues();
int columnId = cursor.getInt(0); // cause COLUMN_ID is 0th in projection above
cv.put(COLUMN_LAST, localCalendar.get(Calendar.DAY_OF_YEAR) - cursor.getInt(1));
mDB.update(DB_TABLE, cv, COLUMN_ID + " = ?" + id, new String[] {columnId});
}
// always close cursor
cursor.close(); // you can use try-finally block

Related

how to fetch sqlite data based on columns

I saved data on sqlite db with year and month, now want to retrieve data based on year and month but object is always null.
Here is my code
public List<AddIncomeModel> fetch(String year,String month) {
database = this.getReadableDatabase();
// Cursor cursor = database.query(TABLE_NAME, null, null, null, null, null, null);
Cursor cursor=database.rawQuery("SELECT * FROM " + TABLE_NAME+" WHERE " +YEAR +" = "+year+" AND " + MONTH + " = "+month,null);
List<AddIncomeModel> contacts = new ArrayList<AddIncomeModel>();
AddIncomeModel contactModel;
if (cursor.getCount() > 0) {
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToNext();
contactModel = new AddIncomeModel();
contactModel.setId(cursor.getInt(0));
contactModel.setIncome_source(cursor.getString(1));
contactModel.setDescription(cursor.getString(2));
contactModel.setAmount(cursor.getString(3));
contacts.add(contactModel);
}
}
cursor.close();
database.close();
return contacts;
}
Please tell me where I am going wrong.
Thanks
In SQLiteDatabase.query() the selection comes in two parts. The where clause (a String) and the whereArgs (an array of String).
To add more than one condition to the where clause you can use AND or OR, just like && or || in Java.
A question mark in the where clause is bound to one of the Strings in the whereArgs array.
Try Like This
cursor = db.query(TABLE_NAME, new String[] { ID, YEAR , MONTH},
YEAR + " LIKE ? AND " + MONTH+ " LIKE ?",
new String[] {"%" + dan + "%", "%" + vrijeme + "%"},
null, null, null, null);

Get specific data from sqlitedatabase using row id

I have two columns in a database, id and city. How can I get all the city data and put it in a string when the row id is less than 3. I am having difficulty in writing a query to get data when the row id is less than 3. Right now my method gets all the data from the database. Thanks.
String[] columns = new String[]{KEY_ROWID, KEY_CITY};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result =" ";
int iRow = c.getColumnIndex(KEY_ROWID);
int iCity = c.getColumnIndex(KEY_CITY);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iCity) + "\n";
}
return result;
String[] columns = new String[]{KEY_ROWID, KEY_CITY};
// "note "rowid" is used in fts tables and "id" in normal tables.
// I'm assuming your constant KEY_ROWID chose the correct one.
String where = KEY_ROWID + " <= " + 3;
Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, where, null, null, null, null);
if(!cursor.moveToFirst()){
Log.e("System.out", "cursor is empty");
}else{
int ix_city = cursor.getColumnIndexOrThrow(KEY_CITY);
StringBuilder sb = new StringBuilder();
do{
String city = cursor.getString(ix_city);
Log.i("System.out", "city name " + city);
if(TextUtils.isEmpty(city))
continue;
sb.append(city).append("\n");
}while(cursor.moveToNext());
Log.i("System.out", "the entire list " + sb.toString());
}

how to get a specific data by using a string argument?

i am using this method to get the price of all item that has a category name value bt it is not showing anything...
public long getcostmain(String xyz)throws SQLException {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID, KEY_CATEGORY,KEY_DATE,KEY_PRICE,KEY_DETAILS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_DATE + "=" + xyz, null, null, null, null);
long cost = 0;
for(c.moveToFirst(); ! c.isAfterLast(); c.moveToNext()){
cost = cost + c.getLong(3);
}
return cost;
}
In your code, when you query data from your database, you need to change your code to following:
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_DATE + "='" + xyz +"'", null, null, null, null);
You need to put ' mark around your xyz string.

Android: adding a birthday event to an android contact programmatically

I am trying to birthday information to a contact. I use lookupkey to identify my contacts (as it is safer than just relying on contactId). In order to be able to insert the Event into the database i need a raw_contact_id ... so i'm trying to get this id:
String where = ContactsContract.Data.LOOKUP_KEY + " = ? AND "
+ ContactsContract.Data.MIMETYPE + " = ?";
String[] params = new String[] { lookupKey,
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE };
Cursor cursor = contentResolver.query(
ContactsContract.Data.CONTENT_URI, null, where, params, null);
if (cursor.moveToFirst()) {
birthdayRow = cursor.getInt(idIdx);
long rawContactId = cursor.getLong(cursor
.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
}
The problem is that if there is not birthday event set for a contact then this cursor i receive is empty ... and i don't know how to insert this event without a raw_contact_id. In order to insert the event i do the folowing:
values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
values.put(ContactsContract.Data.MIMETYPE, Event.CONTENT_ITEM_TYPE);
values.put(ContactsContract.CommonDataKinds.Event.START_DATE,
birthdayStartDate);
values.put(ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY);
values.put(ContactsContract.CommonDataKinds.Event.START_DATE,
context.getString(R.string.birthday_label));
if (birthdayRow >= 0) {
int result = contentResolver.update(
ContactsContract.Data.CONTENT_URI, values,
ContactsContract.Data._ID + " = " + birthdayRow, null);
Log.i("ContactList", "update result: " + result);
} else {
Uri result = contentResolver.insert(
ContactsContract.Data.CONTENT_URI, values);
Log.i("ContactList", "update result: " + result);
}
So please advice what shall i do, is there any way to add this event to the ContactData whitout a raw_contact id? Also i find strange the fact that for other ContactData like nickname i am doing the same thing and i dont get an empty cursor for the params
String[] params = new String[] { String.valueOf(lookupKey),
ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE };
even if the contact has no nickname.
Use this to get the raw contact id before performing the insert.
long rawContactId = -1;
String[] projection = new String[]{ContactsContract.CommonDataKinds.Event.RAW_CONTACT_ID};
String selection = ContactsContract.CommonDataKinds.Event.CONTACT_ID + "=?";
String[] selectionArgs = new String[]{
String.valueOf(bdayContact.getId()) };
Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, selection, selectionArgs, null);
try {
if (c.moveToFirst()) {
rawContactId = c.getLong(0);
}
} finally {
c.close();
}

How do I order my SQLITE database in descending order, for an android app?

What is the most efficient method of showing my data in descending order?
public String getRank() {
String[] rank = new String[]{ KEY_ROWID };
Cursor c = scoreDb.query(DATABASE_TABLE, rank, null, null, null, null, null); //reading information from db.
String rankResult = "";
int iRow = c.getColumnIndex(KEY_ROWID); //Cursor looking for column setting equal to these ints.
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
//Move to first row - where cursor starts and moves to next row as long it is not after last row.
rankResult = rankResult + c.getString(iRow) + "\n";
//Returning value of row that it is currently on.
}
return rankResult; //returning result
}
public String getName() {
String[] name = new String[]{ KEY_NAME };
Cursor c = scoreDb.query(DATABASE_TABLE, name, null, null, null, null, null); //reading information from db.
String nameResult = "";
int iRow1 = c.getColumnIndex(KEY_NAME); //Cursor looking for column setting equal to these ints.
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
//Move to first row - where cursor starts and moves to next row as long it is not after last row.
nameResult = nameResult + c.getString(iRow1) + "\n";
//Returning value of row that it is currently on.
}
return nameResult; //returning result
}
public String getScore() {
String[] score = new String[]{ KEY_SCORE };
Cursor c = scoreDb.query(DATABASE_TABLE, score, null, null, null,null, null); //reading information from db.
String scoreResult = "";
int iRow2 = c.getColumnIndex(KEY_SCORE); //Cursor looking for column setting equal to these ints.
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
//Move to first row - where cursor starts and moves to next row as long it is not after last row.
scoreResult = scoreResult + c.getString(iRow2) + "\n";
//Returning value of row that it is currently on.
}
return scoreResult; //returning result
}
Query has two syntax, the syntax you are using, last column represents orderBy, you just need to specify on what column you want to do orderBy +"ASC" (or) orderBy +"DESC"
Cursor c = scoreDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC");
Refer this documentation to understand more about query() method.
return database.rawQuery("SELECT * FROM " + DbHandler.TABLE_ORDER_DETAIL +
" ORDER BY "+DbHandler.KEY_ORDER_CREATED_AT + " DESC"
, new String[] {});
Cursor c = scoreDb.query(Table_Name, score, null, null, null, null, Column+" DESC");
Try this
According to docs:
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);
and your ORDER BY param means:
How to order the rows, formatted as an SQL ORDER BY clause
(excluding the ORDER BY itself). Passing null will use the default
sort order, which may be unordered.
So, your query will be:
Cursor cursor = db.query(TABLE_NAME, null, null,
null, null, null, KEY_ITEM + " DESC", null);
public List getExpensesList(){
SQLiteDatabase db = this.getWritableDatabase();
List<String> expenses_list = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_NAME ;
Cursor cursor = db.rawQuery(selectQuery, null);
try{
if (cursor.moveToLast()) {
do{
String info = cursor.getString(cursor.getColumnIndex(KEY_DESCRIPTION));
expenses_list.add(info);
}while (cursor.moveToPrevious());
}
}finally{
cursor.close();
}
return expenses_list;
}
This is my way of reading the record from database for list view in descending order. Move the cursor to last and move to previous record after each record is fetched. Hope this helps~
Cursor c = myDB.rawQuery("SELECT distinct p_name,p_price FROM products order by Id desc",new String[]{});
this works for me!!!
you can do it with this
Cursor cursor = database.query(
TABLE_NAME,
YOUR_COLUMNS, null, null, null, null, COLUMN_INTEREST+" DESC");
SQLite ORDER BY clause is used to sort the data in an ascending or descending order, based on one or more columns.
Cursor c = scoreDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC");
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
TABLE_NAME,
rank,
null,
null,
null,
null,
COLUMN + " DESC",
null);
We have one more option to do order by
public Cursor getlistbyrank(String rank) {
try {
//This can be used
return db.`query("tablename", null, null, null, null, null, rank +"DESC",null );
OR
return db.rawQuery("SELECT * FROM table order by rank", null);
} catch (SQLException sqle) {
Log.e("Exception on query:-", "" + sqle.getMessage());
return null;
}
}
You can use this two method for order
This a terrible thing! It costs my a few hours!
this is my table rows :
private String USER_ID = "user_id";
private String REMEMBER_UN = "remember_un";
private String REMEMBER_PWD = "remember_pwd";
private String HEAD_URL = "head_url";
private String USER_NAME = "user_name";
private String USER_PPU = "user_ppu";
private String CURRENT_TIME = "current_time";
Cursor c = db.rawQuery("SELECT * FROM " + TABLE +" ORDER BY " + CURRENT_TIME + " DESC",null);
Every time when I update the table , I will update the CURRENT_TIME for sort.
But I found that it is not work.The result is not sorted what I want.
Finally, I found that, the column "current_time" is the default row of sqlite.
The solution is, rename the column "cur_time" instead of "current_time".
About efficient method. You can use CursorLoader. For example I included my action. And you must implement ContentProvider for your data base. https://developer.android.com/reference/android/content/ContentProvider.html
If you implement this, you will call you data base very efficient.
public class LoadEntitiesActionImp implements LoaderManager.LoaderCallbacks<Cursor> {
public interface OnLoadEntities {
void onSuccessLoadEntities(List<Entities> entitiesList);
}
private OnLoadEntities onLoadEntities;
private final Context context;
private final LoaderManager loaderManager;
public LoadEntitiesActionImp(Context context, LoaderManager loaderManager) {
this.context = context;
this.loaderManager = loaderManager;
}
public void setCallback(OnLoadEntities onLoadEntities) {
this.onLoadEntities = onLoadEntities;
}
public void loadEntities() {
loaderManager.initLoader(LOADER_ID, null, this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(context, YOUR_URI, null, YOUR_SELECTION, YOUR_ARGUMENTS_FOR_SELECTION, YOUR_SORT_ORDER);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}

Categories

Resources