Access to global data everywhere - efficiently

I need to find a solution that contains and accesses large fragments of complex global data and methods. It must be accessible from within and from ordinary instance variables of various data classes.

Here is how I did it. I would just like to know if there is something wrong with this or if there is a better / cleaner way.

First I stretch Application , as recommended many times ...

 public class MainDataManager extends Application{ public ... large chunks of data in arrays, lists, sets,.... //static variable for singleton access from within instance variables of other classes public static MainDataManager mainDataManager; //create and init the global data, and store it in the static variable of the class @Override public void onCreate() { super.onCreate(); //in case it should get called more than once for any reason if (mainDataManager == null) { init(); mainDataManager = this; } } 

Now access to it from the inside, as recommended everywhere ...

 MainDataManager mainDataManager = (MainDataManager)getApplicationContext(); 

And since I need to access it from regular instances of data classes ...

 public class MyDataClass { public MainDataManager mainDataManager; public String name; public MyDataClass(String namex) { this.name = namex; //this is why I defined the static variable within MainDataManager, so //one has access to it from within the instance of MyDataClass this.mainDataManager = MainDataManager.mainDataManager; } public void examplesForAccessing() { //some examples on how to access the global data structure and associated methods mainDataManager.someMethodAccess(); xyz = mainDataManager.someDataAccess; mainDataManager.someIndirectMethodAccess.clear(); mainDataManager.someOtherData = false; } } 

Since I have not done this yet, I would like to know if there is anything wrong with this. Memory, efficiency, ...

Thank you very much!

Can I add a small alert? I could just use the MainDataClass class and access MainDataClass.var or MainDataClass.method(). Are there any disadvantages to REAL?

Is the data in both cases stored on the heap / stack?

+4
source share
1 answer

You did not specify in detail about your "big chunks of data", but keep in mind that the onCreate method is the first thing that starts when your application starts and starts in the main / user interface thread. This means that if you perform lengthy tasks in your init () method, your UX will be bad, not to mention the fact that you risk the exception of ANR.

The solution for this is simple:

  • Keep onCreate Shorted
  • Create a BG stream and use it to run all initialization code
  • Show the Splash / Welcome screen with the corresponding progress bar when the BG stream is running.
0
source

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


All Articles