2017-10-29 47 views
0

我想在我的数据库中保存一个复选框状态并在稍后检索它,但它似乎不工作。我现在得到我的日志中的错误,希望有人能够协助。如何保存数据库中的复选框状态?

这是我为我的复选框代码:

<CheckBox 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/check1" 
     android:text="test" 
     android:layout_below="@+id/textViewAge" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:layout_marginTop="15dp" /> 

    <CheckBox 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/check2" 
     android:text="test2" 
     android:layout_below="@+id/check1" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:layout_marginTop="11dp" /> 

然后在我的CreateOrEditJobCards.java:

checkA = (CheckBox) findViewById(R.id.check1); 
    checkA.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 

     @Override 
     public void onCheckedChanged(CompoundButton arg0, boolean checked) { 
      // TODO Auto-generated method stub 
      if(checked) 
      { 
       SaveString="Yes"; 
      } 
      else 
      { 
       SaveString="No"; 
      } 
     } 
    }); 
    checkB = (CheckBox) findViewById(R.id.check2); 
    checkB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 

     @Override 
     public void onCheckedChanged(CompoundButton arg0, boolean checked) { 
      // TODO Auto-generated method stub 
      if(checked) 
      { 
       SaveStringA="Yes"; 
      } 
      else 
      { 
       SaveStringA="No"; 
      } 
     } 
    }); 

...... 

if(personID > 0) { 
     saveButton.setVisibility(View.GONE); 
     buttonLayout.setVisibility(View.VISIBLE); 

     Cursor rs = dbHelper.getPerson(personID); 
     rs.moveToFirst(); 
     String personName = rs.getString(rs.getColumnIndex(DBHelper.PERSON_COLUMN_NAME)); 
     String personGender = rs.getString(rs.getColumnIndex(DBHelper.PERSON_COLUMN_GENDER)); 
     SaveString = rs.getString(rs.getColumnIndex(DBHelper.PERSON_CHECKBOX_A)); 
     SaveStringA = rs.getString(rs.getColumnIndex(DBHelper.PERSON_CHECKBOX_B)); 
     int personAge = rs.getInt(rs.getColumnIndex(DBHelper.PERSON_COLUMN_AGE)); 
     if (!rs.isClosed()) { 
      rs.close(); 
     } 

     nameEditText.setText(personName); 
     nameEditText.setFocusable(false); 
     nameEditText.setClickable(false); 

     genderEditText.setText(personGender); 
     genderEditText.setFocusable(false); 
     genderEditText.setClickable(false); 

     ageEditText.setText((personAge + "")); 
     ageEditText.setFocusable(false); 
     ageEditText.setClickable(false); 

     checkA.setChecked(Boolean.parseBoolean(String.valueOf(SaveString))); 
     checkA.setFocusable(false); 
     checkA.setClickable(false); 

     checkB.setChecked(Boolean.parseBoolean(String.valueOf(SaveStringA))); 
     checkB.setFocusable(false); 
     checkB.setClickable(false); 
    } 
} 

@Override 
public void onClick(View view) { 
    switch (view.getId()) { 
     case R.id.saveButton: 
      persistPerson(); 
      return; 
     case R.id.editButton: 
      saveButton.setVisibility(View.VISIBLE); 
      buttonLayout.setVisibility(View.GONE); 
      nameEditText.setEnabled(true); 
      nameEditText.setFocusableInTouchMode(true); 
      nameEditText.setClickable(true); 

      genderEditText.setEnabled(true); 
      genderEditText.setFocusableInTouchMode(true); 
      genderEditText.setClickable(true); 

      ageEditText.setEnabled(true); 
      ageEditText.setFocusableInTouchMode(true); 
      ageEditText.setClickable(true); 

      checkA.setEnabled(true); 
      checkA.setFocusableInTouchMode(true); 
      checkA.setClickable(true); 

      checkB.setEnabled(true); 
      checkB.setFocusableInTouchMode(true); 
      checkB.setClickable(true); 


      return; 
     case R.id.deleteButton: 
      AlertDialog.Builder builder = new AlertDialog.Builder(this); 
      builder.setMessage(R.string.deletePerson) 
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
          dbHelper.deletePerson(personID); 
          Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show(); 
          Intent intent = new Intent(getApplicationContext(), JobCardMainActivity.class); 
          intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
          startActivity(intent); 
         } 
        }) 
        .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
          // User cancelled the dialog 
         } 
        }); 
      AlertDialog d = builder.create(); 
      d.setTitle("Delete Job Card?"); 
      d.show(); 
      return; 
    } 
} 

