如何在EditText中使用用户输入更新我的微调器的字段

时间:2017-09-20 19:14:41

标签: android android-sqlite android-spinner crud

我有一个SQLite数据库正在填充我的Spinner。 "添加"它的功能很好!我想做的是当用户点击微调项目时,他可以更改以下字段并在数据库中更新

我的Spinner数据库

public class SpinnerDatabase extends SQLiteOpenHelper{
    private SQLiteDatabase db;

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "spinnerDB";
    private static final String TABLE_LABELS = "labels";
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";

    public SpinnerDatabase(Context context) {
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CATEGORIES_TABLES = "CREATE TABLE " +
                TABLE_LABELS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"+
                KEY_NAME + " TEXT)";
        db.execSQL(CREATE_CATEGORIES_TABLES);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
        onCreate(db);
    }

    public void insertLabel(String label){
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME,label);

        db.insert(TABLE_LABELS,null,values);
        db.close();
    }   
    public List<String> getAllLabels(){
        List<String> labels = new ArrayList<String>();
        String selectQuery = "SELECT * FROM "+ TABLE_LABELS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery,null);
        if (cursor.moveToFirst()){
            do{
                labels.add(cursor.getString(1));
            }while (cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return labels;
    }


    public void updateSpinner (int id, String label){
        ContentValues values;
        String where;

        db = this.getWritableDatabase();

        where = KEY_ID + " = " +id;

        values = new ContentValues();
        values.put(KEY_NAME,label);

        db.update(TABLE_LABELS,values,where,null);
        db.close();
    }
}

问题是当我点击按钮进行更新时,它没有做任何事情!只需更新其他项目(如果我有更多项目)。 这是我的片段中列​​出所有条目的方法:

 private void loadSpinnerData (){
        SpinnerDatabase db = new SpinnerDatabase(getActivity().getApplicationContext());

        List<String> labels = db.getAllLabels();

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),
                android.R.layout.simple_spinner_item,labels);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
    }

这里的按钮保存我尝试进行更新:

btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = editText.getText().toString();

                if(name.length()>0 && name != null){
                    int spinnerValue = spinner.getSelectedItemPosition();
                    SpinnerDatabase db = new SpinnerDatabase(getActivity().getApplicationContext());
                    db.updateSpinner(spinnerValue,name);
            }
        });

1 个答案:

答案 0 :(得分:0)

您的问题是,您使用Spinner的所选位置(0,1,2等)作为行的ID。第一行id为1,然后是2,等等( 可能但不是很明确,即由于某种原因删除行,并且序列中有间隙 )。

因此,您当前遇到的是行ID和微调器位置之间的差异为1,因此不会更新任何内容或正在更新其他行。

你需要使用一些方法来计算行id到spinner的位置(例如第二个数组,它具有第一个数组的相同索引的相应id),或者我要做的是,利用CursorAdpater的灵活性,例如SimpleCursorAdapter,然后使用spinner.getSelectedItemId()代替spinner.getSelectedItemPosition()

