Bug in my SQLite based application. using date. Android - android

All!
My code:
This method needs to check current date and if it is changed it will make new record in db.
public static void updateHintBase(SQLiteOpenHelper database)
{
String currentDate = getDateInString();
SQLiteDatabase db = database.getReadableDatabase();
Cursor cursor = db.query("HINTS",
new String[]{"CURRENT_DATE"},
"CURRENT_DATE = ?",
new String[]{currentDate},
null, null, null);
int countRow = cursor.getCount();
cursor.close();
if (countRow==0)
{
ContentValues values = new ContentValues();
values.put("CURRENT_DATE", currentDate);
values.put("SPENT", 0);
values.put("TOTAL", TOTAL_HINTS);
db.insert("HINTS", null, values);
}
db.close();
}
This method transforms date to String :
private static String getDateInString()
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(new Date());
return date;
}
Table structure:
db.execSQL("CREATE TABLE HINTS (CURRENT_DATE TEXT PRIMARY KEY , "
+ "SPENT INTEGER,"
+ "TOTAL INTEGER);");
But my code doesn't work. First time it works, but the second time when date was changed my first method finds element in cursor anyway...
For example:
1) Today 16.01.2017. My application was executed. Everything is all right.
2) Today 18.01.2017. My application was executed and I expect that method cursor.getCount() will return to me 0 and new row with new date will be created. But it returns to me 1. etc.

You may have to set cursor to cursor.MoveToNext() You are also closing the cursor before you get the information which may be the problem. Lastly looping through the cursor is the most efficient way to get more that one piece of information.

Please try this query:
cursor = db.rawQuery("select count(YOUR_ID) from HINTS where CURRENT_DATE = ? ", new String[] {currentDate});

Oh! I found my mistake!
Word "CURRENT_DATE" is reserved by SQL.
https://docs.oracle.com/cd/B28359_01/server.111/b28286/functions037.htm#SQLRF00628
That's why my code works incorrect.
I change "CURRENT_DATE" to "TODAY" an now it works fine.

Related

sqlite database overwrites existing record than inserting new record in physical device

I am facing challenge where i am unable to insert new record into table, rather it overwrites the first record in the table.
This happens in the physical device where as it is working fine in the emulator.
Following is the code used to insert the record:
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss", Locale.getDefault());
String strDate = formatter.format(date);
//SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING);
SQLiteDatabase db = this.getWritableDatabase();
/*ContentValues values = new ContentValues();
//values.put("UserId",1);
values.put("NoQPassed", scoreValues.get("NoPassed"));
values.put("NoQFailed", scoreValues.get("NoFailed"));
values.put("NoQSkipped", scoreValues.get("NoSkipped"));
values.put("SubjectName", scoreValues.get("strSubjectName"));
values.put("CompletedDateTime", strDate);
intRetVal= db.insert(score_Table_Name, null, values);*/
String strQuery="insert into "+score_Table_Name+" values ('"+strDate+"','"+scoreValues.get("NoPassed")+
"','"+scoreValues.get("NoFailed")+"','"+scoreValues.get("NoSkipped")+"','"+scoreValues.get("strSubjectName")+"')";
db.execSQL(strQuery);
db.close();
Tried inserting using db.insert and db.executeSQL, but none help. Can someone help me where i am going wrong?
I didnt add any primary key or autoincrement key to make sure the conflict is not because of that column. Do we always need to have primary key to insert new record?
you can use below getCount() method to count occurrences. if getCount(name)== 0 then do inserting. otherwise not inserting and try to log.
public int getCount(String name) {
Cursor c = null;
try {
db = Dbhelper.getReadableDatabase();
String query = "select count(*) from TableName where name = ?";
c = db.rawQuery(query, new String[] {name});
if (c.moveToFirst()) {
return c.getInt(0);
}
return 0;
}
finally {
if (c != null) {
c.close();
}
if (db != null) {
db.close();
}
}
}
But this logic may not be valid if you say you override it. I think there is no override possibilities in that android sqlite. Please check you might be drop your database any where before inserting new record. It may seems like override data

Getting an SQLite working within Android and accessing data

