Android: duplicate values are being inserted in to database - android

Each time i run the project same values are also being inserted in the android database. Even i have given the drop if exists query.What i need is that the data in the database gets updated only if there are some changes in the response from the server side instead of cresting database every time but what is happening with me is that same values got insertes again in the tables. How do I solve this? Following is my code:
public void onCreate(SQLiteDatabase database) {
try{
// onUpgrade(database, oldVersion, newVersion)
database.execSQL(DATABASE_CREATE);
}
catch (Exception e) {
System.out.println("in on create db"+e);
}}
public void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
database.execSQL("DROP TABLE IF EXISTS" +DATABASE_CREATE);
onCreate(database);
}
private static final String INSERT = "insert into "
+ DATABASE_TABLE + "(KEY_TYPE,KEY_ENCODING,KEY_WIDTH,KEY_HEIGHT,KEY_DATA,KeyIId)"+" values (?,?,?,?,?,?)";
public WineDatabaseAdapter(Context context) {
try{
this.context = context;
openHelper = new WineDatabaseHelper(context);
this.db=openHelper.getWritableDatabase();
this.insertStmt=this.db.compileStatement(INSERT);
}
catch(Exception e)
{
System.out.println(e);
}
}
Can anyone help me how to solve this problem.
Thanks

DROP TABLE seems a pretty extreme way of trying to stop duplicate values. It's a bit hard to follow the code you've posted, but the normal way of stopping duplicates is to add a unique index on the appropriate column(s). Have you tried that yet ? E.g. something like
CREATE UNIQUE INDEX idx_keytype ON tableName (key_type)

What does your schema look like? If you don't want duplicate rows and you know a certain column will be unique use the "UNIQUE" specifier on it. If what you really want is for the row to be replaced you have to use the databaseHelper command "replace" ie. dbHelper.replace(...);

Related

ORMLite dropping data when adding a column to the table

In my Android app, I'm using ORMLite to store data into local database, and when adding a column to that database using onUpgrade() method, I'm getting all the data of that table to be erased.
I'm using upgrade schema way mentioned in ORMLite documentation:
private static final int DATABASE_VERSION = 10;
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVer, int newVer) {
try {
if(oldVer < 10){
getGuardiansDao().executeRaw("ALTER TABLE `messages` ADD COLUMN updated_by TEXT;");
getGuardiansDao().executeRaw("ALTER TABLE `messages` ADD COLUMN updated_by_time TEXT;");
}
} catch (SQLException e) {
Log.e(DBManager.class.getName(), "Unable to upgrade database from version " + oldVer + " to new "
+ newVer, e);
}
}
And in the class assigned to that table:
#DatabaseTable(tableName = "messages")
public class Message extends Object implements Parcelable{
.
.
.
#DatabaseField
private String updatedBy;
#DatabaseField
private String updatedByTime;
}
Now after executing that it erases all the data stored in the table messages and I don't have any clue why that is happening.
Now after executing that it erases all the data stored in the table messages and I don't have any clue why that is happening.
Certainly the code that you've posted won't erase the table and ORMLite doesn't do that automatically or anything. Is there any chance the onCreate(...) method is being called instead for some reason?
There are many ways to debug this but you could log the contents of the table using raw statements in the onUpgrade(...) method to ensure that the table is being correctly built. Then you might be able to detect when it has been cleared.

How to reset SqLite database in Android?

I want my users to be able to reset the application, then I need to reset the SQLite database that I have created.
How can I do that? I want to reset the database or delete and recreate the database.
Just delete your database by
context.deleteDatabase(DATABASE_NAME);
Please make sure to close your database before deleting.
Bit late but this can help other people
public void clearDatabase(String TABLE_NAME) {
String clearDBQuery = "DELETE FROM "+TABLE_NAME;
db.execSQL(clearDBQuery);
}
This should remove all the rows from the table refer documentation of SQLite database here!
Working for me.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS TABLE_NAME");
onCreate(db);
}
Just drop tables from database
db.execSQL("DROP TABLE "+TABLENAME);
and again create the table in same database.
You can delete the content of all your tables using delete from table where 1=1, or you can call your database onCreate method again
There are two option to clear the table from the database
Firstly
If you wan to delete the data on specific row you need to add this code in the database class
public Boolean specification(int id, String table_name)
{
return db.delete(table_name, KEY_ID + "=" + id, null) > 0;
}
and add the below code when you want to perform this action
db.deleteSpecificOrder(id, "table_orders");
Secondly
If you want to delete all the data from th table then you just need to add below code into your database
public void clearDatabase(String TABLE_NAME) {
db = this.getReadableDatabase();
String clearDBQuery = "DELETE FROM " + TABLE_NAME;
db.execSQL(clearDBQuery);
}
and then add the below line where you want to perform that action
db.clearDatabase("table_food_items");
I Hope that will help you

