简体   繁体   English

在所有活动中存储和访问变量的最佳方法是什么?

[英]What is the best way to store and access variables in all activities

I have an app in which I have more than 450 custom Java objects, and about 200 other variables of strings, int, etc. I know that these much variables use large RAM of the device, so I want to know the best way for storing and accessing them. 我有一个应用程序,其中有450多个自定义Java对象,以及大约200个其他字符串,int等变量。我知道这些变量使用设备的大RAM,因此我想知道存储的最佳方法并访问它们。 Some variables are used in many activities. 一些变量用于许多活动中。

you can use data base for storing variables in memory but it better to use Sharedprefrences to store all variables : 您可以使用数据库在内存中存储变量,但最好使用Sharedprefrences存储所有变量:

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 
Editor editor = pref.edit();
editor.putBoolean("key_name", true); 
editor.commit();

and easilly get the variable : 和easilly得到变量:

pref.getString("key_name", null);

I would definitely persist them to aa file since they are so many. 我肯定会坚持他们到一个文件,因为他们是如此之多。 Doing this you can load the classes in when you need them and not worry about memory 这样,您可以在需要它们时加载类,而不必担心内存

Saving custom class 保存自定义类

FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();

Loading custom Class 加载自定义类

FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
SimpleClass simpleClass = (SimpleClass) is.readObject();
is.close();
fis.close();

Here´s another question with some cool implementations of this 这是这个的一些很酷的实现的另一个问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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