Android Global Object Object

I am developing an Android application. I have some action in this. And I must have an object that can be accessed from all activities. Any ideas how to organize it?

+6
source share
4 answers

Use the global Application object as follows:

 package com.yourpackagename; public class App extends Application { } 

In AndroidManifest.xml :

 <application android:name=".App"> 

To access it from Activity :

 App globalApp = (App) getApplicationContext(); 

The App class will be automatically created when the application starts. It will be available as long as the application process is active. It can act as a global store where you can put your things and have access to them throughout the life of the application.

+11
source

There are several ways to do this. If the object you want to share is String (or is easily described using String), I would recommend General Settings . It serves as a keystore for exchanging data in the application.

If this is not the case (i.e. the suitability of String), you can consider passing it as an extra with an Intent that triggers your various actions. For instance:

 Intent newActivity = new Intent(CurrentActivity.class, ActivityToLaunch.class); newActivity.putExtra("object_key", Bundle_With_Your_Object); 

More about this strategy (especially the Bundle class if you are not familiar), I would read this Android document .

+3
source

In this case, you can use SharedPreferences:

To add or change:

 SharedPreferences prefs = this.getSharedPreferences("Cusom Name", Activity.MODE_PRIVATE); prefs.edit().putString("your_key", value).commit(); 

Clear:

 SharedPreferences prefs = this.getSharedPreferences("Cusom Name", Activity.MODE_PRIVATE); prefs.edit().clear(); 

To get the value:

 SharedPreferences prefs = this.getSharedPreferences("Cusom Name", Activity.MODE_PRIVATE); String value = prefs.getString("your_key", ""); 
+1
source

First create a class called MasterActivity that extends the Activity and defines your global object.

 public class MasterActivity extends Activity { public Object mObject; } 

Then you need to expand your main activity class with MasterActivity, for example:

 // 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(); } } 

Thus, you can use your object in all your actions by simply expanding MasterActivity instead of Activity.

0
source

Source: https://habr.com/ru/post/910879/


All Articles