I'm simply trying to store the state of checkbox in database but my application crashes when i click on submit button.I am trying to do this with a sqliteOpenHelper. After storing the state I also want to display it but first I'm not able to store it. Please guide me as I'm new to android. Here's my code..
//MainActivity.java
CheckBox ch1;
Button btnSubmit;
int checked=0;
DatabaseHelper dbhelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ch1=(CheckBox)findViewById(R.id.checkBox);
btnSubmit=(Button)findViewById(R.id.button);
AddData();
}
public void AddData() {
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ch1.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked){
checked = 1;
}else{
checked = 0;
}
}
});
boolean insertData = dbhelper.addData(checked);
if (insertData == true) {
Toast.makeText(MainActivity.this, "Order Placed!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Something went wrong :
(.", Toast.LENGTH_LONG).show();
}
}
});
}
//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)";
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;
}
}
}
Aucun commentaire:
Enregistrer un commentaire