I'm trying to save data into a sqlite db, i have looked around but the strucutre for the helper is always this, i can't find out what's the problem. I don't get any exception, just is impossible write data into the db
public class DBhelper extends SQLiteOpenHelper {
private static final String QR_TABLE = "QR_TABLE";
private static final String ID = "COLUMN_ID";
private static final String C_TEXT = "COLUMN_TEXT";
private static final String C_DATE = "COLUMN_DATE";
private static final String DB_NAME = "qreader.db";
public DBhelper(Context context) {
super(context, DB_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableStatement = "CREATE TABLE " + QR_TABLE + " (" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + C_TEXT + " TEXT, "+ C_DATE + "TEXT)";
db.execSQL(createTableStatement);
}
public boolean addRow(String text, String date){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(C_TEXT, text);
cv.put(C_DATE, date);
long result = db.insert(QR_TABLE, null, cv);
db.close();
if(result == -1){
return false;
}
return true;
}
Here is the MainActivity file
public class MainActivity extends AppCompatActivity {
protected static TextView tvresult;
private DBhelper db;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(this, "NOT DELETED", Toast.LENGTH_SHORT).show();
db = new DBhelper(this);
Boolean res;
for(int i=0; i<30; i++){
res = db.addRow("Prova", "10");
if(res)
Log.w("myapp", "Added");
}
Log.w("App", db.getValues().toString());
...
On my log i see that the result from the getValues() is empty, so the database is not filled, and the "Added" message is never sent to the logcat.
Use insertOrThrow()
instead of insert()
to get a helpful exception message.
It likely says that COLUMN_DATE
does not exist, and the reason for that is a missing space in onCreate()
: C_DATE + "TEXT)"
should be C_DATE + " TEXT)"
. After adding the space you can uninstall your app to recreate the database file with the updated schema.