Error in Inserting values to Database

I am creating a simple Database to add the values of product. While adding the entries in database I am getting an error in Logcat and the program get stop there and then.
I am not clear with the error but its something related to insertion of data or in query I have written. I tried all possible alternatives I could.
Program Code is :
DataBase.java
public class DataBase extends SQLiteOpenHelper
{
public DataBase(Context context) {
super(context, CreateTable.DB_NAME, null, CreateTable.DB_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String create = "Create Table " + CreateTable.TABLE_NAME + "( " + CreateTable.KEY_ID
+ " INTEGER PRIMARY KEY," + CreateTable.KEY_NAME + " TEXT,"
+ CreateTable.KEY_PRICE + " REAL)";
db.execSQL(create);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public void addProduct(Product p)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues c = new ContentValues();
c.put(CreateTable.KEY_NAME, p.getName());
c.put(CreateTable.KEY_PRICE, p.getPrice());
db.insert(CreateTable.TABLE_NAME, null, c);
db.close();
}
}
EnterDeatils.java
public class EnterDeatils extends Activity {
EditText name;
EditText price;
Button done;
int id = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.enter_deatils);
name = (EditText) findViewById(R.id.edtname);
price = (EditText) findViewById(R.id.edtprice);
done = (Button) findViewById(R.id.btndone);
done.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Product p = new Product();
p.setId(id);
p.setName(name.getText().toString());
p.setPrice(Float.valueOf(price.getText().toString()));
DataBase d = new DataBase(EnterDeatils.this);
d.addProduct(p);
}
});
}
}
LogCat Error:
01-12 23:06:52.343: E/Database(382): Error inserting pPrice=12.0 pName=ds
01-12 23:06:52.343: E/Database(382): android.database.sqlite.SQLiteException: table Books has no column named pPrice: , while compiling: INSERT INTO Books(pPrice, pName) VALUES(?, ?);
Requesting you guys to just help me to identify the error.
Thanks in Advance.
SQLiteOpenHelper onCreate() is only called if the database file does not exist. If you modify the SQL in onCreate(), you'll have to ensure the database file is updated.
Two approaches:
Delete the old version of the database. Uninstall is one way to do this. This way the database is created with whatever code you currently have in onCreate(). This is often the simplest way during app development.
Bump up the database version number you pass to SQLiteOpenHelper superclass. If this number is different from the version number stored in the database file, onUpgrade() or onDowngrade() is called, and you can update the database schema. This is the preferred way when you already have released versions out so your users can preserve their data when updating your app.
Delete your database from terminal
adb shell
cd /data/data/com.example.applicationname/databases
rm *
First you created table Books with x number of columns but pPrice column was not included in that create table query. Later on you added this column name to your create table query.
That's why this problem happened.
Try to delete the database. It will delete the old database from application and when you re start new database will be created.
onCreate() is only called if your database DOES NOT exist
Seems that your database was created without column KEY_PRICE.
After that you have altered your code adding column KEY_PRICE to String create.
If this is true you must increment database version in order it be created again:
Change:
CreateTable.DB_VERSION = 1;
To
CreateTable.DB_VERSION = 2;
As laalto suggested change onUpgrade
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + CreateTable.TABLE_NAME);
onCreate(db);
}
Check if you are missing some space. I had same problem , and solved with adding space...

Unable to open databse file sql lite android

