-1

My Android project need share a List<Right> rights between Activities. The value of this list is initiated in LoginActivity. In other Activity, i use this list to check right of user (if user has a correspondence right, app will show correspondence tab or do something else). The problem i meet is how to store List<Right> rights in my Android application. I have read many Post and people use Gson and Flexjson to change this list to String and use SharedPreferences.Editor putString (String key,String value) to store in SharedPreferences. In other Activity, use preferences.getString("girl_heart_key", "DEFAULT"); to get String and Deserialize it to List<Right> rights. But i think we can use a global static variable:

public static List<RightObject>rights = new ArrayList<RightObject>();

to share List<RightObject>rights between Activities. My question is: can we use global static variable to replace SharePrefrence in this case? and Is there any risk( about performance, security or memory) ?

Tung Vo
  • 2,227
  • 5
  • 27
  • 45
  • check it http://stackoverflow.com/questions/12624671/how-shared-preference-can-be-differ-from-static-global-variable-of-one-class – Linh Feb 22 '17 at 02:22

1 Answers1

3

NO, it's not recommended to do it.

global static variable has same lifetime as your Application, data will be destroyed once Application is finished. SharedPreference on the other hand can persist the data until user has clear the storage/cache of your app through app settings.

The better approach is to have a Repository that can be shared as a DataSource for your application.

In case you accidentally have a static reference to a Context, than there will be a memory leak.

see more Android : Static Fields and Memory Leaks

Community
  • 1
  • 1
WenChao
  • 3,586
  • 6
  • 32
  • 46