(near "null": syntax error (code 1): , while compiling: INSERT INTO null - java

I am trying to save data into a database, but it seems that the onCreate method is not run. Might be this might be another problem but the logcat
12-01 01:22:41.785 19724-19724/com.example.user.timetable_test E/SQLiteLog: (1) near "null": syntax error
12-01 01:22:41.795 19724-19724/com.example.user.timetable_test E/SQLiteDatabase: Error inserting _length=1 _name=Break
android.database.sqlite.SQLiteException: near "null": syntax error (code 1): , while compiling: INSERT INTO null(_length,_name) VALUES (?,?)
#################################################################
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(near "null": syntax error (code 1): , while compiling: INSERT INTO null(_length,_name) VALUES (?,?))
#################################################################
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1058)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:623)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1607)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1479)
at com.example.user.timetable_test.setup.TableDBHandler.addEntry(TableDBHandler.java:79)
at com.example.user.timetable_test.setup.SetTable$PlaceholderFragment$1.onClick(SetTable.java:227)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10826)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7225)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
The SQLite class is:
package com.example.user.timetable_test.setup;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.user.timetable_test.MiscData;
public class TableDBHandler extends SQLiteOpenHelper{
private MiscData data = MiscData.getInstance();
private static int DATABASE_VERSION = 1;
private static String DATABASE_NAME = "Timetable.db";
private static String[] TABLE_DAY = new String[MiscData.getInstance().getDays()];
private static String COLUMN_SESSION_NUM = "_id";
private static String COLUMN_NAME = "_name";
private static String COLUMN_LENGTH = "_length";
private SQLiteDatabase db;
public TableDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory,
int version){
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
db = getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase){
Log.i("SQL", "DB Created");
for(int i = 0; i < data.getDays(); i++){
TABLE_DAY[i] = data.getDay(i + data.getFirstDay());
}
for(int i = 0; i < data.getDays(); i++){
String query = "CREATE TABLE " + TABLE_DAY[i] + "(" + COLUMN_SESSION_NUM +
" INTEGER PRIMARY KEY ," + COLUMN_NAME + " TEXT," +
COLUMN_LENGTH + " INTEGER " + ");";
sqLiteDatabase.execSQL(query);
}
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1){
Log.i("SQL", "DB updated");
for(int j = 0; j < data.getDays(); j++){
TABLE_DAY[j] = data.getDay(j + data.getFirstDay());
sqLiteDatabase.execSQL("DROP TABLE EXISTS " + TABLE_DAY[j]);
}
onCreate(sqLiteDatabase);
}
public void addEntry(int day, String name, int length){
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, name);
values.put(COLUMN_LENGTH, length);
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_DAY[day], null, values);
db.close();
}
}
I am using an array to create a dynamic number of tables.
The log message in the onCreate method doesn't show up in the logcat, I checked a lot.
Calling the addEntry method:
tableDBHandler.addEntry(page, sessionSpinners[i].getSelectedItem().toString(), Integer.parseInt(lengthText[i].getText().toString()));
If I changed the DATABASE_VERSION from 1 the onUpgrade method is called, but if the version was 1 I cannot see the message from onCreat, in the logcat.
Shouldn't this class create a .db file? Because after clicking the button, and running the method, I can't see any files in the app's folder.

INSERT INTO null - the table name is null. It comes from the TABLE_DAY array you initialize in your SQLite helper onCreate(). But onCreate() is only invoked when the database file is created, not each time you open your database.
You could move the TABLE_DAY init from onCreate() to e.g. constructor.
I am using an array to create a dynamic number of tables.
If the TABLE_DAY array is really dynamic, you're in much more trouble. Consider redesigning your database schema so that the tables are static but the content can be dynamic.

Related

My app keep stopping after i added data base code - Android Studio

