I am trying to implement simple database CRUD operations, in case of UPDATE operation user moves to another screen where he inputs the new and old values for the column he wants to update, So while moving to next activity I want to pass the object of database class created in MainActivity to UpdateActivity, I tried it by implementing the Database class Serializbale but it crashes.
java.lang.RuntimeException: Parcelable encountered IOException reading a Serializable object
Here is the code i tried
MainActivity
MyDbHandler dbObj = new MyDBHandler(this, null, null, 1);
public void updateBtnClicked(View view)
{
Intent intent = new Intent(MainActivity.this, ActivityUpdate.class);
intent.putExtra("Object", dbObj);
startActivity(intent);
}
ActivityUpdate
intent = getIntent();
dbObj2 = (MyDBHandler) intent.getSerializableExtra("Object");
public void doneButtonClicked(View view)
{
String str1 = newValue.getText().toString();
String str2 = oldValue.getText().toString();
dbObj2.updateProduct(str1, str2);
finish();
}
So how could the database class object be passed from one to another activity? Thanks
how could the database class object be passed from one to another activity
You don't serialize Database objects. You request them again.
MyDbHandler dbHandler = new MyDbHandler(MainActivity.this); // pass your Activity here
dbHandler.update(new Foo(42));
Where MyDbHandler
is some extension of SQLiteOpenHelper
written like so
public class MyDbHandler extends SQLiteOpenHelper {
// Database Info
private static final String DATABASE_NAME = "DatabaseName";
private static final int DATABASE_VERSION = 1;
public MyDbHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion != newVersion) {
// TODO
}
/**
* Update method defined here
**/
public void update(Foo bar) {
SQLiteDatabase db = getWritableDatabase();
// TODO: Write to & close the database
}
}
MyDbHandler must extend Serializable to be correctly serialized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With