I am trying to get an SQLite database to work in Android and have a few questions!
I have put the following in the onCreate method of my database class, which extends SQLiteOpenHelper.
db.execSQL("CREATE TABLE IF NOT EXISTS `challenge` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `date` TEXT )");
I then have the following method.
public void addChallenge(){
SQLiteDatabase db = this.getWritableDatabase();
Date cDate = new Date();
String fDate = new SimpleDateFormat("yyyy-MM-dd").format(cDate);
ContentValues values = new ContentValues();
values.put("date", fDate);
db.insert("challenge", null, values);
}
And the following would grab the challenge added above back.
public int getChallengeId(){
SQLiteDatabase db = this.getWritableDatabase();
Date cDate = new Date();
String fDate = new SimpleDateFormat("yyyy-MM-dd").format(cDate);
String countQuery = "SELECT id FROM challenge WHERE date = " + fDate;
Cursor cursor = db.rawQuery(countQuery, null);
int challenge_id = 0;
if(cursor.moveToFirst()){
challenge_id = cursor.getInt(0);
}
return challenge_id;
}
My issue is that the challenge ID is returning as 0.
So I have a few questions.
Where is the database stored by default within Android?
Am I calling this correctly?
The code I use to access the above methods is as follows
Database db_add = new Database(context);
db_add.addChallenge();
db_add.close();
Database db_get = new Database(context);
challenge_id = db_get.getChallengeId();
db_get.close();
Any ideas?
Thanks.
The SQL query is not correct.
2015-02-23 tells the database that you want to subtract the numbers 2 and 23 from the number 2015.
Strings must be 'quoted'.
However, you should avoid such formatting problem by using parameters:
String countQuery = "SELECT id FROM challenge WHERE date = ?";
Cursor cursor = db.rawQuery(countQuery, new String[]{ fDate });

Android - SQLite Comparing system date to date in database

