I have following function in my service:
private void saveToDB(String sender, String message, String time) {
DBHandler db = new DBHandler(getApplicationContext(), sender);
db.insertOrCreateTable(sender, message, time);
}
This is my db handler class:
public class DBHandler extends SQLiteOpenHelper {
// All Static variables
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Mo";
private static String mSender;
private static final String KEY_ID = "id";
private static final String KEY_SENDER ="sender";
private static final String KEY_MSG = "msg";
private static final String KEY_TIME ="time";
//constructor
public DBHandler(Context context, String sender) {
//higher db version when user needs to create new table
super(context, DATABASE_NAME, null, DATABASE_VERSION);
SQLiteDatabase db = this.getWritableDatabase();
mSender = sender;
}
// Contacts table name
private static final String TABLE_MESSAGES = mSender;
private String CREATE_MESSAGES_TABLE = "Create Table " + TABLE_MESSAGES +
"("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_SENDER + " TEXT, "
+ KEY_MSG + " TEXT, "
+ KEY_TIME + " TEXT" + ")";
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_MESSAGES_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if exists
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MESSAGES);
onCreate(db);
}
public void insertOrCreateTable(String s,String m,String t) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_SENDER, s); // Message Sender
values.put(KEY_MSG, m); // Message Message
values.put(KEY_TIME, t); // Message Time
// Inserting Row
db.insert(mSender, null, values);
db.close();
}
}
Now, I try to create tables dynamically but it always returns an error:
E/SQLiteLog: (1) near "65": syntax error
03-09 12:03:13.813 20828-21609/com.example.asus.service E/SQLiteDatabase: Error inserting sender=65 time=12:03 msg=C
android.database.sqlite.SQLiteException: near "65": syntax error (
code 1): , while compiling: INSERT INTO 65(sender,time,msg) VALUES (?,?,?)
Any Ideas or suggestions? Also I posted this in a thread in a different way so feel free to look at it too (might help u understand my problem better) Here's the link: How do I dynamically add tables in android sqlite?
What am I doing wrong guys?
If your table has name
65
you should use' '
to insert. Instead of:INSERT INTO 65(sender,time,msg) VALUES (?,?,?)
try:
INSERT INTO '65'(sender,time,msg) VALUES (?,?,?)