Getting date difference in sqlite - android

I want to get date difference between today and expiring day. This is the code I implemented. But this is not returning the right output.
public String[] getDaysList(){
Cursor cursor = db.query("COUPON", null, null, null, null, null, null );
if(cursor.getCount()<1){
cursor.close();
return null;
}
String[] array = new String[cursor.getCount()];
int i=0;
while(cursor.moveToNext()){
String days = "(julianday('now') - julianday(EXPIRED_DATE))";
array[i] = days;
i++;
}
return array;
}
This returns (julianday('now') - julianday(EXPIRED_DATE)). Please help me to get date difference as string to a array here.

The now modifier returns not only the date but also the time.
To change the timestamp to the start of the date, use the date() function:
SELECT julianday(date('now')) - julianday(EXPIRED_DATE) FROM ...
(If the expired column also contains time values, you have to use date() for it, too.)
And to actually execute this, you have to give it to the database:
public String[] getDaysList() {
String days = "julianday(date('now')) - julianday("+EXPIRED_DATE+")";
Cursor cursor = db.query("COUPON",
new String[]{ days }, // query returns one column
null, null, null, null, null);
try {
String[] array = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
array[i++] = cursor.getString(0); // read this column
}
return array.length > 0 ? array : null;
} finally {
cursor.close();
}
}
(And the number of days is not a string; consider using int[] instead.)

Hi please try these one
Cursor cursor = db.rawQuery("SELECT julianday('now') - julianday(DateCreated) FROM COUPON", null);
if (cursor.moveToFirst()) {
do {
array[i]=cursor.getString(0)
} while (cursor.moveToNext());
}

Related

Displaying data on Android after retrieving data form Android Sq lite

I am retrieving data according to dates but when running my app its shows nothing.
Here's my code :
SQL QUERY :
private Cursor getAllCurrentData()
{
String[] selectArg = new String[]{};
return db.query(Db_Contract.Db_Fieds.TABLE_NAME,
null ,
Db_Contract.Db_Fieds.DATE+ "= 2018-11-10",
selectArg,
null,
null,
Db_Contract.Db_Fieds.TIMESTAMP);
}
Displaying Data :
private void totalMoney()
{
Cursor cursor = getAllCurrentData();
double sum = 0.000d;
double getMoney;
while (cursor.moveToNext()) {
getMoney = cursor.getDouble(cursor.getColumnIndex(Db_Contract.Db_Fieds.MONEY));
sum += getMoney;
}
total.setText("Total money spent: " +sum);
}
I am new to Android Programming. Where I am doing wrong ?. Please correct me
First make sure you are connected to database and cursor returned by db.query() is not empty/null. Then Iterate over cursor like
private void totalMoney()
{
openDatabase();
Cursor cursor = getAllCurrentData();
cursor.moveToFirst();
double getMoney = 0;
while (!cursor.isAfterLast()) {
getMoney = cursor.getDouble(cursor.getColumnIndex(Db_Contract.Db_Fieds.MONEY));
sum += getMoney;
cursor.moveToNext();
}
total.setText("Total money spent: " + sum );
closeDatabase();
}

android sqlite not update all rows one column

I am new on android development. I have a table with 9 columns who can store products , first is _id autoincrement, and the other two last insertdays and days.
In insertdays i store current date as integer after convert date to int. In the days column i store the number of days to expire a product.
I made 3 methods getDays(), getInsertdate(), expCheck().
The getDays return to expCheck the days for each row, its working
The getInsertdate return to expCheck the inserted date its working
The problem is, when i try to update my database , expCheck() called on onCreate() and onResume() methods, the values of days column for all rows(products) does not updated. With expCheck() method i try to reduce the number of days for each day who pass.
My database table in the photo the last column must reduce by one if pass one day, reduce by 2 each row if pass two days e.t.c ... Can anyone help me !!!
public int getInsertDate(int productId){
int output=0;
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projectionG = {
ProductEntry.COLUMN_PRODUCT_INSERTDATE};
Cursor cursor1 = db.query(TABLE_NAME, projectionG, " _id = ?", new String[] {String.valueOf(productId) }, null, null, null, null);
if (cursor1 !=null) {
if (cursor1.moveToFirst()) output = cursor1.getInt(7);
}
cursor1.close();
return output;
}
public int getDays(int productId){
int output=0;
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projectionD = {ProductEntry.COLUMN_PRODUCT_DAYS};
Cursor cursor = db.query(TABLE_NAME, projectionD, " _id = ?", new String[] {String.valueOf(productId) }, null, null, null, null);
if (cursor !=null) {
if (cursor.moveToFirst() ) {
output = cursor.getInt(8);
}
}
cursor.close();
return output;
}
public void expCheck(){
//Read current date
Calendar calendar = Calendar.getInstance();
SQLiteDatabase db=mDbHelper.getWritableDatabase();
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
ProductEntry.COLUMN_PRODUCT_DAYS
};
// Perform a query on the products table
Cursor cursor = db.query(
ProductEntry.TABLE_NAME, // The table to query
projection, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // Don't group the rows
null, // Don't filter by row groups
null); // The sort order
int j = toJulianDate(calendar.getTime());
Toast.makeText(this, "date is" + j,Toast.LENGTH_SHORT).show();
//Method getInsertDate return the insert date of product to database
int currentInsertdate = getInsertDate(cursor.getColumnIndex(ProductEntry.COLUMN_PRODUCT_INSERTDATE));
// Method getDays return the number of days to expire a product
int currentDays = getDays(cursor.getColumnIndex(ProductEntry.COLUMN_PRODUCT_DAYS));
currentDays = currentDays - (j - currentInsertdate);// calculate the new amount of remaining days to expire th product
ContentValues values = new ContentValues();
values.put(ProductEntry.COLUMN_PRODUCT_DAYS, currentDays);
//update all rows
db.update(TABLE_NAME, values, null, null);
}

