Quentamia
Quentamia

Reputation: 3292

What is a good method for persisting objects through an Android app?

I'm trying to persist data objects throughout my Android app. I want to be able to access an object in one activity, modify it, save it, navigate to a new activity, and access the same object with the updated value.

What I'm essentially talking about is a cache, but my data objects are complex. For example, ObjectA contains ObjectB which contains ObjectC. Does anyone know if a good method, tool, or framework for persisting complex objects in Sql?

Upvotes: 0

Views: 505

Answers (3)

Kyle
Kyle

Reputation: 711

Put a static field in a subclassed Application. Also inside your manifest, put:

android:name="MyApp" inside your application tags.

Also to access from other files, simply use:

MyApp myApp = (MyApp)getApplicationContext();

See here How to declare global variables in Android?:

class MyApp extends Application {

  private String myState;

  public String getState(){
    return myState;
  }
  public void setState(String s){
    myState = s;
  }
}

class Blah extends Activity {

  @Override
  public void onCreate(Bundle b){
    ...
    MyApp appState = ((MyApp)getApplicationContext());
    String state = appState.getState();
    ...
  }
}

Upvotes: 1

Zsombor Erdődy-Nagy
Zsombor Erdődy-Nagy

Reputation: 16914

  • You could use an ORM framework, like OrmLite for mapping objects into sql, but it may be an overkill for you situation.

  • You could also make these shared object Parcelable and pass them between the Activities thru the Intents.

  • You could also save these objects into the SharedPreferences, so each Activity can access them whenever they feel the need to it, and the objects are also persisted this way. This may mean more IO access though, so take that into consideration as well. You could use e.g. Gson to serialize the objects more painlessly for this.

These are the solutions I'd consider. But whatever you do, don't put this common object into some kind of "standard" global static variable, like using a custom Application class, static field or any implementation of the Singleton pattern, these are really fragile constructs on Android.

Upvotes: 0

rdgilead
rdgilead

Reputation: 226

Why don't you use a JSON serialization mechanism ?

In association with a static access to your objects you can easily build a lite-weight database with some basic functionnalities:

  • loadObjectsFromCache
  • saveObjectsInCache
  • getObjects

You can also store your objects in differents files, and use a streaming json parser like this one: http://code.google.com/p/google-gson/

It's the same that this one: http://developer.android.com/reference/android/util/JsonReader.html but can be used even if your application api level is inferior to 11.

It use less memory than the basic DOM parser: http://developer.android.com/reference/org/json/JSONObject.html, but with the same speed.

Upvotes: 0

Related Questions