简体   繁体   中英

Global static variable or shared preference android

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) ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM