Ben
Ben

Reputation: 141

How in Android to pass an object to new Intent

I'd greatly appreciate any thoughts on the following problem: In Android I have my MainActivity, which creates and sets up a database handler class. e.g.

public class DbHandler extends SQLiteOpenHelper{
    //do db handling
}

Also, I've created my OnClickListener, which creates an Intent then startActivity's the Intent.

My question / problem is how to best pass the DBHandler into the new Activity. I've thought about creating a global - and the risks of the thread restarting. I can't quite work out how to parcel / serialize unless I create a wrapper - but still have the problem of passing the object in the "parcel"

I'm keen to understand how others have solved this?? Many thanks.

Upvotes: 4

Views: 598

Answers (1)

karabara
karabara

Reputation: 557

As I know it is good practice to use only one instance of SQLiteOpenHelper, so create it as singleton and make accessible

public final class DatabaseHelper extends SQLiteOpenHelper {

    /**
     * instance.
     */
    private static DatabaseHelper instance;

    /**
     * @return instance.
     */
    public static synchronized DatabaseHelper getInstance() {
        if (instance == null) {
            instance = new DatabaseHelper();
        }

        return instance;
    }
...
}

Upvotes: 2

Related Questions