Android: SQLiteConstraintException: error code 19: constraint failed - android

I checked other examples in SO and I searched a lot, nothing is working for me. The database file is this (after suggested edit).
Error
E/Database(274): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
E/Database(274): at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
E/Database(274): at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:55)
E/Database(274): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1549)
E/Database(274): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1410)
E/Database(274): at com.example.nycgasstationhunter.userRegister$2.onClick(userRegister.java:51)
E/Database(274): at android.view.View.performClick(View.java:2408)
E/Database(274): at android.view.View$PerformClick.run(View.java:8816)
E/Database(274): at android.os.Handler.handleCallback(Handler.java:587)
E/Database(274): at android.os.Handler.dispatchMessage(Handler.java:92)
E/Database(274): at android.os.Looper.loop(Looper.java:123)
E/Database(274): at android.app.ActivityThread.main(ActivityThread.java:4627)
E/Database(274): at java.lang.reflect.Method.invokeNative(Native Method)
E/Database(274): at java.lang.reflect.Method.invoke(Method.java:521)
E/Database(274): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
E/Database(274): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
E/Database(274): at dalvik.system.NativeStart.main(Native Method)
Code
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
public class userRegister extends Activity{
//database
SQLiteDatabase db;
DBHelper dbhelper;
Context ourContext;
ContentValues cv;
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_register);
//database
dbhelper=new DBHelper(this);
db=dbhelper.getWritableDatabase();
cv=new ContentValues();
//editText
final EditText userEdit=(EditText) findViewById(R.id.userEdit);
final EditText emailEdit=(EditText) findViewById(R.id.emailEdit);
final EditText passwordEdit=(EditText) findViewById(R.id.passwordEdit);
final EditText retypePassEdit=(EditText) findViewById(R.id.retypePassEdit);
//Register button
Button regButton = (Button) findViewById(R.id.regButton);
regButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//string
final String userName=userEdit.getText().toString();
final String emailAddress=emailEdit.getText().toString();
final String password=passwordEdit.getText().toString();
final String retypePassword=retypePassEdit.getText().toString();
if (userName.length()!=0){
if (emailAddress.length()!=0){
if (password.length()!=0){
if (retypePassword.equals(password)){
//save in DB
cv.put(DBHelper.USER, userName);
cv.put(DBHelper.EMAIL,emailAddress);
cv.put(DBHelper.PASSWORD, retypePassword);
db.insert(DBHelper.USER_TABLE, null, cv);
Intent intent = new Intent (userRegister.this,Profile.class);
startActivity(intent);
}
else
Toast.makeText(userRegister.this,"Password mismatch", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(userRegister.this,"Invalid password", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(userRegister.this,"Invalid email", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(userRegister.this,"Invalid user name", Toast.LENGTH_SHORT).show();
}
});
}
}
When I insert information and press regButton, it sends me to Profile activity. There is no information being saved in database. I don't understand the error in LogCat and how can I solve that? Why there is nothing in database? (I am using SQLite Database Browser to check data.) Thank you

The error SQLiteConstraintException indicates that an integrity constraint was violated.
From your Create Table SQL command I think the first problem is your primary key. It should be declare as autoincrement
Change String createDB:
public final String createDB="create table "+USER_TABLE+"("
+ C_ID + " integer primary key autoincrement, "
+ USER + " text not null,"
+ EMAIL + " text not null,"
+ PASSWORD + " text not null,"
+ TIME + " text not null);";
Also, all fields are declared not null, you should test if retypePassword is not null and you must set a value to field TIME.
EDIT
In order the autoincrement take effect, the database version value need to be incremented.
In DBHelper class change DATABASE_VERSION=1; to DATABASE_VERSION=2;

If the database schema is as follows as you mention in comments (from this question)...
public final String createDB="create table "+USER_TABLE+"("
+C_ID+" integer primary key, "
+USER+" text not null,"
+EMAIL+ " text not null,"
+PASSWORD+ " text not null,"
+TIME+ " text not null);";
... then you have not specified a value for the TIME column which has the not null constraint.
Some options:
Add a TIME value to the ContentValues before insert().
Change the schema and provide a suitable default such as
TIME + " text not null default current_timestamp"
As always, when changing the database schema, remove the old database so that onCreate() gets called with the new code (clear app data or just uninstall the app).

In my case I made two HTTP-requests and got two lists. Then wrote them to two tables. But first in a child table and then in parent. Strange, but a problem appeared on Android 4.4.2, but not on Android 5.0.

Related

Why am i getting SQLlite constraint error (Code=19) even if i am not leaving any fields null?

I am trying to create a Admin table.Taking the input from the app and adding it to the table.My admin class is used for getting and setting the values .
I tried a lot but unable to identify the issue yet .
This is from my Data Base Helper class
#Override
public void onCreate(SQLiteDatabase db) {
String query_create_administrator="create table "+TBL_ADMINISTRATOR+" ( "+ADMIN_ID+" INTEGER PRIMARY KEY, "+ADMIN_NAME+
" TEXT, "+ADMIN_MAIL+" TEXT, "+ADMIN_PASSWORD+" TEXT, "+ADMIN_CONTACT+" TEXT, "+ADMIN_ADDRESS+" TEXT, "+
ADMIN_ROLE+" TEXT, "+STATUS+" TEXT)";
String query_create_student="create table "+TBL_STUDENT+" ( "+STUDENT_ID+" INTEGER PRIMARY KEY, "
+STUDENT_PID+" TEXT, "+STUDENT_NAME+" TEXT, "+STUDENT_MAIL+" TEXT, "+STUDENT_PASSWORD+" TEXT, "
+STUDENT_CONTACT+" TEXT, "+STUDENT_ADDRESS+" TEXT, "+STUDENT_COURSE+" TEXT, "+STUDENT_YEAR+" TEXT, "
+STUDENT_BRANCH+" TEXT)";
db.execSQL(query_create_administrator);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long registerAdmin(Administrator obj){
SQLiteDatabase db=getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(ADMIN_ID,obj.getId());
cv.put(ADMIN_NAME,obj.getName());
cv.put(ADMIN_MAIL,obj.getMail());
cv.put(ADMIN_PASSWORD,obj.getPassword());
cv.put(ADMIN_CONTACT,obj.getContact());
cv.put(ADMIN_ADDRESS,obj.getAddress());
cv.put(ADMIN_ROLE,obj.getRole());
cv.put(STATUS,obj.getStatus());
db.insert(TBL_ADMINISTRATOR,null,cv);
long done=3;
return done;
}
This is the method from the activity class
public void register(View v){
long check=0;
obj=new Administrator();
SchoolDBHandler db=new SchoolDBHandler(this);
String n,m,p,c,a;
n=name.getText().toString();
m=mail.getText().toString();
p=pass.getText().toString();
c=contact.getText().toString();
a=address.getText().toString();
if(n.equalsIgnoreCase("")||m.equalsIgnoreCase("")||p.equalsIgnoreCase("")||c.equalsIgnoreCase("")||a.equalsIgnoreCase(""))
{
Toast.makeText(getApplicationContext(),"All fields are mandatory",Toast.LENGTH_SHORT).show();
}
else {
obj.setName(n);
obj.setMail(m);
obj.setPassword(p);
obj.setContact(c);
obj.setAddress(a);
obj.setStatus("Active");
if(role_select2!=null)obj.setRole(role_select2);
check=db.registerAdmin(obj);
if(check>0) {
resetEditTextxs();
Toast.makeText(getApplicationContext(),"Successfully Created",Toast.LENGTH_SHORT).show();
}
else Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_SHORT).show();
}
}
This is the error log:
E/Database: Error inserting status=Active address=AAA email=AAA name=AAA role=parent contact=1211 eid=0 pass=AAA
android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:61)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1582)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1426)
at com.thebitshoes.classproject.dao.SchoolDBHandler.registerAdmin(SchoolDBHandler.java:191)
at com.thebitshoes.classproject.AdminSignUp.register(AdminSignUp.java:109)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:2485)
at android.view.View$PerformClick.run(View.java:9080)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Your "onCreate:"
public void onCreate(SQLiteDatabase db) {
String query_create_administrator="create table "+TBL_ADMINISTRATOR+" ( "+ADMIN_ID+" INTEGER PRIMARY KEY, "+ADMIN_NAME+
" TEXT, "+ADMIN_MAIL+" TEXT, "+ADMIN_PASSWORD+" TEXT, "+ADMIN_CONTACT+" TEXT, "+ADMIN_ADDRESS+" TEXT, "+
ADMIN_ROLE+" TEXT, "+STATUS+" TEXT)";
<= ADMIN_ID is your primary key: it cannot be null
Your registerAdmin":
public long registerAdmin(Administrator obj){
SQLiteDatabase db=getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(ADMIN_ID,obj.getId());
cv.put(ADMIN_NAME,obj.getName());
cv.put(ADMIN_MAIL,obj.getMail());
cv.put(ADMIN_PASSWORD,obj.getPassword());
cv.put(ADMIN_CONTACT,obj.getContact());
cv.put(ADMIN_ADDRESS,obj.getAddress());
cv.put(ADMIN_ROLE,obj.getRole());
cv.put(STATUS,obj.getStatus());
db.insert(TBL_ADMINISTRATOR,null,cv);
<= It looks like you're TRYING to assign an admin_id...
Your error message:
status=Active
address=AAA
email=AAA name=AAA
role=parent
contact=1211
eid=0
<= But ADMIN_ID doesn't appear to be in the actual "insert"
You haven't shown us how you've defined class "Administrator" (the "obj" parameter in registerAdmin()), nor what the "ADMIN_ID" column name actually is (so we don't really know how to map the names in your error message with the names in your definition).
But the message is definitely occurring in "registerAdmin()", and, because you have only one required field ("ADMIN_ID"), that's definitely the place to start looking.
'Hope that helps!
==========================================================
UPDATE: There are several different questions here:
Q: Why am I getting SQLiteConstraintException: error code 19?
A: The error is coming from registerAdmin(), column ADMIN_ID (aka "eid"). You've apparently already registered an administrator, with the duplicate ID "0".
Don't do that :) Primary keys must be non-null, and must be unique.
Q: Should I let it be auto incremented by default?
A: In general, for most other databases, I'd reply "sure!"
However, I've seen some articles discouraging AUTO_INCREMENT in SQLLite. For example: http://www.sqlitetutorial.net/sqlite-autoincrement/
I'll leave the choice up to you. If you allow SQLLite to assign the ID, however, make sure it's in sync with your Java "Administrator" object (obj).
ALSO: you might not WANT to insert, if the administrator already exists.
If you want to modify an EXISTING administrator, then you want to UPDATE the row. Look here for more details:
SQLite UPSERT / UPDATE OR INSERT
-- Try to update any existing row
UPDATE players
SET user_name='steven', age=32
WHERE user_name='steven';
-- If no update happened (i.e. the row didn't exist) then insert one
INSERT INTO players (user_name, age)
SELECT 'steven', 32
WHERE (Select Changes() = 0);
Again - I hope that helps!
PS:
Please consider renaming eid to ADMIN_ID, or admin_id.
And don't forget to apply the same principles when you register students!

Sqlite column id is not unique

below is my code i just want to display the data i inserted in the sqlite database to a text view but i have this error saying that the id is not unique.
package com.example.sqlitetest;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity {
TextView scrName, fName;
Button go;
SQLiteDatabase db;
String screenName, fullName;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db = openOrCreateDatabase("MyDataBase", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE if not exists MyTable(ScreenName Varchar, FullName Varchar, id int(3) PRIMARY KEY);");
db.execSQL("Insert into MyTable VALUES('joff', 'tiquez', 1);");
cursor = db.rawQuery("Select * from MyTable", null);
cursor.moveToFirst();
scrName = (TextView) findViewById(R.id.scrName);
fName = (TextView) findViewById(R.id.fName);
while(cursor.isAfterLast() == false){
//retrieving the data from sqlite (im not sure if im doing it right)
String screenname = cursor.getString(cursor.getColumnIndex("ScreenName"));
String fullname = cursor.getString(cursor.getColumnIndex("FullName"));
//this are the textview
scrName.setText(screenname);
fName.setText(fullname);
cursor.moveToNext();
}
db.close();
}
}
this is my whole java code. thanks :)
Well I think this project works fine when you run it first time. When you run it second time it gives error because id is your primary key and the row with the id 1 has been already inserted to your database.
To get rid of errors either :
1) uninstall the app and run it again
2) Don't make id as primary key
3) Catch the exception and handle it yourself
Might I suggest an alternative to this. What you can do is make the id column autoincrement as well while still keeping that column as primary key
EDIT:-
Also I have some other suggestions for you:-
db.execSQL("Insert into MyTable VALUES('joff', 'tiquez', 1);");
you can user ContentValues instead
while(cursor.isAfterLast() == false){
could be replaced with while(!cursor.isAfterLast()){. Looks cleaner this way.
Or you could directly replace while(cursor.isAfterLast() == false){ with while(cursor.moveToNext()){ and can remove out cursor.moveToNext(); from the while block.
Happy Coding!!!

Table not found issue in SQLite

I have written a code that get information from json file related to specific YouTube video and then stores the information I need in my database.
The parsing from json file has no problem. when I am trying to insert values in my database an error message appears telling me that no such table exists.
Here is the stack-trace:
07-31 08:42:22.451: I/Database(365): sqlite returned: error code = 1,
msg = no such table: youtube_VIDEOS 07-31 08:42:22.471: E/Database(365):
Error inserting video_CommentCount=70 video_CountView=50 video_Name=Badly
Drawn Boy - Disillusion (directed by Garth Jennings)
video_Url=https://www.youtube.com/watch?v=B11msns6wPU&feature=youtube_gdata_player
video_LIKES=60 video_Img=https://i1.ytimg.com/vi/B11msns6wPU/default.jpg
video_Descrption=My new playlist Description 07-31 08:42:22.471:
E/Database(365): android.database.sqlite.SQLiteException:
no such table: youtube_VIDEOS: ,
while compiling: INSERT INTO youtube_VIDEOS(video_CommentCount, video_CountView, video_Name, video_Url,video_LIKES, video_Img, video_Descrption) VALUES(?, ?, ?, ?, ?, ?, ?);
07-31 08:42:22.471: E/Database(365): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
And here is my database code:
package com.example.tstnetconnwithjson.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class youtube_db extends SQLiteOpenHelper {
public static final String dataBase_NAME="YOUTUBE_database";
private static final int dataBase_VERSION=1;
private static final String dataBase_TABLE="youtube_VIDEOS";
public static final String[] COLS_List={"video_Name","video_Descrption","video_Img","video_Url","video_CountView","video_LIKES","video_CommentCount"};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//end of declaring attributes and tables conents
public youtube_db(Context context) {
super(context,dataBase_NAME, null, dataBase_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table" + dataBase_NAME + "(" + COLS_List[0] +" text not null , "+ COLS_List[1]
+" text not null , "+ COLS_List[2]+" text not null , "+COLS_List[3]+" text not null , "+COLS_List[4]+" integer , "+COLS_List[5]
+" integer , "+COLS_List[6]+" integer ) ");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.i("in the upgrade", "ok");
}
}
And here is the function that would insert the information in my database:
package com.example.tstnetconnwithjson.db;
import com.example.tstnetconnwithjson.tables.videos;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class youtubeDataBaseManager {
SQLiteDatabase SQL_db;
youtube_db my_Database;
public youtubeDataBaseManager(Context c){
my_Database=new youtube_db(c);
SQL_db= my_Database.getWritableDatabase();
}//end of costructor
public long insert_Youtube_Info( videos video){
ContentValues contentValues = new ContentValues();
contentValues.put(youtube_db.COLS_List[0], video.getVideoname());
contentValues.put(youtube_db.COLS_List[1], video.getDecscrption());
contentValues.put(youtube_db.COLS_List[2], video.getImageurl());
contentValues.put(youtube_db.COLS_List[3], video.getVediourl());
contentValues.put(youtube_db.COLS_List[4], "50");
contentValues.put(youtube_db.COLS_List[5], "60");
contentValues.put(youtube_db.COLS_List[6], "70");
long addResult ;
addResult= SQL_db.insert(youtube_db.dataBase_TABLE, null, contentValues);
if(addResult==-1)
{
Log.i("add video", "add error.... ");
}
else
{
Log.i("add video", "add:ok.... ");
}
return addResult;
}
Can anyone tell me what is the problem?
"create table" + dataBase_NAME + "("
You are missing space between name and <create table> keyword. You have to change it to:
"create table " + dataBase_TABLE + "("
Otherwise, your DDL statement won't work.
Later, you try and reference a table called "youtube_VIDEOS", which doesn't exist. Because you never created it. It's all about typo.
you should change here:
create table" + dataBase_TABLE+ "(" + COLS_List[0] +" text not null , "+ COLS_List[1]
+" text not null , "+ COLS_List[2]+" text not null , "+COLS_List[3]+" text not null , "+COLS_List[4]+" integer , "+COLS_List[5]
+" integer , "+COLS_List[6]+" integer ) ");
You have that error, because your table in database didn't successfully created. Why ? Because your table hasn't got primary key (id). Add, e.g :
`_id` INT PRIMARY KEY AUTOINCREMENT,
And now every thing should work correctly

Cannot create Android SQLite database: PRAGMA error

Errors:
E/Database( 8614): Failure 21 (out of memory) on 0x0 when preparing 'PRAGMA user_version = 1'.
E/Database( 8614): Failure 21 (out of memory) on 0x0 when preparing 'ROLLBACK;'.
D/Database( 8614): exception during rollback, maybe the DB previously performed an auto-rollback
D/AndroidRuntime( 8614): Shutting down VM
W/dalvikvm( 8614): threadid=3: thread exiting with uncaught exception (group=0x4001dc20)
E/AndroidRuntime( 8614): Uncaught handler: thread main exiting due to uncaught exception
My current code:
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Database extends SQLiteOpenHelper {
private static String DatabaseName = "Entries.db";
public Database(Context context) {
super(context, DatabaseName, null, 1);
}
public void onCreate(SQLiteDatabase D) {
D.execSQL(
"CREATE TABLE Containers ("
+ "ID INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "Parent INTEGER,"
+ "Sequence INTEGER,"
+ "Name TEXT"
+ ")"
);
D.execSQL(
"CREATE TABLE Files ("
+ "ID INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "Parent INTEGER,"
+ "Sequence INTEGER,"
+ "Name TEXT,"
+ "Text TEXT"
+ ")"
);
D.execSQL("INSERT INTO Containers (Parent, Sequence, Name) VALUES (0, 2, \"TestLine2\")");
D.execSQL("INSERT INTO Containers (Parent, Sequence, Name) VALUES (0, 1, \"TestLine1\")");
D.execSQL("INSERT INTO Containers (Parent, Sequence, Name) VALUES (0, 3, \"TestLine3\")");
D.execSQL("INSERT INTO Containers (Parent, Sequence, Name) VALUES (2, 1, \"TestLine2-1\")");
D.execSQL("INSERT INTO Containers (Parent, Sequence, Name) VALUES (2, 2, \"TestLine2-2\")");
D.close();
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
}
public static Cursor Query(Context context, String SQL) {
StartQuerySeries(context);
Cursor Result = Query(SQL);
StopQuerySeries();
return Result;
}
private static Database D = null;
public static void StartQuerySeries(Context context) {
D = new Database(context);
}
public static Cursor Query(String SQL) {
SQLiteDatabase X = D.getWritableDatabase();
return X.rawQuery(SQL, null);
}
public static void StopQuerySeries() {
D.close();
D = null;
}
}
The error happens when, in the primary Activity, it's called like this:
Database.Query(this, "INSERT INTO Files (Parent, Sequence, Name, Text) VALUES (1, 1, \"Item1\", \"Item1 Text\")");
The error happens on the "D.getWritableDatabase()" line... The closest thing I can find is, on http://www.sqlite.org/c3ref/c_abort.html that Failure 21 says "Library used incorrectly" - any help?
Oh, and I checked - the database file does get created, but there are no tables in it, so that onCreate() above isn't getting called.
I've got the same problem 2 minutes ago. I solved it by removing the D.close() line.
It seems like android doesn't like it when you close the passed SQLiteDatabase Object. I think the surrounding code which calls the onCreate() method already manages opening and closing the database correctly. So you just have to do everything to get the tables up.
Maybe There is some work done on this object after you created the tables. I would like to know if this solves your problem as well.
I would also really love to hear the exact explaination for this behaviour.
Thanks a lot !!!
The symptom:
was exactly the same for me ...
I succeeded to get the database file created but not the tables
and I was getting following error in LogCat
03-16 09:55:12.093: ERROR/Database(224): Failure 21 (out of memory) on 0x0 when preparing 'ROLLBACK;'.<BR>
03-16 09:55:12.093: DEBUG/Database(224): exception during rollback, maybe the DB previously performed an auto-rollback
How I fixed it:
I followed your advice, just remove a "db.close" instruction I added after
db.execSQL("CREATE TABLE .... in my onCreate procedure and i worked perfect.
Remove the db.close() in the method onCreate
#Override
public void onCreate(SQLiteDatabase db)
Don't call SQLiteDatabas# close();

Error Creating Table on Android

I'm trying to create a table in android database, but when i try to run the application the LogCat returns the following error:
08-22 02:39:29.098: ERROR/AndroidRuntime(277): Caused by: android.database.sqlite.SQLiteException: near "auto_increment": syntax error: CREATE TABLE words(id INTEGER PRIMARY KEY, word TEXT, count INTEGER not null auto_increment)
The code for this error is this:
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, word TEXT, count INTEGER not null auto_increment)");
}
And there is a error on this line too, the one between arrows:
public DataHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
-->this.db = openHelper.getWritableDatabase();<--
this.insertStmt = this.db.compileStatement(INSERT);
this.updateStmt = this.db.compileStatement(UPDATE);
}
Ps: The codes before is from DataHelper class.
and erro at this line (the logcat just say the line of the class, dont say the error):
this.dh = new DataHelper(this);
Ps: DataHelper is the class that manage the database.
Change auto_increment to autoincrement and you should be good. Simple syntax error :)
There are two problems in count INTEGER not null auto_increment
as mentioned by smith324, auto_increment is spelled wrong
more importantly, count has to be primary key, if you want to have it auto-increment by sqlite rules.

Categories

Resources