我是 Android 新手,我对 EditText 和 SQLite 有疑问。我想从 EditText 获取字符串,然后使用可点击按钮将其插入数据库......但我的代码不起作用。
这是我的代码:
Button savebtn, clearbtn;
EditText deatxt, numtxt;
public ArrayList<String> num_name, det_name;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
clearbtn = (Button) findViewById(R.id.clearbtn);
savebtn = (Button) findViewById(R.id.savebtn);
deatxt = (EditText) findViewById(R.id.deatxt);
numtxt = (EditText) findViewById(R.id.numtxt);
clearbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
deatxt.setText("");
numtxt.setText("");
savebtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(SarresidActivity.this, "saved!", Toast.LENGTH_LONG).show();
DatabaseManager mDatabaseManager = new DatabaseManager(SarresidActivity.this);
SQLiteDatabase mainDatabase = mDatabaseManager.getDatabase();
String deatxtstring = deatxt.getText().toString();
String numtxtstring = numtxt.getText().toString();
mainDatabase.execSQL("INSERT INTO tbl_name(num_name, det_name) VALUES ('" + numtxtstring + "','" + deatxtstring + "');");
Cursor mCursor = mainDatabase.rawQuery("SELECT * FROM tbl_name;", null);
num_name = new ArrayList<String>();
det_name = new ArrayList<String>();
if (mCursor.moveToFirst()) {
// SQL data
do {
num_name.add(mCursor.getString(mCursor.getColumnIndex("num_name")));
det_name.add(mCursor.getString(mCursor.getColumnIndex("det_name")));
}
while (mCursor.moveToNext());
}
mCursor.close();
mDatabaseManager.closeDatabase();
}
和 :
public class DatabaseManager {
public final static String DATABASE_NAME = "sarresid.db";
public final static String DATABASE_TABLE_NAME = "tbl_name";
private Context mContext;
private SQLiteDatabase mSQLiteDatabase;
public DatabaseManager(Context c) {
mContext = c;
init();
}
private void init() {
mSQLiteDatabase = mContext.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
mSQLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS "
+ " tbl_name (id INTEGER"
+ ", num_name number"
+ ", det_name VARCHAR"
+ ", PRIMARY KEY(id));");
}
public SQLiteDatabase getDatabase() {
return mSQLiteDatabase;
}
public void closeDatabase() {
if (mSQLiteDatabase != null)
mSQLiteDatabase.close();
}