public void persistPerson() { 
    if(personID > 0) { 
     if(dbHelper.updatePerson(personID, 
       nameEditText.getText().toString(), 
       genderEditText.getText().toString(), 
       checkA.getText().toString(), 
       checkB.getText().toString(), 

       Integer.parseInt(ageEditText.getText().toString()))) { 

      Toast.makeText(getApplicationContext(), "Job Card Update Successful", Toast.LENGTH_SHORT).show(); 
      Intent intent = new Intent(getApplicationContext(), JobCardMainActivity.class); 
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      startActivity(intent); 
     } 
     else { 
      Toast.makeText(getApplicationContext(), "Job Card Update Failed", Toast.LENGTH_SHORT).show(); 
     } 
    } 
    else { 
     if(dbHelper.insertPerson(nameEditText.getText().toString(), 
       genderEditText.getText().toString(), 
       checkA.getText().toString(), 
       checkB.getText().toString(), 

       Integer.parseInt(ageEditText.getText().toString()))) { 
      Toast.makeText(getApplicationContext(), "Job Card Inserted", Toast.LENGTH_SHORT).show(); 
     } 
     else{ 
      Toast.makeText(getApplicationContext(), "Could not Insert Job Card", Toast.LENGTH_SHORT).show(); 
     } 
     Intent intent = new Intent(getApplicationContext(), JobCardMainActivity.class); 
     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     startActivity(intent); 
    } 
} 
} 

在我DBHelper.java

public static final String PERSON_TABLE_NAME = "person"; 
public static final String PERSON_COLUMN_ID = "_id"; 
public static final String PERSON_COLUMN_NAME = "name"; 
public static final String PERSON_COLUMN_GENDER = "gender"; 
public static final String PERSON_COLUMN_AGE = "age"; 
public static final String PERSON_CHECKBOX_A = "checka"; 
public static final String PERSON_CHECKBOX_B = "checkb"; 

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

@Override 
public void onCreate(SQLiteDatabase db) { 
    db.execSQL(
      "CREATE TABLE " + PERSON_TABLE_NAME + 
        "(" + PERSON_COLUMN_ID + " INTEGER PRIMARY KEY, " + 
        PERSON_COLUMN_NAME + " TEXT, " + 
        PERSON_COLUMN_GENDER + " TEXT, " + 
        PERSON_CHECKBOX_A + " TEXT, " + 
        PERSON_CHECKBOX_B + " TEXT, " + 
        PERSON_COLUMN_AGE + " INTEGER)" 
    ); 
} 

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

public boolean insertPerson(String name, 
          String gender, 
          String checka, 
          String checkb, 
          int age) { 

    SQLiteDatabase db = this.getWritableDatabase(); 
    ContentValues contentValues = new ContentValues(); 

    contentValues.put(PERSON_COLUMN_NAME, name); 
    contentValues.put(PERSON_COLUMN_GENDER, gender); 
    contentValues.put(PERSON_COLUMN_AGE, age); 
    contentValues.put(PERSON_CHECKBOX_A, checka); 
    contentValues.put(PERSON_CHECKBOX_B, checkb); 

    db.insert(PERSON_TABLE_NAME, null, contentValues); 
    return true; 
} 

public int numberOfRows() { 
    SQLiteDatabase db = this.getReadableDatabase(); 
    int numRows = (int) DatabaseUtils.queryNumEntries(db, PERSON_TABLE_NAME); 
    return numRows; 
} 

public boolean updatePerson(Integer id, 
          String name, 
          String gender, 
          String checka, 
          String checkb, 
          int age) { 
    SQLiteDatabase db = this.getWritableDatabase(); 
    ContentValues contentValues = new ContentValues(); 
    contentValues.put(PERSON_COLUMN_NAME, name); 
    contentValues.put(PERSON_COLUMN_GENDER, gender); 
    contentValues.put(PERSON_COLUMN_AGE, age); 
    contentValues.put(PERSON_CHECKBOX_A, checka); 
    contentValues.put(PERSON_CHECKBOX_B, checkb); 
    db.update(PERSON_TABLE_NAME, contentValues, PERSON_COLUMN_ID + " = ? ", new String[] { Integer.toString(id) }); 
    return true; 
} 

