保存值之前关闭该应用程序?应用程序

2023-09-07 02:19:05 作者:多想一不小心就和你白了头

我想节省一些值之前,我关闭应用程序。但我不知道如果我必须创建一个新的文件(.txt),并将其保存;或者我只是可以改变的strings.xml文件,当我打开应用程序下一次保存的值将是正确的保存的值或将walues​​这是我第一次使用前定义。我知道,存在非常简单的方法,从strings.xml中读取文件,所以我认为必须有一个办法关闭之前设置在此文件中的值(但我不能在网络上找到)。感谢您的任何实例或你的意见和解释。

I want to save some values before i closed the app. But i don't know if i must create a new file(.txt) and save it in; or i just can change strings.xml file and when i open app next time the saved values will be the right saved values or will be walues which i define them before first using. I know that exist really easy way to read from strings.xml file and so i think that there must be a way to set values in this file before closing (but i can't find on the net). Thanks for any examples or yours advice and explanation.

推荐答案

Android提供的共享preferences类来帮助你节省简单的应用程序数据。 您可以使用共享preferences类,以节省您想要的配置信息或任何东西。 当您关闭应用程序,的onStop()的onDestroy()将被调用。您可以覆盖它们来实现你想要的。

Android provides the SharedPreferences class to help you save simple application data. You can use SharedPreferences class to save the config information or anything you want. When you close the application, onStop(), onDestroy() will be called. You can override them to implement what you want.

共享preferences类的用法很简单:

Usage of SharedPreferences class is very simple:

第1步:使用共享preferences写入对象

step 1: Writing with SharedPreferences object

//Create a object SharedPreferences from getSharedPreferences("name_file",MODE_PRIVATE) of Context
private SharedPreferences pref;
pref = getSharedPreferences("info", MODE_PRIVATE);
//Using putXXX - with XXX is type data you want to write like: putString, putInt...   from      Editor object
Editor editor = pref.edit();
editor.putString("key5","value5");
//finally, when you are done saving the values, call the commit() method.   
editor.commit()

第二步:阅读与共享preferences反对

step2: Reading with SharedPreferences object

//get SharedPreferences from getSharedPreferences("name_file", MODE_PRIVATE)
SharedPreferences shared = getSharedPreferences("info",MODE_PRIVATE)
//Using getXXX- with XX is type date you wrote to file "name_file"
 String string_temp = shared.getString("key5");

的MODE_PRIVATE常数指示共享preference FLE只能由APPLICA-灰创建它被打开。

The MODE_PRIVATE constant indicates that the shared preference fle can only be opened by the applica-tion that created it.

共享preferences文件保存在/ XML文件中的数据/数据​​// shared_ preFS文件夹

The shared preferences file is save as an XML file in /data/data//shared_prefs folder