I don't know what is the problem of my database, my app keep stopping after i added the data base code.
Please can you help with to fix that.
I have tried many times to figure it out but still not getting anywhere.
This is my data base code :
public class databaseOpenHelper extends SQLiteOpenHelper{
// Country table name
private static final String TABLE_NAME= "contacts";
// Country Table Columns names
private static final String KEY_ID = "id";
private static final String NAME = "Name";
private static final String PHONENO = "PhoneNo";
public databaseOpenHelper(Context context){
super(context,"Login.db",null,1);
}
#Override
public void onCreate(SQLiteDatabase myDB) {
myDB.execSQL("create Table users(username Text primary key,password Text)");
// create the table for the first time
String CREATE_COUNTRY_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + NAME + " TEXT,"
+ PHONENO + " TEXT" + ")";
myDB.execSQL(CREATE_COUNTRY_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase myDB, int i, int i1) {
myDB.execSQL("drop Table if exists users");
}
public Boolean isertData(String username,String password){
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("username",username);
contentValues.put("password",password);
long result = myDB.insert("users",null,contentValues);
if(result == -1){
return false;
}
else {
return true;
}
}
public Boolean checkusername(String username){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ?",new String[] {username});
if (cursor.getCount()>0){
return true;
}
else {
return false;
}
}
public Boolean checkusernamePassword(String username,String password){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ? and password = ?",new String[] {username,password});
if (cursor.getCount()>0){
return true;
}
else{
return false;
}
}
// method to add the contact
public void addcontact(ContactModel contact){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues c=new ContentValues();
c.put(NAME,contact.getName());
c.put(PHONENO,contact.getPhoneNo());
db.insert(TABLE_NAME,null,c);
db.close();
}
// method to retrieve all the contacts in List
public List<ContactModel> getAllContacts(){
List<ContactModel> list=new ArrayList<>();
String query="SELECT * FROM "+TABLE_NAME;
SQLiteDatabase db=this.getReadableDatabase();
Cursor c=db.rawQuery(query,null);
if(c.moveToFirst()) {
do {
list.add(new ContactModel(c.getInt(0),c.getString(1),c.getString(2)));
} while (c.moveToNext());
}
return list;
}
// get the count of data, this will allow user
// to not add more that five contacts in database
public int count(){
int count=0;
String query="SELECT COUNT(*) FROM "+TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c=db.rawQuery(query,null);
if(c.getCount()>0){
c.moveToFirst();
count=c.getInt(0);
}
c.close();
return count;
}
// Deleting single country
public void deleteContact(ContactModel contact) {
SQLiteDatabase db = this.getWritableDatabase();
int i=db.delete(TABLE_NAME,KEY_ID + " = ?",
new String[] { String.valueOf(contact.getId()) });
db.close();
}
}
And this is my logcat :
FATAL EXCEPTION: main
Process: com.example.localisation, PID: 11700
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.localisation/com.example.localisation.phone}: android.database.sqlite.SQLiteException: no such table: contacts (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM contacts
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3635)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: android.database.sqlite.SQLiteException: no such table: contacts (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM contacts
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1047)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:654)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:590)
at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:62)
at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1546)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1485)
at com.example.localisation.databaseOpenHelper.getAllContacts(databaseOpenHelper.java:108)
at com.example.localisation.phone.onCreate(phone.java:81)
at android.app.Activity.performCreate(Activity.java:8051)
at android.app.Activity.performCreate(Activity.java:8031)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3608)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loopOnce(Looper.java:201) 
at android.os.Looper.loop(Looper.java:288) 
at android.app.ActivityThread.main(ActivityThread.java:7839) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 
The failure is saying that there is not a table called contacts as per
Caused by: android.database.sqlite.SQLiteException: no such table: contacts (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM contacts
Running your code and then using the errant getAllContacts method, as indicated in the log by:-
at com.example.localisation.databaseOpenHelper.getAllContacts(databaseOpenHelper.java:108)
Works.
As such it is highly likely that you have added the contacts cable after previously running the App and that this has created the database. The database persists and thus will still exist from on run to the other. As such the onCreate method will not be called, as it is only called once when the database is created.
The easy fix is to uninstall the App and rerun. However, this will delete any existing data.
If you need to keep any data then you should a) increase the version number and then b) add code to the onUpgrade method to create the new table (same code).
For example:-
a)
public databaseOpenHelper(Context context){
super(context,"Login.db",null,2 /*<<<<<<<<<< CHANGED */);
}
b)
#Override
public void onUpgrade(SQLiteDatabase myDB, int i, int i1) {
//myDB.execSQL("drop Table if exists users");
if (i1 == 2) {
String CREATE_COUNTRY_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + NAME + " TEXT,"
+ PHONENO + " TEXT" + ")";
myDB.execSQL(CREATE_COUNTRY_TABLE);
}
}
You can the see that the contacts table has been created by using App Inspection e.g.
according to the error code you uploaded i noticed this SELECT * FROM contacts which means that you don't have table named contacts in you sqlite database so i recommend you, for testing you should use sqlite browser to create database and add data to it and then use it in your android studio project. if you get any problem fearther don't hesitate to ask it in comments thanks.