public Integer deletePerson(Integer id) { 
    SQLiteDatabase db = this.getWritableDatabase(); 
    return db.delete(PERSON_TABLE_NAME, 
      PERSON_COLUMN_ID + " = ? ", 
      new String[] { Integer.toString(id) }); 
} 

public Cursor getPerson(int id) { 
    SQLiteDatabase db = this.getReadableDatabase(); 
    Cursor res = db.rawQuery("SELECT * FROM " + PERSON_TABLE_NAME + " WHERE " + 
      PERSON_COLUMN_ID + "=?", new String[]{Integer.toString(id)}); 
    return res; 
} 

public Cursor getAllPersons() { 
    SQLiteDatabase db = this.getReadableDatabase(); 
    Cursor res = db.rawQuery("SELECT * FROM " + PERSON_TABLE_NAME, null); 
    return res; 
} 
} 

基本上在此应用程序用户将选择“添加新的工作卡”,然后填写表格并点击保存。然后按照编号顺序显示在列表视图中。 当用户将然后选择前面创建他们就可以点击发送表格,然后它会通过电子邮件的形式(我仍在努力对和代码是不是在上面)

但是就像我前面说的,一切在表单工作并保存,但似乎无法得到复选框来保存它被检查的状态

请问有人请看一下mu代码并指出我出错的地方并提供帮助吗?

感谢

编辑

日志输出:

