Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing database class object from main activity to another activity

Tags:

android

sqlite

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

like image 743
shehzy Avatar asked Jul 26 '16 23:07

shehzy


2 Answers

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
    }
}
like image 118
OneCricketeer Avatar answered Sep 28 '22 04:09

OneCricketeer


MyDbHandler must extend Serializable to be correctly serialized.

like image 41
Mr. Negi Avatar answered Sep 28 '22 05:09

Mr. Negi