Reputation: 13
I'm making a game for the Android platform and I need to access some information from multiple activities (achievements, sound on/off, etc). I know I can pass individual values from one activity to another, but is there a way I can set up like a database or something where I can access the variables from any activity?
Upvotes: 0
Views: 131
Reputation: 3430
You can use shared preference as easy way to do this.
The docs says:
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
Following is the code from the docs:
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
@Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
For other ways to store data there is very good tutorials on android site- http://developer.android.com/guide/topics/data/index.html
Upvotes: 0
Reputation: 10540
There are many ways to achieve this. You could set up an SQLite database, use SharedPreferences, or use startActivityForResult() in combination with an Intent. All of these are well documented in the Developer's site if you want to research them.
Upvotes: 0
Reputation: 106
It depends on your app requirement. Usually the data are shared between 2 activities via, "Extras sent as part of the intent"
If you like to share the data across multiple activities then you could use, 1. Preference - Using application preference (XML file stored in app directory) 2. Databases - Using Android Content provider/resolver
Upvotes: 0
Reputation: 33741
Yes, you can use SQLite to persist data. There are other alternatives: http://developer.android.com/guide/topics/data/data-storage.html It really depends on how complex the data is. Another approach is pass data between activities as Serializable or Parcelable objects, but if you want to be able to query data anew from any activity you'll need a sqlite db or some sort of mechanism to serialize data and write it to disk.
Upvotes: 2