使用SharedPreferences存储如下数据到文件user.xml,写出关键代码。 <map> <boolean name="婚否" value="false" /> <string name="name">张三</string> <int name="年龄" value="20" /> </map>
时间: 2023-10-07 10:06:52 浏览: 37
好的,以下是使用SharedPreferences存储数据到文件user.xml的关键代码示例:
```java
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPreferencesExample {
public static void main(String[] args) {
// 获取SharedPreferences对象
Context context = getApplicationContext();
SharedPreferences sharedPreferences = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
// 存储数据
editor.putBoolean("婚否", false);
editor.putString("name", "张三");
editor.putInt("年龄", 20);
editor.apply(); // 提交数据
}
}
```
在这个示例中,我们首先通过Context对象获取了SharedPreferences对象,其中参数"user"表示文件名,Context.MODE_PRIVATE表示该SharedPreferences文件是私有的,只能被本应用程序访问。然后,我们通过SharedPreferences对象获取了SharedPreferences.Editor对象,并使用它向文件中存储数据。
在这个例子中,我们存储了一个boolean类型的数据、一个String类型的数据和一个int类型的数据。最后,我们调用SharedPreferences.Editor的apply()方法提交数据。