-1

In my current project I have a form that stores data in sqlite. I have 3 radio button inside one radio group. what I want to do is save the values of these radio buttons in one fragment and retrieve them in another in case user wanted to edit the form.

I already read this post but I couldn't solve the problem.

I found out I can't save boolean data in sqlite I should use Integer with 0 and 1 values. But I don't know how to implement it.

In my SQLiteOpenHelper class I made a new column like this:

  public static final int COL5 = 0;

in my onCreate method i wrote

 String createTable = "CREATE TABLE " + TABLE_NAME + " " +
                "(ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COL2 + " TEXT, " + COL3 + " TEXT, " + COL4 + " TEXT, " + COL5 + "  INTEGER DEFAULT 0)";

in my add addData method I added it as Integer

I don't know how should I save and retrieve it. How should I save whether or not the radio button is checked as an Integer and then retrieve the same value.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • if radio button is checked then save it as 1 and unchecked save it as 0 when you are retrieving data check the value for COL5, if it is 1 set radioButton.setChecked(true) or set as false . – Vamsi Smart Feb 16 '18 at 19:32

1 Answers1

0

You have the RadioButtons in a RadioGroup therefore only one can always be checked. so you need only database entry to store the state. So check which one is checked and then store a value between 0 and 4 (or 1 and 5) whatever you like in your database.

so all you need for your table creation is:

String createTable = "CREATE TABLE " + TABLE_NAME + " " +
            "(ID INTEGER PRIMARY KEY, " +
             " radioGroupState INTEGER)";

(Note that I dropped the AUTOINCREMENT, because it is unnecessary) and then query like this:

@Override
public void onCreate(SQLiteDatabase db) {
    String createTable = "CREATE TABLE " + TABLE_NAME + " " +
            "(" + ID + " INTEGER PRIMARY KEY, " +
            " radioGroupState INTEGER)";

}

public void saveRadioButtonState(Integer state) {
    ContentValues cv = new ContentValues();
    cv.put("radioGroupState", state);
    getWritableDatabase().update(TABLE_NAME,  cv, ID +"=?", new String[]{ID + ""});
}

public Integer getRadioButtonState() {
    RADIO_GROUP_STATE = "radioGroupState";
    Cursor c = getReadableDatabase().query(TABLE_NAME, RADIO_GROUP_STATE, ID + " = ?", new
                    String[]{RADIO_BUTTON_ID.toString()},
            null,
            null, null);
    Integer state = -1;
    if (c.moveToFirst()) {
        state = c.getInt(c.getColumnIndex("radioGroupState"));
    }
    c.close();
    return state;
}

Addendum: Looking at your previous question I'm a bit confused about what you really want to save in the database. My solution shows you how to save which RadioButton was pressed. If you want so save text just replace Integer by String.

leonardkraemer
  • 6,573
  • 1
  • 31
  • 54