切换按钮值的开和关状态应存储到数据库中

时间:2019-05-03 06:50:49

标签: android android-togglebutton

我正在使用具有切换按钮的应用程序,并且我想在不使用“编辑文本”的情况下在数据库中存储开和关值,你能告诉我这个过程吗?

1 个答案:

答案 0 :(得分:1)

以下是一个简单的应用程序,其中显示了3个按钮,单击这些按钮可将状态切换到SQlite数据库中。

它由3部分代码组成(每一个设计都是要遵循的过程):-

  1. 具有3个按钮的布局activity_main.xml
  2. DatabaseHelper,它具有核心数据库代码,并提供可用于添加(插入),更新和查询数据库DatabaseHelper.java的方法。
  3. 管理用户界面MainActivity.java的活动

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <Button
        android:id="@+id/toggle1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/toggle2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/toggle3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

DataabseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DBNAME = "mydatabase"; // The name of the database (the file name)
    public static final int DBVERSION = 1; // The SQliteOpenHelper class provides a means of managing versions so verion nmber is required

    //publicly availavle constants for the toggle states
    public static final int TOGGLESTATUSON = 1;
    public static final int TOGGLESTATUSOFF = 0;

    // The table and the columns
    public static final String TABLE_TOGGLE = "toggle";
    public static final String COL_TOGGLE_ID = BaseColumns._ID; // using _id allows CursorAdapater to be used
    public static final String COL_TOGGLE_STATUS = "toggle_status";

    SQLiteDatabase mDB; // The database connection

    // The Constructor
    public DatabaseHelper(Context context) {
        super(context, DBNAME, null, DBVERSION); // Call the super constructor
        mDB = this.getWritableDatabase(); // store the connection
    }

    // This is called ONCE when the database is created. Used here to create the table
    @Override
    public void onCreate(SQLiteDatabase db) {

        //The SQL for creating the table
        String crt_toggle_table_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_TOGGLE + "(" +
                COL_TOGGLE_ID + " INTEGER PRIMARY KEY, " +
                COL_TOGGLE_STATUS + " INTEGER " +
                ")";
        // Execute the sql
        db.execSQL(crt_toggle_table_sql);
    }

    //No Version management included
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    // Add a row to the table (sets the button state to ON)
    public long addToggleRow() {
        ContentValues cv = new ContentValues();
        cv.put(COL_TOGGLE_STATUS,TOGGLESTATUSON);
        return mDB.insert(TABLE_TOGGLE,null,cv);
    }

    // Retrieve all rows
    public Cursor getToggleRows() {
        return mDB.query(TABLE_TOGGLE,null,null,null,null,null,null);
    }

    // Update a row, as per the provided id, toggling the value
    public void toggleToggle(long id) {
        mDB.execSQL(
                "UPDATE " + TABLE_TOGGLE + " SET " + COL_TOGGLE_STATUS + " = NOT " + COL_TOGGLE_STATUS + " WHERE " + COL_TOGGLE_ID + " =?",
                new String[]{String.valueOf(id)} // the arguments to be bound 
                );
    }
}

MainActivity.java(管理UI)

public class MainActivity extends AppCompatActivity {

    //Class variables for the Buttons (3) and the DatabaseHelper object
    Button[] mButtons = new Button[3];
    DatabaseHelper mDBHlpr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Instantiate the DatabaseHelper (will create it when first run)
        mDBHlpr = new DatabaseHelper(this);
        initialiseDBToggleRows(); // Add the rows to the table, 1 per button, if not already added

        // set the array of buttons
        mButtons[0] = this.findViewById(R.id.toggle1);
        mButtons[1] = this.findViewById(R.id.toggle2);
        mButtons[2] = this.findViewById(R.id.toggle3);

        // Get the buttons states from the database setting the button text to ON or OFF
        loadButtons();

        // Add the onCLickListeners to 
        //      a) update the respective row in the database (toggle it)
        //      b) refresh the button display
        for (int i=0; i < mButtons.length;i++) {
            final int current = i;
            mButtons[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mDBHlpr.toggleToggle((long)current + 1);
                    loadButtons();
                }
            });
        }
    }

    // Set the button text according to the values tored in the database
    private void loadButtons() {
        Cursor csr = mDBHlpr.getToggleRows();
        while (csr.moveToNext()) {
            if (csr.getInt(csr.getColumnIndex(DatabaseHelper.COL_TOGGLE_STATUS)) == DatabaseHelper.TOGGLESTATUSON) {
                mButtons[csr.getPosition()].setText("ON");
            } else {
                mButtons[csr.getPosition()].setText("OFF");
            }
        }
    }

    //Add a row, if no rows exist, for each button in the mButtons array
    private void initialiseDBToggleRows() {
        if(DatabaseUtils.queryNumEntries(mDBHlpr.getWritableDatabase(),DatabaseHelper.TABLE_TOGGLE) > 0) return;
        for (int i=0; i < mButtons.length; i++) {
            mDBHlpr.addToggleRow();
        }
    }
}

结果

安装后的应用程序如下:-

enter image description here

单击任何按钮会将其从ON切换为OFF或从OFF切换为ON,状态存储在数据库中,因此停止应用程序并重新启动将维护/恢复上一个状态(除非卸载了该应用程序或清除了该应用程序的数据/已删除)。