如何从EditText获取字符串并将其插入到Android中的SQLite?

时间:2013-09-08 15:15:16

标签: android sqlite button android-edittext

我是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();
}

2 个答案:

答案 0 :(得分:1)

我还没有尝试过创建和访问SQLite数据库的方法。

我通常这样做的方法是创建一个扩展 SQLiteOpenHelper

的类

onCreate()方法中,您可以编写如下创建表sql语句: (常量是为了以后更容易访问,也有助于解决拼写错误)

private static final String TABLE_HOUSE = "house";
private static final String COLUMN_HOUSE_ID = "_id";
private static final String COLUMN_HOUSE_STREET = "street";

[...]

public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + TABLE_HOUSE + " (" 
        + COLUMN_HOUSE_ID + " integer primary key autoincrement, " 
        + COLUMN_HOUSE_STREET + " varchar(100))");
}

此外,您还需要自己创建插入或获取数据的方法。

public HouseCursor queryHouse() {
    Cursor wrapped = getReadableDatabase()
        .query(TABLE_HOUSE, null, null, null, null, null, null);
    return new HouseCursor(wrapped);
}

如果你想要的话。对您需要的结果进行分组或排序,以使用sql代码替换相应的null。 (查看here了解相关信息)

在我的示例中,我将结果放在CursorWrapper中,如果要在ListView中查看数据,可以将其放入CursorAdapter

public static class HouseCursor extends CursorWrapper {

    public HouseCursor(Cursor cursor) {
        super(cursor);
    }

    public House getHouse() {
    if (isBeforeFirst() || isAfterLast())
        return null;

        House h = new House();
        h.setId(getLong(getColumnIndex(COLUMN_HOUSE_ID)));
        h.setStreet(getString(getColumnIndex(COLUMN_HOUSE_STREET)));

        return h;
    }
}

可以通过这种方式插入数据

public long insertHouse(House h) {
    ContentValues cv = new ContentValues();
    cv.put(COLUMN_HOUSE_STREET, h.getStreet());

    return getWritableDatabase().insert(TABLE_HOUSE, null, cv);
}

我从中获取源代码的类和整个应用程序是here@github

答案 1 :(得分:0)

即使它试图插入,id参数

也是如此

注意:主键必须具有非空且唯一的值