I'm trying to to create a database and insert some data into it but this doesn't seem to be working. Can anybody tell me what's wrong in my implementation? Here is my code for the database. Thank you.
SQLiteDatabase db = null;
db.openOrCreateDatabase("order", null);
db.execSQL("CREATE TABLE IF NOT EXISTS order ( id INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR, Price INTEGER)");
db.execSQL("INSERT INTO order (Name, Price) VALUES ('Paneer Tikka', '100')");
SQLiteDatabase db = null;
db.openOrCreateDatabase.. will result in NullPointerException. You need to assign SQLLiteDatabase instance to db and then call openOrCreateDatabase on db.
Another issue is, 100 is integer, don't need in single quotes.
db.execSQL("INSERT INTO order (Name, Price) VALUES ('Paneer Tikka', 100)");
There is a really nice tutorial supplied by google. It take you through how to do the basics with the SQLite database.
http://developer.android.com/resources/tutorials/notepad/index.html
I would suggest going through that.
In that tutorial is suggests using a SQLHelper inner class something like this
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE_CELEBS);
db.execSQL(DATABASE_CREATE_CHECKINS);
Log.i("dbCreate", "must have worked");
} catch (Exception e) {
Log.i("dbCreate", e.toString());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS celebs");
db.execSQL("DROP TABLE IF EXISTS checkins");
onCreate(db);
}
}
Then to get a new database you can call
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
You need to learn about SQLiteOpenHelper. Ask Google for some tutorials.
Incredibly Sqlite has much better performance "in transation" on inserts without transaction. I particularly, massive use transaction processes, or failure comes randomly at some point.

Storing application database schema

In example apps database is in most cases single table, so db schema is stored in static variable.
Storing large schema in seperate file is more friendly for me.
How can I do that? I thought about using resources (R.strings.db_schema) but probably there is a better way.
Could somebody give me any advice?
You could put the schema data in a raw file under res/raw. Then you can just load and parse that file the first time.
The way I do is to have a class per table, named after the table with "Table" suffix (e.g. PlayerTable or EventTable).
These classes contain all the static variable for the table name and all the field names, and they also contain two static methods:
public static void onCreate(SQLiteDatabase database)
public static void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion)
So that my SQLiteOpenHelper can just call all of them, without having hundreds of static variables with all the fields and create queries. E.g:
#Override
public void onCreate(SQLiteDatabase database) {
PlayerTable.onCreate(database);
EventTables.onCreate(database);
..... any other table you have .....
}
This class is then injected into all my data access objects (select / update / insert queries). For them I have dedicated classes that contain all my methods, by functionality (e.g. EventHandlingDAO for all the queries that deal with event handling).
And finally, theses DAO are injected into the activities that need them, when needed.
EDIT: A few more details about my code:
My main objects are the DAO (data access objects), in which I have methods like:
// in EventHandlingDAO:
public void addEvent(Event event) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
try {
database.execSQL("INSERT INTO " + EventTable.EVENT_TABLE_NAME + " (...."); // list of fields and values
} finally {
database.close();
}
}
public List<Event> getAllEvents() {
final List<Event> result = new ArrayList<Event>();
SQLiteDatabase database = databaseHelper.getReadableDatabase();
try {
final Cursor cursor = database.rawQuery("SELECT " + EventTable.KEY_NAME + ", " + EventTable.KEY_DATE_AS_STRING + " FROM " + EventTable.TABLE_NAME, null);
cursor.moveToFirst();
// ... rest of the logic, that iterates over the cursor, creates Event objects from the cursor columns and add them to the result list
return result;
} finally {
database.close();
}
}
So in that DAO, I have my databaseHelper object, which instanciates my class that extends SQLiteOpenHelper with the methods I talked about above.
And of course, I have interfaces to all my DAO, so that I can inject a Stub or mocked implementation in my tests (or experiment with different implementations if I want to try another solution based on SharedPreference for example)
And the code for my PlayerTable table:
public static void onCreate(SQLiteDatabase database) {
database.execSQL(TABLE_CREATE); // TABLE_CREATE is my "CREATE TABLE..." query
}
public static void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
// A bit blunt, that destroys the data unfortunately, I'll think about doing something more clever later ;)
database.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(database);
}

Categories

Resources