Storing Lists to A Database, and Retrieving Them All Together : Android
I want to store a list of strings, and then retrieve them. How would I 开发者_运维百科do this using a database?
Ideally the way to approach this from a structured way to have your main activity/service interact with a Utility class that directly communicates with the database instead of the activity/service it self.
By doing this you modularize the process making its a lot easier to handle than doing it all in one class. Specifically the flow would follow this
Activity/Service -> Database Utility Class -> Database
The activity gets database results through the utility class. You could have all your database functionality like adding, subtracting, editing of records in the utility class.
Specifically you need to look into SQLiteOpenHelper
public class myDatabaseOpenHelper extends SQLiteOpenHelper {
public myDatabaseOpenHelper(Context context) {
super(context, (Database Name), null, (Database Version));
}
@Override
public void onCreate(SQLiteDatabase db) {
// create event database & category database
db.execSQL([TableCreationStatementHere]);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
One thing to mention is first create your tables on paper, and setup the relations and column names that you want and then build a statement like this:
public static String CREATE_EVENTDATABASE = "CREATE TABLE " + TABLE_EVENTS
+ " ( " + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_NAME + " TEXT, "
+ COL_DATE + " TEXT NOT NULL, "
+ COL_TIME + " TEXT NOT NULL, "
+ COL_DATETIME + " TEXT, "
+ COL_IMAGE + " TEXT, "
+ COL_NOTE + " TEXT, "
+ COL_REPEAT + " INTEGER, "
+ COL_REPEAT_INTERVAL + " INTEGER, "
+ COL_REMINDER + " INTEGER, "
+ COL_CATEGORY + " TEXT, "
+ COL_FLAG + " INTEGER )";
Then after you have created your table, then just grab a handle to your database like so:
myDatabaseOpenHelper helper = new myDatabaseOpenHelper(getApplicationContext());
SQLiteDatabase database = helper.getWritableDatabase()
This line will return you a link to your database, where you can query, delete, update as necessary!
精彩评论