10-29 10:37:13.329 11748-11825/com.software.example D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000, [1440x2560]-format:1 
10-29 10:37:13.331 11748-11748/com.software.example D/ScrollView: onsize change changed 
10-29 10:37:13.367 11748-11748/com.software.example D/[email protected][CreateOrEditJobCards]: MSG_RESIZED_REPORT: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1 
10-29 10:37:13.367 11748-11748/com.software.example D/[email protected][CreateOrEditJobCards]: MSG_WINDOW_FOCUS_CHANGED 1 
10-29 10:37:13.370 11748-11748/com.software.example V/InputMethodManager: Starting input: [email protected] nm : com.software.example [email protected] 
10-29 10:37:13.370 11748-11748/com.software.example I/InputMethodManager: [IMM] startInputInner - mService.startInputOrWindowGainedFocus 
10-29 10:37:13.380 11748-11748/com.software.example D/InputTransport: Input channel constructed: fd=96 
10-29 10:37:13.380 11748-11748/com.software.example D/InputTransport: Input channel destroyed: fd=91 
10-29 10:37:13.406 11748-11825/com.software.example D/OpenGLRenderer: endAllActiveAnimators on 0x7cfa738000 (RippleDrawable) with handle 0x7cfea52600 
10-29 10:37:13.536 11748-11748/com.software.example D/[email protected][CreateOrEditJobCards]: MSG_RESIZED: ci=Rect(0, 96 - 0, 1128) vi=Rect(0, 96 - 0, 1128) or=1 
10-29 10:37:13.557 11748-11748/com.software.example D/ScrollView: onsize change changed 
10-29 10:37:14.180 11748-11748/com.software.example D/[email protected][CreateOrEditJobCards]: ViewPostImeInputStage processPointer 0 
10-29 10:37:14.261 11748-11748/com.software.example D/[email protected][CreateOrEditJobCards]: ViewPostImeInputStage processPointer 1 
10-29 10:37:15.057 11748-11748/com.software.example D/[email protected][CreateOrEditJobCards]: ViewPostImeInputStage processPointer 0 
10-29 10:37:15.156 11748-11748/com.software.exampleD/[email protected][CreateOrEditJobCards]: ViewPostImeInputStage processPointer 1 
10-29 10:37:15.807 11748-11748/com.software.example D/[email protected][CreateOrEditJobCards]: ViewPostImeInputStage processPointer 0 
10-29 10:37:15.975 11748-11748/com.software.example D/[email protected][CreateOrEditJobCards]: ViewPostImeInputStage processPointer 1 
10-29 10:37:16.544 11748-11748/com.software.example D/[email protected][CreateOrEditJobCards]: ViewPostImeInputStage processPointer 0 
10-29 10:37:16.619 11748-11748/com.software.example D/[email protected][CreateOrEditJobCards]: ViewPostImeInputStage processPointer 1 
10-29 10:37:16.697 11748-11748/com.software.example D/InputTransport: Input channel constructed: fd=87 
10-29 10:37:16.698 11748-11748/com.software.example D/[email protected][Toast]: setView = android.widget.LinearLayout{7d5a544 V.E...... ......I. 0,0-0,0} touchMode=true 
10-29 10:37:16.710 11748-11748/com.software.example D/[email protected][CreateOrEditJobCards]: MSG_WINDOW_FOCUS_CHANGED 0 
10-29 10:37:16.712 11748-11748/com.software.example D/[email protected][JobCardMainActivity]: dispatchDetachedFromWindow 
10-29 10:37:16.716 11748-11748/com.software.example D/InputTransport: Input channel destroyed: fd=88 
10-29 10:37:16.735 11748-11825/com.software.example D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000, [652x176]-format:1 
10-29 10:37:16.752 11748-11748/com.software.example D/AbsListView: Get MotionRecognitionManager 
10-29 10:37:16.753 11748-11748/com.software.example D/MotionRecognitionManager: mSContextService = com[email protected]17a4e86 
10-29 10:37:16.753 11748-11748/com.software.example D/MotionRecognitionManager: motionService = c[email protected]6a47347 
10-29 10:37:16.753 11748-11748/com.software.example D/MotionRecognitionManager: motionService = c[email protected]6a47347 
10-29 10:37:16.776 11748-11748/com.software.example D/InputTransport: Input channel constructed: fd=95 
10-29 10:37:16.776 11748-11748/com.software.example D/[email protected][JobCardMainActivity]: setView = [email protected][JobCardMainActivity] touchMode=true 
10-29 10:37:16.836 11748-11825/com.software.example D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000, [1440x2560]-format:1 
10-29 10:37:16.837 11748-11748/com.software.example D/AbsListView: onsize change 
10-29 10:37:16.838 11748-11748/com.software.example D/[email protected][Toast]: MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1 
10-29 10:37:16.878 11748-11748/com.software.example D/[email protected][JobCardMainActivity]: MSG_RESIZED_REPORT: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1 
10-29 10:37:16.878 11748-11748/com.software.example D/[email protected][JobCardMainActivity]: MSG_WINDOW_FOCUS_CHANGED 1 
10-29 10:37:16.879 11748-11748/com.software.example V/InputMethodManager: Starting input: [email protected] nm : com.software.example ic=null 
10-29 10:37:16.879 11748-11748/com.software.example I/InputMethodManager: [IMM] startInputInner - mService.startInputOrWindowGainedFocus 
10-29 10:37:16.883 11748-11748/com.software.example D/InputTransport: Input channel constructed: fd=104 
10-29 10:37:16.883 11748-11748/com.software.example D/InputTransport: Input channel destroyed: fd=96 
10-29 10:37:16.902 11748-11825/com.software.example D/OpenGLRenderer: endAllActiveAnimators on 0x7cce563400 (RippleDrawable) with handle 0x7d0c2ed3a0 
10-29 10:37:16.908 11748-11748/com.software.example W/IInputConnectionWrapper: finishComposingText on inactive InputConnection 
10-29 10:37:16.909 11748-11748/com.software.example W/IInputConnectionWrapper: finishComposingText on inactive InputConnection 
10-29 10:37:17.308 11748-11748/com.software.example D/[email protected][CreateOrEditJobCards]: dispatchDetachedFromWindow 
10-29 10:37:17.312 11748-11748/com.software.example D/InputTransport: Input channel destroyed: fd=85 
10-29 10:37:17.665 11748-11748/com.software.example D/[email protected][JobCardMainActivity]: ViewPostImeInputStage processPointer 0 
10-29 10:37:17.670 11748-11748/com.software.example D/[email protected][Toast]: dispatchDetachedFromWindow 
10-29 10:37:17.675 11748-11748/com.software.example D/InputTransport: Input channel destroyed: fd=87 
10-29 10:37:17.742 11748-11748/com.software.example D/[email protected][JobCardMainActivity]: ViewPostImeInputStage processPointer 1 
10-29 10:37:17.847 11748-11748/com.software.example D/[email protected][JobCardMainActivity]: MSG_WINDOW_FOCUS_CHANGED 0 
10-29 10:37:17.909 11748-11748/com.software.example D/InputTransport: Input channel constructed: fd=87 
10-29 10:37:17.909 11748-11748/com.software.example D/[email protected][CreateOrEditJobCards]: setView = [email protected][CreateOrEditJobCards] touchMode=true 
10-29 10:37:17.939 11748-11825/com.software.example D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000, [1440x2560]-format:1 
10-29 10:37:17.941 11748-11748/com.software.example D/ScrollView: onsize change changed 
10-29 10:37:17.967 11748-11748/com.software.example D/[email protected][CreateOrEditJobCards]: MSG_RESIZED_REPORT: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1 
10-29 10:37:17.967 11748-11748/com.software.example D/[email protected][CreateOrEditJobCards]: MSG_WINDOW_FOCUS_CHANGED 1 
10-29 10:37:17.968 11748-11748/com.software.example V/InputMethodManager: Starting input: [email protected] nm : com.software.example ic=null 
10-29 10:37:17.968 11748-11748/com.software.example I/InputMethodManager: [IMM] startInputInner - mService.startInputOrWindowGainedFocus 
10-29 10:37:17.973 11748-11748/com.software.example D/InputTransport: Input channel constructed: fd=93 
10-29 10:37:17.973 11748-11748/com.software.example D/InputTransport: Input channel destroyed: fd=104 
10-29 10:37:18.000 11748-11825/com.software.example D/OpenGLRenderer: endAllActiveAnimators on 0x7cea5c2c00 (ListView) with handle 0x7d0c26c780 
+0

