只需将复选框状态存储到sqlite数据库

时间:2018-05-28 12:58:16

标签: android sqlite checkbox android-sqlite

我只是试图将复选框的状态存储在数据库中,但是当我点击提交按钮时我的应用程序崩溃。我正在尝试使用sqliteOpenHelper执行此操作。存储状态后我也想显示它,但首先我无法存储它。请指导我,因为我是android的新手。这是我的代码..

MainActivity.java

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "check.db";
    public static final String TABLE_NAME = "entry";
    public static final String COL1 = "SIZE";

    public DatabaseHelper(Context context) {
       super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable = "CREATE TABLE " + TABLE_NAME + "(SIZE INTEGER)";
        db.execSQL(createTable);
    }

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

   public boolean addData(int s1){
       SQLiteDatabase db = this.getWritableDatabase();

       ContentValues contentValues = new ContentValues();
       contentValues.put(COL1, s1);

       long result  = db.insert(TABLE_NAME, null, contentValues);

       if(result == -1){
           return false;
       }else{
           return true;
       }
   }
}

databasehelper.java

05-28 19:06:06.236 3806-3806/com.example.hp.checkbox E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.hp.checkbox, PID: 3806 java.lang.NullPointerException: Attempt to invoke virtual method 'booleancom.example.hp.checkbox.DatabaseHelper.addData(java.lang.String)' on a null object reference
    at com.example.hp.checkbox.MainActivity$2.onClick(MainActivity.java:55)
    at android.view.View.performClick(View.java:5637)
    at android.view.View$PerformClick.run(View.java:22429)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)

logcat的

{{1}}

2 个答案:

答案 0 :(得分:0)

你不应该把这个复选框的事件监听器放在提交按钮onClick监听器上。

答案 1 :(得分:0)

我有一些问题我建议尝试使用以下代码,它将侦听器分开而不是将它们包含起来(只有在点击提交按钮时才会应用checkChanged,因为它太晚了无论状态如何(直到你更改复选框))。

  • 期待, “但我怎么知道它添加了一行?” 方法logData已添加到 DatabaseHelper 将列出日志中的行(例如,从数据库中获取数据的介绍)。

    MainActivity: -

    公共类MainActivity扩展了AppCompatActivity {

    CheckBox ch1;
    Button btnSubmit;
    int checked=0;
    DatabaseHelper dbhelper;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbhelper = new DatabaseHelper(this); //<<<< ADDED
    
        ch1=(CheckBox)findViewById(R.id.checkBox);
        btnSubmit=(Button)findViewById(R.id.button);
    
        // Button onClick Listener
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
    
                dbhelper.addData(checked);
                dbhelper.logData(); //<<<< ADDED to display data to log (see logData in DatabaseHelper)
            }
        });
    
        // CheckBox onchanged Listener
        ch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                checked = 0;
                if (isChecked) {
                    checked = 1;
                }
            }
        });
        //AddData(); //REMOVED
    }
    

DatabaseHelper.java: -

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "check.db";
    public static final String TABLE_NAME = "entry";
    public static final String COL1 = "SIZE";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //String createTable = "CREATE TABLE " + TABLE_NAME + "(SIZE INTEGER)";
        String createTable = "CREATE TABLE " + TABLE_NAME + "(" + COL1 + " INTEGER)"; //<<<< Suggestion
        db.execSQL(createTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        //db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME); //<<<< INVALID
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); //<<<< ADDED CORRECTION
        onCreate(db);
    }

    public boolean addData(int s1){
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues contentValues = new ContentValues();
        contentValues.put(COL1, s1);

        //<<<< simplified return
        return (db.insert(TABLE_NAME, null, contentValues) > 0);
    }

    //<<<<<<<<<< New method to write contents to the log >>>>>>>>>>
    public void logData() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor csr =  db.query(TABLE_NAME,null,null,null, null,null, null);
        Log.d(
                "ENTRY TABLE INFO",
                "Number of rows in table is " +
                        csr.getCount() +
                        "; they are :-"
        );
        while (csr.moveToNext()) {
            Log.d(
                    "ENTRY TABLE INFO",
                    "Row # " +
                            String.valueOf(csr.getPosition()) +
                            " that has a value of " +
                            csr.getInt(csr.getColumnIndex(COL1))
            );
        }
        csr.close();
    }
}

测试结果

执行以下操作后: -

  1. 单击提交按钮(未选中复选框)。
  2. 选中复选框。
  3. 点击提交按钮(选中复选框)。
  4. 日志中的结果输出为: -

    05-28 21:47:40.628 1156-1156/ci.checkit D/ENTRY TABLE INFO: Number of rows in table is 2; they are :-
        Row # 0 that has a value of 0
        Row # 1 that has a value of 1