Creating an object that is accessible to all actions in Android

I am trying to create an ArrayList of data containing objects (for example, a list of addresses and properties (rather complicated)), and I am wondering: how can I make an object accessible (and editable) by all actions, and not just the one it was created in?

Mainly:

  • Create an array in action 1
  • Access to the same array in steps 2 and 3
  • ???
  • Profit
+4
source share
6 answers

The easiest way to do this is to create a Singleton. This is a kind of object that can only be created once, and if you try to access it again, it will return an existing instance of the object. Inside this you can hold an array.

public class Singleton { private static final Singleton instance = new Singleton(); // Private constructor prevents instantiation from other classes private Singleton() { } public static Singleton getInstance() { return instance; } } 

More on singleton: http://en.wikipedia.org/wiki/Singleton_pattern

+11
source

You can extend the application class. And add your arrays there.

You can access the class instance with this command

 MyApplication appContext = (MyApplication)getApplicationContext(); 
+6
source

Well, you can create a Constant class and declare ArrayList as a static variable.

1.)

  Class ConstantCodes{ public static ArrayList<MyClass> list = new ArrayList<MyClass>; } 

It will be available wherever you want, just ConstantCodes.list

2.) You can extend the class to the Application class, like this

 class Globalclass extends Application { private String myState; public String getState(){ return myState; } public void setState(String s){ myState = s; } } class TempActivity extends Activity { @Override public void onCreate(Bundle b){ ... MyApp appState = ((MyApp)getApplicationContext()); String state = appState.getState(); ... } } 
+2
source

you must make it static and access it from any other activity .....

0
source

How to use a static keyword?

public static SomeClass someObject

in your activity class that triggers your object

0
source

1- In Activity1, run the dΓ©clare your array command in public static

 public static ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String, String>>(); 

2- In Activity2 , Activity3 , etc. access to your ArrayList

 Activity1.myArray 
-1
source

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


All Articles