请分享你得到 – Mudassar

+0

错误我不是收到错误,日志显示没有什么会提示我犯了一个错误。 – Newbie

+0

共享完整日志 – Mudassar

回答

1

不要在插入/更新方法中传递checkA.getText()。toString(),你永远不会改变它们。简单地传递SaveStrings(您在onCheckedChangedListeners改变)在dbHelper.insertPerson方法:

dbHelper.insertPerson(nameEditText.getText().toString(), 
      genderEditText.getText().toString(), 
      SaveString, 
      SaveStringA, 
      Integer.parseInt(ageEditText.getText().toString()))) 

考虑更改逻辑有点能够删除的代码了很多。

dbHelper.insertPerson(nameEditText.getText().toString(), 
      genderEditText.getText().toString(), 
      checkA.isChecked() ? "Yes" : "No", 
      checkB.isChecked() ? "Yes" : "No", 
      Integer.parseInt(ageEditText.getText().toString()))) 

然后,你就可以摆脱的两个onCheckedChangedListener方法,以及SaveString和SaveStringA引用。

另外一个错误,我查阅.....

checkA.setChecked(Boolean.parseBoolean(String.valueOf(SaveString))); ..我不认为parseBoolean正常工作为“是”,“否” ......需要“真”“假”,所以除非您更改此设置,否则永远不会检索正确的检查状态。因此,要么改变insertPerson方法是:

checkA.isChecked() ? "True" : "False" 
checkB.isChecked() ? "True" : "False" 

或者改变你的setChecked这样:

checkA.setChecked(SaveString.equals("Yes")); 
+0

谢谢。感谢你的帮助。它现在工作完美:-) – Newbie

0

当你坚持要保存什么用checkbox.getText(返回Person对象),而不是SaveString对象您在哪里存储复选框状态。

0

我使用字符串作为是和否的复选框状态,然后保存它的数据库。 此外,我正在检测后退按钮,并在应用即将关闭时保存复选框的状态,以避免数据库中的连续垃圾邮件。 我附上我的完整代码。希望这能解决你的问题。 另外我使用了不同的java文件来避免混淆。

TaskContract.java

public class TaskContract { 
    public static final String DB_NAME = "com.pkr.checkbox"; 
    public static final int DB_VERSION = 1; 
    public class TaskEntry implements BaseColumns { 
     public static final String TABLE = "checkbox"; 
     public static final String HI_CHECK = "hi_checkbox"; 
     public static final String HELLO_CHECK = "hello_checkbox"; 
    } 
} 