Android - What value is returned by the insert convenience method for a WITHOUT ROWID table?

Note This Question is intended to be a share your knowledge, Q&A-style.
SQLite by default creates a hidden column namely rowid which will be assigned a unique 64 bit signed integer value.
However, since SQLite version 3.8.2, SQLite has supported the WITHOUT ROWID clause, which results in the rowid being omitted.
What would the result be, assuming a successful insert?
i.e. the long returned from the SQLiteDatabase insert family (insert, insertOrThrow and insertWithOnConflict) as per :-
the row ID of the newly inserted row, or -1 if an error occurred
SQLiteDatabase - insert
As SQLite version 3.8.2 or greater is only available since API 21 Lollilop, then WITHOUT ROWID can only be used from API 21 on.
(caveat Some device manufacturers include different versions of SQLite on their devices.android.database.sqlite)
Prior to API 21 coding WITHOUT ROWID would result in a syntax error, so a result would not be possible as such a table cannot exist.
Since API 21 then the result is that 0 is returned, if the insert worked else -1.
However, that is just assuming a simple case of a single table or multiple WITHOUT ROWID tables (i.e. no ROWID tables).
Adding ROWID tables into the mix, which would be the more likely scenario, then the result is as per the previous time, since the database was opened, that a result was set (as per SQLite rather than the Android SDK) or -1.
In short, the value if not -1, indicates that a row was inserted (very likely), -1 would typically indicate that the row was not inserted.
caveat if you force a rowid to be -1 (supply -1 for the rowid column directly or via an alias) then a result of -1 could be returned, even though the row was inserted.
Example
The following demonstrates the creation of a database with a single WITHOUT ROWID table, in which two rows are inserted and the result is output to the log. A subclass of SQLiteOpenHelper is used as this appears to be the more common means of accessing SQLite Database.
DBHelperNoRowid.java (Database Helper)
public class DBHelperNoRowid extends SQLiteOpenHelper {
public final static String DB = "test_norowid";
public static final int VERSION = 1;
public static final String TBL_NOROWID = "norowid";
public static final String COL_ID = BaseColumns._ID;
public static final String COL_MYDATA = "mydata";
SQLiteDatabase mDB;
public DBHelperNoRowid(Context context) {
super(context, DB, null, VERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_norowid_table = "CREATE TABLE IF NOT EXISTS " + TBL_NOROWID + "(" +
COL_ID + " INTEGER PRIMARY KEY, " +
COL_MYDATA + " TEXT" +
") WITHOUT ROWID"; //<<<<<<<<<<
db.execSQL(crt_norowid_table);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long insertUsingConvenienceInsert(long not_an_id, String text) {
ContentValues cv = new ContentValues();
cv.put(COL_ID,not_an_id);
cv.put(COL_MYDATA,text);
return mDB.insert(TBL_NOROWID,null,cv);
}
}
MainActivty.java
public class MainActivity extends AppCompatActivity {
DBHelperNoRowid mDBhlpr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDBhlpr = new DBHelperNoRowid(this);
logInsertResult(2100L,"row 1");
logInsertResult(-898765432,"row 2");
}
private void logInsertResult(long not_an_id, String text) {
Log.d("INSERTRESULT","Insertion of a row returned " + String.valueOf(
mDBhlpr.insertUsingConvenienceInsert(not_an_id,text)
));
}
}
Result
2019-01-23 17:36:04.029 24175-24175/so.uru D/INSERTRESULT: Insertion of a row returned 0
2019-01-23 17:36:04.029 24175-24175/so.uru D/INSERTRESULT: Insertion of a row returned 0
Second run
Running the above will result in the UNIQUE constraint conflict, which will be trapped by the insert method, and then -1 will be returned e.g. :-
2019-01-23 19:49:51.915 24876-24876/so.uru E/SQLiteDatabase: Error inserting _id=2100 mydata=row 1
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: norowid._id (code 1555 SQLITE_CONSTRAINT_PRIMARYKEY)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:796)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1564)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
at so.uru.DBHelperNoRowid.insertUsingConvenienceInsert(DBHelperNoRowid.java:42)
at so.uru.MainActivity.logInsertResult(MainActivity.java:23)
at so.uru.MainActivity.onCreate(MainActivity.java:16)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2019-01-23 19:49:51.916 24876-24876/so.uru D/INSERTRESULT: Insertion of a row returned -1
2019-01-23 19:49:51.918 24876-24876/so.uru E/SQLiteDatabase: Error inserting _id=-898765432 mydata=row 2
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: norowid._id (code 1555 SQLITE_CONSTRAINT_PRIMARYKEY)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:796)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1564)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
at so.uru.DBHelperNoRowid.insertUsingConvenienceInsert(DBHelperNoRowid.java:42)
at so.uru.MainActivity.logInsertResult(MainActivity.java:23)
at so.uru.MainActivity.onCreate(MainActivity.java:17)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2019-01-23 19:49:51.918 24876-24876/so.uru D/INSERTRESULT: Insertion of a row returned -1
Code used for testing a mix of rowid and without tables
Note the following is just one of the multiple permutations used for testing:-
DBHelperBoRowid.java
public class DBHelperNoRowid extends SQLiteOpenHelper {
public final static String DB = "test_norowid";
public static final int VERSION = 1;
public static final String TBL_NOROWID = "norowid";
public static final String COL_ID = BaseColumns._ID;
public static final String COL_MYDATA = "mydata";
public static final String TBL_WITHROWID = "withrowid";
SQLiteDatabase mDB;
public DBHelperNoRowid(Context context) {
super(context, DB, null, VERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_norowid_table = "CREATE TABLE IF NOT EXISTS " + TBL_NOROWID + "(" +
COL_ID + " INTEGER PRIMARY KEY, " +
COL_MYDATA + " TEXT" +
") WITHOUT ROWID";
db.execSQL(crt_norowid_table);
String crt_withrowid_table = "CREATE TABLE IF NOT EXISTS " + TBL_WITHROWID + "(" +
COL_ID + " INTEGER PRIMARY KEY, " +
COL_MYDATA + " TEXT" +
")";
db.execSQL(crt_withrowid_table);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long insertUsingConvenienceInsert(long not_an_id, String text, boolean without_rowid, boolean generate_rowid) {
ContentValues cv = new ContentValues();
String table = TBL_WITHROWID;
if (without_rowid) {
table = TBL_NOROWID;
cv.put(COL_ID,not_an_id);
} else {
if (generate_rowid) {
cv.put(COL_ID,not_an_id);
}
}
cv.put(COL_MYDATA,text);
return mDB.insert(table,null,cv);
}
public void logLastInsertId() {
Cursor csr = mDB.rawQuery("SELECT last_insert_rowid()",null);
if (csr.moveToFirst()) {
Log.d("LASTINSERTEDROWID","The Last RowID inserted was " + String.valueOf(csr.getLong(0)));
} else {
Log.d("LASTINSERTEDROWID","Ooops there does not appear to have been a row inserted");
}
}
}
MainActivity.java (as per the last permutation used)
public class MainActivity extends AppCompatActivity {
DBHelperNoRowid mDBhlpr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDBhlpr = new DBHelperNoRowid(this);
// Insert some rows into the table that is a rowid table
logInsertResult(1,"row 1",false,false);
logInsertResult(1,"row 1",false,false);
logInsertResult(1,"row 1",false,false);
logInsertResult(1,"row 1",false,false);
logInsertResult(-1,"row 1",false,true);
logInsertResult(2100L,"row 1",true,true); //<<<<<<<<<< WITHOUT
logInsertResult(1,"row 1",false,false);
logInsertResult(1,"row 1",false,false);
logInsertResult(1,"row 1",false,false);
logInsertResult(-898765432,"row 2",true,true); //<<<<<<<<<< WITHOUT
logInsertResult(1,"row 1",false,false);
logInsertResult(1,"row 1",false,false);
logInsertResult(1,"row 1",false,false);
logInsertResult(1,"row 1",false,false);
logInsertResult(-1L,"3rd row",true,true); //<<<<<<<<<< WITHOUT
}
private void logInsertResult(long no_an_id, String text, boolean without_rowid, boolean generate_rowid) {
if (without_rowid) {
Log.d("INSERTRESULT",">>>>>>>>>> WITHOUT ROWID ATTEMPT");
}
Log.d("INSERTRESULT","Insertion of a row returned " + String.valueOf(
mDBhlpr.insertUsingConvenienceInsert(no_an_id,text,without_rowid,generate_rowid)
));
mDBhlpr.logLastInsertId(); //
}
}

sqlite for android, how to update table

I found a number of links on stack overflow dealing with this but none of the solutions have worked for me so here goes:
I am trying to add a column to hold a date (and may need to add a time column in future) but am having some trouble since the table had already been created. Here is the database code:
public class MyDatabase {
public static final String KEY_ROWID = "_id";
public static final String KEY_DATE = "Date";
public static final String KEY_SYS = "Systolic";
public static final String KEY_DIA = "Diastolic";
private static final String DATABASE_NAME = "Blood Pressures";//Used to reference database
private static final String DATABASE_TABLE = "bloodPressureTable";//Tables can be stored in database
// this will be used to store ID, date, systolic and diastolic
private static final int DATABASE_VERSION = 9;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public String getData() {
String[] columns = new String[]{KEY_ROWID, KEY_SYS, KEY_DIA};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iSys = c.getColumnIndex(KEY_SYS);
int iDia = c.getColumnIndex(KEY_DIA);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { //if cursor is after position of our last entry, then stop
result = result + c.getString(iRow) + //get ROW_ID column, get name of first row and hotness, create new string
" " + c.getString(iSys) + " " +
c.getString(iDia) + "\n";
}
return result;
}
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) { //This is only called when we first create a database
// when then we will just cycle through onUpgrade, passes a database in
db.execSQL(
"CREATE TABLE " + DATABASE_TABLE + " (" + //create a table called table name
//adds columns inside parenthesise
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + //integer increment automatically, referenced by keyID
KEY_DATE + "TEXT NOT NULL, " + //SQL uses the word text rather than string
KEY_SYS + " INTEGER, " +
KEY_DIA + " INTEGER);"
);
}
#Override //called if oncreate has already been called
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE); //If table name exists it is going
// to drop it and then all we have to do is call our onCreate method
//Removes table added by create table statement
//onCreate(db);
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE " + DATABASE_TABLE +
" ADD COLUMN " + KEY_DATE + " TEXT NOT NULL, ");
}
}
}
//Constructor below
public MyDatabase(Context c) {
ourContext = c;
}
//open() allows us to open and write to database
public MyDatabase open() {
ourHelper = new DbHelper(ourContext); // this is a new instance of that object passing in the context
ourDatabase = ourHelper.getWritableDatabase();//here we set up our database,
// getting the writeable database. This will open up our database through our helper
return this;
}
public void close() {
ourHelper.close(); //close our SQLiteOpenHelper
}
public long createEntry(int systolic, int diastolic) {
ContentValues cv = new ContentValues();
Calendar c = Calendar.getInstance();
String s = Integer.toString(c.get(Calendar.DAY_OF_MONTH)) + "/" + Integer.toString(c.get(Calendar.MONTH)) +
"/" + Integer.toString(c.get(Calendar.YEAR));
cv.put(KEY_DATE, s);
cv.put(KEY_SYS, systolic);
cv.put(KEY_DIA, diastolic);//Put the string in KEY_NAME column?
return ourDatabase.insert(DATABASE_TABLE, null, cv); //we want this method to return this line
}
}
Can someone advise me of a solution please? As you can see I have tried two different methods (one is commented out in onUpgrade). As you can see I am on version 10 from playing about with it already!
Here is the logcat:
03-02 16:03:48.416 1811-1811/com.dissertation.michael.biolog E/SQLiteLog﹕ (1) Cannot add a NOT NULL column with default value NULL
03-02 16:03:48.416 1811-1811/com.dissertation.michael.biolog D/AndroidRuntime﹕ Shutting down VM
03-02 16:03:48.416 1811-1811/com.dissertation.michael.biolog W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41696bd8)
03-02 16:03:48.416 1811-1811/com.dissertation.michael.biolog E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.dissertation.michael.biolog, PID: 1811
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1111, result=-1, data=Intent { (has extras) }} to activity {com.dissertation.michael.biolog/com.dissertation.michael.biolog.MainActivity}: android.database.sqlite.SQLiteException: Cannot add a NOT NULL column with default value NULL (code 1): , while compiling: ALTER TABLE bloodPressureTable ADD COLUMN DateTEXT NOT NULL
at android.app.ActivityThread.deliverResults(ActivityThread.java:3391)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3434)
at android.app.ActivityThread.access$1300(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5045)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: Cannot add a NOT NULL column with default value NULL (code 1): , while compiling: ALTER TABLE bloodPressureTable ADD COLUMN DateTEXT NOT NULL
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1672)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1603)
at com.dissertation.michael.biolog.MyDatabase$DbHelper.onUpgrade(MyDatabase.java:75)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:257)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.dissertation.michael.biolog.MyDatabase.open(MyDatabase.java:90)
at com.dissertation.michael.biolog.MainActivity.onActivityResult(MainActivity.java:170)
at android.app.Activity.dispatchActivityResult(Activity.java:5430)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3387)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3434)
at android.app.ActivityThread.access$1300(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5045)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
at dalvik.system.NativeStart.main(Native Method)
03-02 16:03:48.424 1811-1811/com.dissertation.michael.biolog I/Process: Sending signal. PID: 1811 SIG: 9
Alternatively (and preferably if it is simple) a method to delete my table entirely so that version 1 is created again would be ideal. (No useful data has been entered into the database at this point)... Cheers!
Your application is crashing due to java.lang.NumberFormatException: Invalid int: "300-400", it means you are passing invalid format of INTEGER and 300-400 is not a valid int.
P.S. If you want to enter 300-400 into db column use TEXT or VARCHAR(15) as Datatype of your column