Getting only the last value from cursor of sqlite android

Cursor getting first value as this
But returning last value as this.
Code for getting from cursor
BillInfo getContact(String date) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor query
Cursor cursor = db.query(TABLE_ID, new String[] { KEY_ID,
KEY_NAME, KEY_PRICE, KEY_DATE }, KEY_DATE + "=?",
new String[] { String.valueOf(date) }, null, null, null, null);
BillInfo contact = null ;
Array bill type
BillInfo bill[]=null;
int i=0;
Cursor code
if ( cursor.moveToFirst() ) {
bill=new BillInfo[cursor.getCount()];
do {
//Since both are in different classes
contact = new BillInfo(cursor.getString(0), cursor.getString(1), cursor.getString(2),cursor.getString(3));
bill[i]=contact;
}while(cursor.moveToNext());
}
return bill[i];
}
Code for loading the values on click
public void Load1(View v){
date1=date.getText().toString();
Doubleme d=new Doubleme(this);
BillInfo s;
Returning the value from get contact
s= d.getContact(date1);
info.append( s.toString());
}
Looks like, the value of i is fixed:
int i=0;
But inside of the cursor iteration loop you each time override the bill[i] with a new BillInfo reference. No wonder why the line:
return bill[i];
fetches the last row instead of the first one. I suggest getting rid of the while loop if you only need the first row.

How to retrieve single sqlite column and store rows into array

Im new to android, and i use Sqlite to store an array of type double into a column called "KEY_VALUE"
public long createEntry(Double rates) {
ContentValues cv = new ContentValues();
cv.put(KEY_VALUE, rates);
return ourDatabase.insert(TABLE, null, cv);
}
I put the data into the columns here via another class
for(i=0;i<37;i++){
entry.createEntry((theRSSHandler.rates()[i]));
}
Now i would like to retrieve the column i saved and get each row as an array element, ive seen and tried other similar solutions but they have not worked.
Here is the method i use to try and get the column data But it has failed.
public Double[] getData() {
String[] col = {KEY_VALUE};
Cursor c = ourDatabase.query(TABLE, col, KEY_VALUE , null, null, null, null);
Double[] result = null;
if(c != null){
c.moveToFirst();
}
int iVal = c.getColumnIndex(KEY_VALUE);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result[c.getPosition()] = c.getDouble(iVal);
}
return result;
}
you are trying to put values in an array that has not been initialized.
Double[] result = null;
needs to be followed up with something like...
result = new Double[100];
i think you probably want to initialize it with the number of records pointed to by the cursor
result = new Double[c.count()];

Skip deleted/empty rows sqlite

I am populating AChartEngine from sqlite database and I need all of the data to be displayed. The problem I'm having is when I delete a record the graph series stops populating at the deleted record. I need to find a way to skip over deleted/empty records and continue populating my graph. I need it to do it the same way listview skips over deleted records and keeps on displaying all rows. I am very new to a lot of this and am having a very difficult time with this. I have tried to write if statements in order to skip deleted/empty rows but nothing seems to work. Thank you for helping!
in my graphing activity:
for (int i = 1; !c.isAfterLast(); i++) {
String value1 = db.getValue1(i);
String value2 = db.getValue2(i);
c.moveToNext();
double x7 = Double.parseDouble(value1);
double y7 = Double.parseDouble(value2);
myseries.add(x7, y7);
}
I am getting error: CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
If I surround with try and catch it will populate rows up until the deleted record.
"EDIT"
in my sqlite database:
public String getValue1(long l) {
String[] columns = new String[]{ EMP_DEPT };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String value1 = c.getString(0);
return value1;
}
return null;
}
public String getValue2(long l) {
String[] columns = new String[]{ EMP_DATE1 };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String value2 = c.getString(0);
return value2;
}
return null;
}
Your issue is that your safety net for commands on rows that don't exist is to use if (c != null){ and then perform your commands inside that block, but a Cursor request from a query will never come up null, it will instead result in a cursor object with no rows.
A more appropriate solution to use this as your safety net instead if (c.moveToFirst()){ Because the method itself returns a boolean for if the method actually carried itself out in the first place - true if it moved and false if not (which occurs when there's no rows to move into). another check, if you wish, would be to see how many rows the cursor has with c.getCount().
Additionally, you should combine your methods so that you don't make redundant queries to the database:
public String[] getValues(long l) {
String[] results = new String[2];
String[] columns = new String[]{ EMP_DEPT, EMP_DATE1 };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c.moveToFirst()) {
results[0] = c.getString(0);
results[1] = c.getString(1);
} else {
Log.d("GET_VALUES", "No results formed from this query!");
}
return results;
}
You should use a single query to get all values at once:
SELECT Date1 FROM MyTable WHERE id BETWEEN 1 AND 12345
or:
db.query(EMP_TABLE, columns, EMP_ID + " BETWEEN 1 AND " + ..., ...);
Then missing values will just not show up when you iterate over the cursor.

Categories

Resources