如何将微调器中的选定值插入SQLite?

时间:2019-04-12 11:56:33

标签: java sqlite

美好的一天,

如何将从微调器中选择的值插入SQLite数据库? 我在strings.xml中创建了数组。然后在Activity.java中输入以下代码:

 spinner = (Spinner) findViewById(R.id.spinner2);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.Array2, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

然后(在活动中):

    Button AddHere;
    Spinner spinner;
    DataBase db;
    db = new DataBase(this);

    AddHere = (Button) findViewById(R.id.AddHere);

        AddHere.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String SpinnerEdit = spinner.getSelectedItem().toString();
                boolean isInserted = db.insert(SpinnerEdit);
                if (isInserted == true)
                    Toast.makeText(Activity.this, "Data Inserted", Toast.LENGTH_LONG).show();
                else
                    Toast.makeText(Activity.this, "Data NOT Inserted", Toast.LENGTH_LONG).show();
            }
        });

然后在DBHelper.java中:

public class DBHelper extends SQLiteOpenHelper {

public DBHelper(Context context) {
    super(context, "Testing.db" , null, 1); }

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("Create table Testing (Spinner text);");

}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL(" DROP TABLE IF EXISTS Testing");
    onCreate(db);
}
public boolean insert (String SpinnerEdit)
{
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put ("Category", SpinnerEdit);
    long ins = db.insert("Testing", null, contentValues);
    if (ins==-1) return false;
    else return true;
}}

但是“未插入数据”。问题在哪里以及如何解决?预先感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

此行:

contentValues.put ("Category", SpinnerEdit);

为列Category输入一个值,但您的表不包含该列。
在表的create语句中,只有1列名为Spinner