SQLite Database wont compile correctly?

I am creating an android app which monitors attendance, although I am getting errors when I attempt to login with a users details from the sqlite database saying a column doesnt exist.
DBHelper.class
package uk.ac.qub.qubattend;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 6;
// Database Name
private static final String DATABASE_NAME = "QUBAttendanceDB";
// tasks table name
private static final String TABLE_StudentInfo = "studentinfo";
// Table Columns names
// id column
private static final String KEY_ID = "StudentId";
// question column
private static final String KEY_PASS = "password";
// answer column
private static final String KEY_WEEK1 = "Week1";
private static final String KEY_WEEK2 = "Week2";
private static final String KEY_WEEK3 = "Week3";
private static final String KEY_WEEK4 = "Week4";
private static final String KEY_WEEK5 = "Week5";
private static final String KEY_WEEK6 = "Week6";
private static final String KEY_WEEK7 = "Week7";
private static final String KEY_WEEK8 = "Week8";
private static final String KEY_WEEK9 = "Week9";
private static final String KEY_WEEK10 = "Week10";
private static final String KEY_WEEK11 = "Week11";
private static final String KEY_WEEK12 = "Week12";
// Database constant
private SQLiteDatabase dbase;
/**
* Method to check the db name and version
*
* #param context
*/
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
dbase = db;
// Create Table method
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_StudentInfo + " ( "
+ KEY_ID + " TEXT," + KEY_PASS + " TEXT, " + KEY_WEEK1
+ "TEXT, " + KEY_WEEK2 + "TEXT, " + KEY_WEEK3 + "TEXT, "
+ KEY_WEEK4 + "TEXT, " + KEY_WEEK5 + "TEXT, " + KEY_WEEK6
+ "TEXT, " + KEY_WEEK7 + "TEXT, " + KEY_WEEK8 + "TEXT, "
+ KEY_WEEK9 + "TEXT, " + KEY_WEEK10 + "TEXT, " + KEY_WEEK11
+ "TEXT, " + KEY_WEEK12 + "TEXT" + ")";
db.execSQL(sql);
// implementing add questions method
addAttendance();
}
/**
* Add Questions Method using Question Object with question, 4 options and
* correct answer
*/
private void addAttendance() {
Student s1 = new Student("40023798", "letmeinhere", "90", "80", "0",
"0", "0", "0", "0", "0", "0", "0", "0", "0");
this.addStudent(s1);
}
// Checking that existing database table called TABLE_QUEST is dropped
#Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_StudentInfo);
// Create tables again
onCreate(db);
}
/**
* method for adding a new question into the database
*
* #param quest
*/
public void addStudent(Student student) {
ContentValues values = new ContentValues();
values.put(KEY_ID, student.getStudentId());
values.put(KEY_PASS, student.getPassword());
values.put(KEY_WEEK1, student.getWeek1());
values.put(KEY_WEEK2, student.getWeek2());
values.put(KEY_WEEK3, student.getWeek3());
values.put(KEY_WEEK4, student.getWeek4());
values.put(KEY_WEEK5, student.getWeek5());
values.put(KEY_WEEK6, student.getWeek6());
values.put(KEY_WEEK7, student.getWeek7());
values.put(KEY_WEEK8, student.getWeek8());
values.put(KEY_WEEK9, student.getWeek9());
values.put(KEY_WEEK10, student.getWeek10());
values.put(KEY_WEEK11, student.getWeek11());
values.put(KEY_WEEK12, student.getWeek12());
// Inserting Row with question
dbase.insert(TABLE_StudentInfo, null, values);
}
/**
* Method to move questions in database to an ArrayList
*
* #return
*/
public ArrayList<Student> getAllStudents() {
ArrayList<Student> studentList = new ArrayList<Student>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_StudentInfo;
dbase = this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Student student = new Student();
student.setStudentId(cursor.getString(0));
student.setPassword(cursor.getString(1));
student.setWeek1(cursor.getString(2));
student.setWeek2(cursor.getString(3));
student.setWeek3(cursor.getString(4));
student.setWeek4(cursor.getString(5));
student.setWeek5(cursor.getString(6));
student.setWeek6(cursor.getString(7));
student.setWeek7(cursor.getString(8));
student.setWeek8(cursor.getString(9));
student.setWeek9(cursor.getString(10));
student.setWeek10(cursor.getString(11));
student.setWeek11(cursor.getString(12));
student.setWeek12(cursor.getString(13));
studentList.add(student);
} while (cursor.moveToNext());
}
// return question list
return studentList;
}
/**
* Method to Check Database number of rows
*
* #return
*/
public int rowcount() {
int row = 0;
// select all query
String selectQuery = "SELECT * FROM " + TABLE_StudentInfo;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
row = cursor.getCount();
return row;
}
}
Below is the log which displays the error but I dont know why its throwing the error :
01-17 16:26:51.616: E/SQLiteLog(1667): (1) table studentinfo has no column named Week8
01-17 16:26:51.656: E/SQLiteDatabase(1667): Error inserting StudentId=40023798 Week8=0 Week9=0 Week4=0 Week5=0 password=letmeinhere Week6=0 Week7=0 Week3=0 Week2=80 Week12=0 Week1=90 Week11=0 Week10=0
01-17 16:26:51.656: E/SQLiteDatabase(1667): android.database.sqlite.SQLiteException: table studentinfo has no column named Week8 (code 1): , while compiling: INSERT INTO studentinfo(StudentId,Week8,Week9,Week4,Week5,password,Week6,Week7,Week3,Week2,Week12,Week1,Week11,Week10) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1467)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at uk.ac.qub.qubattend.DBHelper.addStudent(DBHelper.java:109)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at uk.ac.qub.qubattend.DBHelper.addAttendance(DBHelper.java:73)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at uk.ac.qub.qubattend.DBHelper.onCreate(DBHelper.java:62)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at uk.ac.qub.qubattend.DBHelper.onUpgrade(DBHelper.java:83)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:257)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
If anyone knows why it is not picking up column 8 I would really appreciate it!
All of the KEY_WEEK... values have "TEXT, " appended after them, not " TEXT, ", and so your column and datatype names should be running together.
You may be better served either using StringBuilder (faster) or String.format() (easier to read), rather than string concatenation.

