Reputation: 833
i am developing an android app. I have some activities in it. And i must have an object which can be available from all activities. Any ideas how to organize it?
Upvotes: 6
Views: 5322
Reputation: 1120
First, create a class named MasterActivity which extends Activity and define your global object.
public class MasterActivity extends Activity
{
public Object mObject;
}
Then, you have to extend your main activity class with your MasterActivity like it :
// your main activity
public class MainActivity extends MasterActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// you can now use mObject in your main class
mObject.yourmethod();
}
}
By this way, you will be able to use your object in all your activities simply by extending MasterActivity instead of Activity.
Upvotes: 0
Reputation: 3882
Use the global Application
object in the following way:
package com.yourpackagename;
public class App extends Application {
}
In AndroidManifest.xml
:
<application android:name=".App">
To access it from an Activity
:
App globalApp = (App) getApplicationContext();
The App
class will be instantiated automatically when the app starts. It will be available as long as the application process is alive. It can act as a global store in which you can put your things and have access to them throughout the application lifetime.
Upvotes: 12
Reputation: 8141
You can use SharedPreferences in this case:
To add or edit:
SharedPreferences prefs = this.getSharedPreferences("Cusom Name", Activity.MODE_PRIVATE);
prefs.edit().putString("your_key", value).commit();
To clear:
SharedPreferences prefs = this.getSharedPreferences("Cusom Name", Activity.MODE_PRIVATE);
prefs.edit().clear();
To get value:
SharedPreferences prefs = this.getSharedPreferences("Cusom Name", Activity.MODE_PRIVATE);
String value = prefs.getString("your_key", "");
Upvotes: 1
Reputation: 2872
There are a few ways to do this. If the object you want to share is a String (or easily described with a String), I would recommend Shared Preferences. It serves as a key-value store for sharing data within an application.
If this is not the case (i.e. the suitability of a String), you could consider passing it as an extra with the Intent that launches your various activities. For example:
Intent newActivity = new Intent(CurrentActivity.class, ActivityToLaunch.class);
newActivity.putExtra("object_key", Bundle_With_Your_Object);
For more details on this strategy (especially about the Bundle class, if you're not familiar), I would read this Android doc.
Upvotes: 3