The basic idea of what I want to achieve is to make a comparison between the current Android system date and an existing date in a SQlite database.
The idea is to 1.) If the database does not contain contain a entry with today's date, then allow new entry
2.) If the database already contains an entry from today's date, then revoke entry and output error message.
My DBAdapter currently has a method that does the following:
public Cursor getDate(String date) {
String where = KEY_DATE + "=" + date;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c !=null) {
c.moveToFirst();
}
return c;
}
and the method i'm using to make the comparison is:
public void addRecord (View view){
db.open();
Cursor cursor = db.getDate(dateString);
if (cursor.moveToFirst()){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Date");
builder.setMessage("Entry for today exists, would you like to update this instead?"); builder.setPositiveButton("OK", null);
#SuppressWarnings("unused")
AlertDialog dialog = builder.show();
db.close();
}
else{
Do other work..
both Date's used for comparison is formatted using this code:
long longDate = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = sdf.format(longDate);
where I'm simply calling 'dateString'
My trouble is that it doesn't perform the correct checks and skips my else statement completely even tho i know there is an existing 'date' in the database. Is my SQL statement correct?
Try setting up the query like this:
db.query(true, DATABASE_TABLE, ALL_KEYS, KEY_DATE + "=?", new String[] {date}, null, null, null, null);
I use dates on my database, But I save them as a long value with the getDate() function.
Also I have found problems depending on the type of Date variable you use.
I like java.util.Date and never ever use the sql date variable.
I do where conditions for my data and all comparison are by getTime() which is a Long value.
With the long value you get from the database just do new Date( longValue ) and that way you get the correct date variable.

ERROR : CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

Hy Guys, I am Beginner Android Developer. I need your help. i want to insert data into 2 tables of sqlite tblorder, and orderdtl. on orderdtl i have to insert data from multiple item from listview. i try to toast all variable that i want to inserted. their all appears. but when i try to save it. i get those error.
this is my DBDataSource.java
public order createorder(String orderid, String notes, long outletid) {
ContentValues values = new ContentValues();
values.put(DBHelper.ORDER_ID, orderid); // inserting a string
values.put(DBHelper.NOTES, notes); // inserting an int
values.put(DBHelper.OUTLET_ID, outletid); // inserting an int
long insertId = database.insert(DBHelper.TABLE_ORDER, null,
values);
Cursor cursor = database.query(DBHelper.TABLE_ORDER,
allorder, DBHelper.ORDER_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
order neworder = cursorToorder(cursor);
cursor.close();
return neworder;}
private order cursorToorder(Cursor cursor) {
order order = new order();
order.setorderid(cursor.getString(cursor.getColumnIndex(DBHelper.ORDER_ID)));
order.setorderdate(cursor.getString(cursor.getColumnIndex(DBHelper.ORDER_DATE)));
order.setnotes(cursor.getString(cursor.getColumnIndex(DBHelper.NOTES)));
order.setoutletid(cursor.getLong(cursor.getColumnIndex(DBHelper.OUTLET_ID)));
return order;
}
The error refer to this code
Cursor cursor = database.query(DBHelper.TABLE_ORDER,
allorder, DBHelper.ORDER_ID + " = " + insertId, null,
null, null, null);
And this code
order.setorderid(cursor.getString(cursor.getColumnIndex(DBHelper.ORDER_ID)));
orderid is string, i try to get from yyyyMMddHHmmss.this is the code:
private String orderid(){
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyyMMddHHmmss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
I would be very grateful for any help that you give.Thank You.
The query didn't match any rows. Check the result of moveToFirst() to see whether the operation succeeded and only then access cursor data.
Example:
order neworder = null;
if (cursor.moveToFirst()) {
order neworder = cursorToorder(cursor);
}
cursor.close();
return neworder;
The insertId you get from insert() is the sqlite row id for the row. It's likely not the same as ORDER_ID. To make a column an alias for rowid, declare it as INTEGER PRIMARY KEY.
The error I see in logcat is not about _Player_8, but about the unknown column "KEY_Team_Name"
The problem is in your activity, the line prior to the last one:
String EntryA =String.valueOf( db.getentry("Ravirrrr", "KEY_Team_Name"));
It should be:
String EntryA =String.valueOf( db.getentry("Ravirrrr", DatabaseHandler.KEY_Team_Name));
And the DatabaseHandler should have all column names public, as the getentry method requires a column name.
Edit: adding an answer to the question in the comments below.
After calling db.query, you should check if you got something by calling Cursor.isAfterLast(). If true, the select returned an empty result set.
In your example, you WILL get an empty result set as the code creates an entry with "Ravi" as the team name, then asks for a team named "Ravirrrr".

search in sqlite database

i am trying to build an application that save data in sqlite database.i have a class that search in the database searching by VendorName and Date. The problem is i want it to display the MeterNumbers that was saved on the same Date . to what i have tried it only gives me the first result it get in the database, lets say i search for Tom that was saved on 01/01/2013, it supposed to display both metereNumbers of Tom that was saved on 01/01/2013
here is an example of my table in sqlite
VendorName Date MeterNumber
...Tom.... 01/01/2013 ......2098957438902
...Tom... 01/01/2013........4786909876785
...Steven...18/01/2013.........8978978906542
This is the Code in Sqlite database
public String getMeterNUmber(String MeterNumber) throws SQLException
{
String[] whereArgs = new String[]{MeterNumber};
Cursor mCursor = db.rawQuery("SELECT MeterNumber FROM " + SCAN_TABLE + " WHERE Date = ?",whereArgs);
mCursor.moveToFirst();
if(mCursor.getCount() > 0){
MeterNumber = mCursor.getString(0);
}
return MeterNumber;
}
this is the code in the class that calls for the query in the sqlite database and take the result to another class by intent
Intent updateCustomerIntent = new Intent(Searching.this, Result.class);
updateCustomerIntent.putExtra("product", dbUser.getMeterNUmber(ss));
startActivity(updateCustomerIntent);
Firstly, your parameter should be date not number,Secondly you don't loop through the result you just pull your first record. I think you should revise some good tutorial first at using SQLite with android.Here are some good links that may help.
Android SQLite Database and ContentProvider - Tutorial!
Android SQLite Database Tutorial
First of all, your getMeterNumber method takes a meter number as an argument, as already pointed out in ggenglish's comment, this seems odd, it should be a date no? Also, your method only calls mCursor.getString(0) once, and then returns that, which means you will only get the meter number from the first row of your result set.
If you want all the results, you will need to iterate over the full recordset. When you receive the cursor, it will be positioned just before the first row, so, you can loop through it with the method moveToNext(). Then, you will also have to store your result in a appropriate data structs, such as a ArrayList
ArrayList<String> results = new ArrayList<String>();
while (mCursor.moveToNext()) {
results.add(mCursor.getString(0));
}
So, you will end up with something like this
public ArrayList<String> getMeterNUmber(String meterDate) throws SQLException
{
String[] whereArgs = new String[]{meterDate};
Cursor mCursor = db.rawQuery("SELECT MeterNumber FROM " + SCAN_TABLE + " WHERE Date = ?",whereArgs);
ArrayList<String> results = new ArrayList<String>();
while (mCursor.moveToNext()) {
results.add(mCursor.getString(0));
}
mCursor.close();
return results;
}
And then finally, use putStringArrayListExtra instead of putExtra when adding the data to the intent.
If you are expecting one value you should do this:
public String getMeterNUmber(String date) throws SQLException {
String meterNumber = null;
Cursor cursor = db.rawQuery("SELECT MeterNumber FROM " + SCAN_TABLE + " WHERE Date = ?", new String[]{date} );
if ( cursor.moveToNext() ) meterNumber = cursor.getString(0);
cursor.close();
return meterNumber;
}
if you are expecting multiple elements you should loop as mentioned by others
public ArrayList<String> getMeterNUmber(String date) throws SQLException {
ArrayList<String> meterNumbers = new ArrayList<String>();
Cursor cursor = db.rawQuery("SELECT MeterNumber FROM " + SCAN_TABLE + " WHERE Date = ?", new String[]{date} );
while ( cursor.moveToNext() ) meterNumbers.add( cursor.getString(0) );
cursor.close();
return meterNumbers;
}
you specify you are querying by name and date but your example code shows otherwise, hopefully this helps a bit though.

Categories

Resources