要使用A CursorAdapter,您需要一行名为 _id 的行(例如,将private static final String KEY_ID = "id";更改为public static final String KEY_ID = "_id";

请注意!我也建议如上所述更改private staticspublic statics

同样要使用CursorAdapter,您需要一个Cursor。 SpinnerDatabase.java中的以下方法就足够了。

public Cursor getAll() {
    db = this.getWritableDatabase();
    return db.query(TABLE_LABELS,null,null,null,null,null,null);
}

以下内容可用于设置adpater: -

    csr = dbhlpr.getAll();

    sca = new SimpleCursorAdapter(this,
            android.R.layout.simple_list_item_1,
            csr,
            new String[]{SpinnerDatabase.KEY_NAME},
            new int[]{android.R.id.text1},0);

    spinner.setAdapter(sca);

请注意!使用SpinnerDatabase.KEY_NAME,这就是为什么我建议公共静态&#39;而不是private static

SimpleCursorAdpater有一些小的差异;

  • 第3个参数是Cursor,
  • 4th 是要显示的游标中列名的String数组(应与第5个参数匹配),
  • 第五是数据放置的视图的ID (对于simple_list_item_1,如上所述使用1列名称和android.R.id.text1)< / em>的

当涉及到更新时,请使用 spinner.getSelectedItemId() 作为行ID。

工作示例(假设行有数据)

<强> SpinnerDatabase.java

public class SpinnerDatabase extends SQLiteOpenHelper {
    private SQLiteDatabase db;

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "spinnerDB";
    private static final String TABLE_LABELS = "labels";
    private static final String KEY_ID = "_id";
    public static final String KEY_NAME = "name";

    public SpinnerDatabase(Context context) {
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CATEGORIES_TABLES = "CREATE TABLE " +
                TABLE_LABELS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"+
                KEY_NAME + " TEXT)";
        db.execSQL(CREATE_CATEGORIES_TABLES);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
        onCreate(db);
    }

    public void insertLabel(String label){
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME,label);

        db.insert(TABLE_LABELS,null,values);
    }


    //Defunct
    public List<String> getAllLabels(){
        List<String> labels = new ArrayList<String>();
        String selectQuery = "SELECT * FROM "+ TABLE_LABELS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery,null);
        if (cursor.moveToFirst()){
            do{
                labels.add(cursor.getString(1));
            }while (cursor.moveToNext());
        }

        cursor.close();
        return labels;
    }


    public void updateSpinner (long id, String label){
        ContentValues values;
        String where;

        db = this.getWritableDatabase();

        where = KEY_ID + " = " +id;

        values = new ContentValues();
        values.put(KEY_NAME,label);

        db.update(TABLE_LABELS,values,where,null);
        db.close();
    }

    public Cursor getAll() {
        db = this.getWritableDatabase();
        return db.query(TABLE_LABELS,null,null,null,null,null,null);
    }
}

活动 SO46330096Activity.java

public class SO46330096Activity extends AppCompatActivity {

    SpinnerDatabase dbhlpr;
    Spinner spinner;
    Button editbutton;
    EditText spinneritem;
    SimpleCursorAdapter sca;
    Cursor csr;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_so46330096);
        spinner = (Spinner) findViewById(R.id.spinner);
        editbutton = (Button) findViewById(R.id.editbutton);
        spinneritem = (EditText) findViewById(R.id.spinnerinput);
        dbhlpr = new SpinnerDatabase(this);
        csr = dbhlpr.getAll();

        sca = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1,
                csr,
                new String[]{SpinnerDatabase.KEY_NAME},
                new int[]{android.R.id.text1},0);
        spinner.setAdapter(sca);

        editbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (spinneritem.getText().toString().length() > 0) {
                    dbhlpr.updateSpinner(spinner.getSelectedItemId(),spinneritem.getText().toString());
                    sca.swapCursor(csr = dbhlpr.getAll());
                }
            }
        });

    }
}

布局 activity_so46330096.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SO463300096 Activity"/>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            android:text="SPINNER ENTRY"
            />
        <EditText
            android:id="@+id/spinnerinput"
            android:layout_width="0dp"
            android:layout_weight="3"
            android:layout_height="match_parent" />
        <Button
            android:id="@+id/editbutton"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            android:text="EDIT"/>
    </LinearLayout>
    <Spinner
        android:id="@+id/spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </Spinner>
</LinearLayout>

用法示例: -

选择了Spinner(已输入注释更新数据): -

enter image description here

选择花生酱并输入更新数据: -

enter image description here

单击“编辑”按钮后: -

enter image description here

将EditText设置为当前选定的微调器项

以下内容可用于将EditText设置为当前所选微调器项的值: -

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            spinneritem.setText(csr.getString(csr.getColumnIndex(SpinnerDatabase.KEY_NAME)));
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });

可以在Activity中设置适配器后添加。

在上面的 SO46330096Activity.java 中,它可以遵循以下一行: -

        spinner.setAdapter(sca);