简体   繁体   中英

Passing database class object from main activity to another activity

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必须扩展Serializable才能正确序列化。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM