Inserting values from a textbox into SQLite database
I've created an Android application which requires the user to register his username and password. My question is, how can I insert the input values(textbox) into m开发者_高级运维y SQLite database?
Thanks in advance.
First, read Android docs on SQLite if you haven't already http://developer.android.com/guide/topics/data/data-storage.html#db.
Then assuming you have everything setup properly on the DB side the next step is to construct your SQL to look something like this...
private static final String INSERT_SQL = "insert into " + TABLE + " (username, password) " +
" values (?, ?)";
Then you need to actually do the insert...
public void doInsert(String username, String password) {
final SQLiteDatabase db = getWritableDatabase();
SQLiteStatement insert_stmt = null;
try {
insert_stmt = db.compileStatement(INSERT_SQL);
insert_stmt.bindString(1, username);
insert_stmt.bindString(2, password);
insert_stmt.executeInsert();
}
finally {
if (insert_stmt != null) insert_stmt.close();
}
}
This assumes doInsert is located in a class that extends SQLiteOpenHelper so that it can use getWritableDatabase, but as long as you have your SQLiteOpenHelper around you can move doInsert anywhere you like.
If you need to get values from an EditText then this should get you going...
final EditText input = (EditText) findViewById(R.id.textId);
final String txt = input.getText().toString();
精彩评论