Android getting Error inserting to databse and code 19: constraint failed

i'm wrote simple DataBaseHelper to use SQlite in android. after create class as :
public class DatabaseHandler extends SQLiteOpenHelper{
private static String DB_PATH = "";
private static final String DATABASE_NAME = "tsms";
private static String RECEIVE_FIELDS_TABLE = "ReceiveFields";
private static final String COLUMN_ID = "id";
private static final String COLUMN_LASTID = "lastId";
private static final String COLUMN_SMSNUMBER = "smsNumber";
private static final String COLUMN_MOBILENUMBER = "mobileNumber";
private static final String COLUMN_SENDERNAME = "senderName";
private static final String COLUMN_SMSBODY = "smsBody";
private static final String COLUMN_RECEIVEDATE = "receiveDate";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase mDataBase;
/* UPDATE DATABASE_CREATE FIELD*/
private static final String DATABASE_CREATE = "CREATE TABLE " + RECEIVE_FIELDS_TABLE + "("
+ COLUMN_ID + " INTEGER UNIQUE , "
+ COLUMN_LASTID + " INTEGER UNIQUE , "
+ COLUMN_SMSNUMBER + " VARCHAR UNIQUE , "
+ COLUMN_MOBILENUMBER + " VARCHAR , "
+ COLUMN_SENDERNAME + " VARCHAR , "
+ COLUMN_SMSBODY + " TEXT , "
+ COLUMN_RECEIVEDATE + " VARCHAR , PRIMARY KEY (" + COLUMN_ID + ", " + COLUMN_LASTID + ", " + "))";
private Context context;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + RECEIVE_FIELDS_TABLE);
// Create tables again
onCreate(sqLiteDatabase);
}
// Adding new fields
public void addToReceived(ReceiveFields fields) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_LASTID, fields.getLastId()); // ReceiveFields last ID
values.put(COLUMN_MOBILENUMBER, fields.getMobileNumber()); // ReceiveFields Mobile Number
values.put(COLUMN_SENDERNAME, fields.getSenderName()); // ReceiveFields Mobile Number
values.put(COLUMN_SMSBODY, fields.getSmsBody()); // ReceiveFields Mobile Number
values.put(COLUMN_SMSNUMBER, fields.getSmsNumber()); // ReceiveFields Mobile Number
values.put(COLUMN_MOBILENUMBER, fields.getMobileNumber()); // ReceiveFields Mobile Number
values.put(COLUMN_RECEIVEDATE, String.valueOf(fields.getReceiveDate())); // ReceiveFields Mobile Number
// Inserting Row
db.insert(RECEIVE_FIELDS_TABLE, null, values);
db.close(); // Closing database connection
}
}
I get Error Inserting to database with this way:
db.addToReceived(new ReceiveFields(
Long.valueOf(str1[0]),
str1[1],
str1[2],
URLDecoder.decode(str1[3], "UTF-8"),
URLDecoder.decode(str1[4], "UTF-8"),
ct.getGregorianDate()));
Log.i Result:
29904757 30007227 00120504001 00120504001 sssasaS 2014/8/3
full LogCate Result:
08-28 06:35:29.974 2698-2698/ir.tsms E/Database﹕ Error inserting lastId=29904755 receiveDate=2014/8/3 senderName=09127574751 mobileNumber=09127574751 smsNumber=30007227 smsBody=
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:55)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1549)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1410)
at ir.tsms.DataBase.DatabaseHandler.addToReceived(DatabaseHandler.java:96)
at ir.tsms.wsdl.TSMS.getReceivedSMS(TSMS.java:141)
at ir.tsms.Receive.ResivedSMS.getResivedSMS(ResivedSMS.java:41)
at ir.tsms.Receive.ResivedSMS.<init>(ResivedSMS.java:36)
at ir.tsms.Activities.DashboardActivity.onTabSelected(DashboardActivity.java:160)
at android.support.v7.app.ActionBarImplBase.selectTab(ActionBarImplBase.java:486)
at android.support.v7.app.ActionBarImplBase.addTab(ActionBarImplBase.java:410)
at android.support.v7.app.ActionBarImplBase.addTab(ActionBarImplBase.java:401)
at ir.tsms.Activities.DashboardActivity.onCreate(DashboardActivity.java:68)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.access$2300(ActivityThread.java:125)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
at ir.tsms.wsdl.TSMS.getReceivedSMS(TSMS.java:141) line is :
db.addToReceived(new ReceiveFields(
Check these things, it may causes by these reason:
1- you did not add COLUMN_ID to values so it is null.
2-COLUMN_ID and COLUMN_LASTID are not UNIQUE (clear your database or android app data , maybe it stored in your db first time you ran it and now again you want to add you can not because it is not unique now, every time you run, your db is in memory and it is not clread, in order to clear it you must remove app data or run delete SQL statement)
so i suggest you to see your DB file, if you use eclipse try this:
http://www.tylerfrankenstein.com/browse-android-emulator-sqlite-database-eclipse
3-COLUMN_ID and COLUMN_LASTID are not int i mean fields.getLastId() may return String
check exactly your table defination and your values to insert !!!
It seems like you're trying to insert null as smsBody but your table does not allow you to do this as it has NOT NULL constraint for this column.

Categories