简体   繁体   中英

android sqlite table name

my application may have more then one users on the same phone, and i want each user to have its own "ApplicationFriends" mysqlite table. when the name of the table is only "ApplicationFriends" everything works great. but when i'm trying to set the table name like this "ApplicationFriends2345" when 2345 is a uniqe user number, i always get an error when trying to run a select query, saying the table isn't exist.

this is my table creation code:

public DatabaseManager(Context context, String id) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    DatabaseManager.TABLE_APPLICATION_FRIENDS = TABLE_APPLICATION_FRIENDS_BASE + id;
}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_APPLICATIN_FRIENDS_TABLE = "CREATE TABLE IF NOT EXISTS "
            + TABLE_APPLICATION_FRIENDS + " (" + APPLICATION_FRIENDS_KEY_ID
            + " INTEGER PRIMARY KEY," + APPLICATION_FRIENDS_KEY_NAME
            + " TEXT" + ")";
    String CREATE_CHAT_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_Chat
            + " (" + CHAT_KEY_SENDER_ID + " INTEGER," + CHAT_KEY_MESSAGE
            + " TEXT," + CHAT_KEY_TIME + " DateTime" + ")";

    db.execSQL(CREATE_APPLICATIN_FRIENDS_TABLE);
    db.execSQL(CREATE_CHAT_TABLE);
}

SQLiteOpenHelper.onCreate(SQLiteDatabase) is only once called when the database is created. See http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html .

A better approach is to have only one "Application Friends" table. In the table add a column called UserId which stores the Id. Then when you write a query on the table you include UserId = '2345'. For Example: db.rawQuery("Select * from ApplicationFriends where userID = '2345'",null) . This will return all data for user with id = "2345"

You can do it the way you were trying to (with a table for each user). You just have to move the table creation code into a method other than the onCreate in your dbhelkper class, then call it as necessary (when you add a new user).

public void createFriendTable(String friendID) { 
    String CREATE_FRIEND_TABLE = "CREATE TABLE IF NOT EXISTS " 
            + friendID + " (" + APPLICATION_FRIENDS_KEY_ID 
            + " INTEGER PRIMARY KEY," + APPLICATION_FRIENDS_KEY_NAME 
            + " TEXT" + ")"; 
     db.execSQL(CREATE_FRIEND_TABLE); 
} 

Then wherever you need it:

mDbHelper.createFriendTable(friendID);

This is what I would do as it would make removing a user much easier. You would just drop their table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM