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

时间:2019-03-05 15:35:18

标签: java android

我有一个应用程序,其中有450多个自定义Java对象以及大约200个其他字符串,int等变量。 我知道这些变量会占用设备的大量RAM,因此我想知道存储和访问它们的最佳方法。在许多活动中都使用了一些变量。

2 个答案:

答案 0 :(得分:0)

您可以使用数据库将变量存储在内存中,但是最好使用Sharedprefrences来存储所有变量:

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

然后easilly获得变量:

pref.getString("key_name", null);

答案 1 :(得分:0)

我肯定会把它们保存到一个文件中,因为它们太多了。这样做可以在需要时加载类,而不必担心内存

保存自定义类

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

加载自定义类

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

这是另一个question,其中包含一些很酷的实现

相关问题