TaskDBHelper.java

public class TaskDBHelper extends SQLiteOpenHelper { 
    public TaskDBHelper(Context context){ 
     super(context, TaskContract.DB_NAME, null, TaskContract.DB_VERSION); 
    } 

    @Override 
    public void onCreate(SQLiteDatabase db) { 
     String createTable = "CREATE TABLE " + TaskContract.TaskEntry.TABLE + " (" + 
      TaskContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 
      TaskContract.TaskEntry.HI_CHECK + " TEXT NOT NULL, " + 
      TaskContract.TaskEntry.HELLO_CHECK + " TEXT NOT NULL);"; 
     String defaultEntry = "INSERT INTO " + TaskContract.TaskEntry.TABLE + " (" + TaskContract.TaskEntry.HI_CHECK + "," + TaskContract.TaskEntry.HELLO_CHECK + ") VALUES\n" + 
      "('No','No');"; 

     db.execSQL(createTable); 
     db.execSQL(defaultEntry); 
    } 

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

MainActivity.java

public class MainActivity extends AppCompatActivity { 

    private CheckBox hi_checkbox_but; 
    private CheckBox hello_checkbox_but; 
    private TaskDBHelper mHelper = new TaskDBHelper(this); 
    String hi, hello; 

    private static final String TAG = "MainActivity"; 

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

     hi_checkbox_but = (CheckBox) findViewById(R.id.checkBox); 
     hello_checkbox_but = (CheckBox) findViewById(R.id.checkBox1); 

     SQLiteDatabase db = mHelper.getReadableDatabase(); 
     Cursor cur = db.query(TaskContract.TaskEntry.TABLE, 
      new String[]{TaskContract.TaskEntry._ID, TaskContract.TaskEntry.HI_CHECK, TaskContract.TaskEntry.HELLO_CHECK}, 
      null, null, null, null, null); 
     while (cur.moveToNext()){ 
      int hi_index = cur.getColumnIndex(TaskContract.TaskEntry.HI_CHECK); 
      int hello_index = cur.getColumnIndex(TaskContract.TaskEntry.HELLO_CHECK); 
      hi = cur.getString(hi_index); 
      hello = cur.getString(hello_index); 

     } 

     if (hi.equals("Yes")) 
      hi_checkbox_but.setChecked(true); 
     else 
      hi_checkbox_but.setChecked(false); 

     if (hello.equals("Yes")) 
      hello_checkbox_but.setChecked(true); 
     else 
      hello_checkbox_but.setChecked(false); 

    } 

    private Boolean exit = false; 

    @Override 
    public void onBackPressed() { 
     String hi_toPass, hello_toPass; 
     if (exit) { 

      if (hi_checkbox_but.isChecked()) 
       hi_toPass = "Yes"; 
      else 
       hi_toPass = "No"; 
      if (hello_checkbox_but.isChecked()) 
       hello_toPass = "Yes"; 
      else 
       hello_toPass = "No"; 

      SQLiteDatabase db = mHelper.getWritableDatabase(); 
      ContentValues cv = new ContentValues(); 
      cv.put(TaskContract.TaskEntry.HI_CHECK,hi_toPass); 
      cv.put(TaskContract.TaskEntry.HELLO_CHECK, hello_toPass); 
      db.insertWithOnConflict(TaskContract.TaskEntry.TABLE, 
       null, 
       cv, 
       SQLiteDatabase.CONFLICT_REPLACE); 
      db.close(); 
      finish(); 
     } 
     else{ 
      Toast.makeText(this, "Press back again to exit.", Toast.LENGTH_SHORT).show(); 
      exit = true; 
      new Handler().postDelayed(new Runnable() { 
       @Override 
       public void run() { 
        exit = false; 
       } 
      }, 3 * 1000); 
     } 
    } 
} 

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" 
android:layout_margin="16dp" 
android:orientation="vertical" 
tools:context="com.pkr.checkbox.MainActivity"> 

<CheckBox 
    android:id="@+id/checkBox" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_margin="16dp" 
    android:text="HI" /> 

<CheckBox 
    android:id="@+id/checkBox1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_margin="16dp" 
    android:text="Hello" /> 

</LinearLayout>