Displaying data on Android after retrieving data form Android Sq lite - android

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();
}

Related

Getting date difference in sqlite

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());
}

Cursor not working in Android sqlite

My android app has 2 tables Projects and Tasks.
Each Project can have multiple Tasks.
Like below
Now I want to sum up all proportion values of the single task table
I did it.. but the issue is its adding proportion values from all task tables !
The cursor I coded is as follows
public int sumproportion(long projectId){
int value = 0;
int p = 0;
Cursor cu = mDatabase.rawQuery("SELECT * FROM " + DBHelper.TABLE_TASKS, null);
ArrayList temp = new ArrayList();
if (cur != null) {
if (cur.moveToFirst()) {
do {
temp.add(cur.getString(cur.getColumnIndex("proportion"))); // "Title" is the field name(column) of the Table
} while (cur.moveToNext());
}
}
Object ia[] = temp.toArray();
for(int i=0; i<ia.length; i++)
{
p = Integer.parseInt((String) ia[i]);
value = value + p;
}
System.out.println("Value is: " + value);
return value;
}
When I added cursor as below
Cursor cur = mDatabase.query(DBHelper.TABLE_TASKS, mAllColumns,
DBHelper.COLUMN_TASK_PROJECT_ID + " ="+String.valueOf(projectId),
null, null, null, null);
It doesn't add anything. Can any one help fix it please?
First of all, you can just use query like this SELECT SUM(proportion) from TABLE_TASK. proportion should have numeric type.
Secondly, verify that your Cursor return any rows. Probably you pass wrong projectId if there no rows.

How to check the value already excists or not in sqlite db in android?

In my application I am saving a bill number in SQLite database. Before I add a new bill number how to check if the bill number exists in the DB.
My main class code is,
String bill_no_excist_or_not = db.billno_exist_or_not(""+et_bill_number.getText().toString());
Log.v("Bill No", ""+bill_no_excist_or_not);
My DB Code,
String billno_exist_or_not(String bill_number){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_BILL_DETAILS, new String[] { KEY_BILL_NUMBER }, KEY_BILL_NUMBER + "=?"
+ new String[] { bill_number }, null, null, null, null);
//after this i don't know how to return the values
return bill_number;
}
I don't know how to check the values which is already available or not in DB. Can any one know please help me to solve this problem.
Here is the function that helps you to find whether the value is available in database or not.
Here please replace your query with my query..
public int isUserAvailable(int userId)
{
int number = 0;
Cursor c = null;
try
{
c = db.rawQuery("select user_id from user_table where user_id = ?", new String[] {String.valueOf(userId)});
if(c.getCount() != 0)
number = c.getCount();
}
catch(Exception e) {
e.printStackTrace();
} finally {
if(c!=null) c.close();
}
return number;
}
Make your KEY_BILL_NUMBER column in your table UNIQUE and you can just insert using insertWithOnConflict with the flag SQLiteDatabase.CONFLICT_IGNORE

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.

android sqlite query optimisation

I have an SQLite db with about 400 000 entries. To query the db I am using the following method:
public double lookUpBigramFrequency(String bigram) throws SQLException {
SQLiteDatabase db = dbh.getReadableDatabase();
double frequency = 0;
bigram = bigram.toLowerCase();
String select = "SELECT frequency FROM bigrams WHERE bigram = '"
+ bigram + "'";
Cursor mCursor = db.rawQuery(select, null);
if (mCursor != null) {
if (mCursor.moveToFirst()) {
frequency = Double.parseDouble(mCursor.getString(0));
} else {
frequency = 0;
}
}
return frequency;
}
but it takes about 0.5 sec to retrieve a single entry and having few queries, it builds up and the method is executing for 10 secs. How to speeed it up?
Firstly, use an INDEX
http://www.sqlite.org/lang_createindex.html
in your case that will be something like:
CREATE INDEX idx_bigram ON bigrams (bigram)
Secondly, use '?' instead of literal query. It helps sqlite for caching requests:
String select = "SELECT frequency FROM bigrams WHERE bigram = ?";
Cursor mCursor = db.rawQuery(select, new String[]{ bigram });
Thirdly, I trust query is more efficient than rawQuery:
mCursor = dq.query("bigrams", new String[] { "frequency" }, "bigram = ?",
new String[]{ bigram }, null, null, null, null);
Fourthly, you can query several values at once (not compatible with point 2):
SELECT frequency FROM bigrams WHERE bigrams IN ('1', '2', '3')
Fifthly, you don't need to open your database every time. You should consider leaving it open.
Edit
After seeing this question IN clause and placeholders it appears you can combine 2 and 4 after all (not sure it is useful, though)
Always use transaction mechanism when you want to do lots of database operations
public static void doLotDBOperations() {
try {
// Code to Open Database
// Start transaction
sqlDb.beginTransaction();
// Code to Execute all queries
sqlDb.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
// End all transaction
sqlDb.endTransaction();
// Code to Close Database
}
}

Categories

Resources