1. Android读写首选项

1.1 SharedPreferences

  SharedPreferences 是一种轻型的数据存储方式,它的本质是基于XML文件存储Key-Value键值对数据,通常用来存储一些简单的配置信息,其存储位置在/data/data/<包名>/shared_prefs目录下。

  SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。本例程讲解 SharedPreference 数据的读写操作。

16_Android的数据存储_ SharedPreference、XML和JSON

 1 package com.example.sharedpreference;
 2 
 3 import android.app.Activity;
 4 import android.content.SharedPreferences;
 5 import android.content.SharedPreferences.Editor;
 6 import android.os.Bundle;
 7 import android.view.View;
 8 import android.widget.EditText;
 9 import android.widget.Toast;
10 
11 public class MainActivity extends Activity {
12     
13     static final String KEY = "MyValue";
14     private EditText et;
15     SharedPreferences preferences;
16     Editor editor;
17 
18     @Override
19     protected void onCreate(Bundle savedInstanceState) {
20         super.onCreate(savedInstanceState);
21         setContentView(R.layout.activity_main);
22 
23         et = (EditText) findViewById(R.id.et);
24         preferences = getPreferences(Activity.MODE_PRIVATE);
25         editor = preferences.edit();
26         
27         findViewById(R.id.btnRead).setOnClickListener(new View.OnClickListener() {
28             
29             @Override
30             public void onClick(View v) {
31                 //如果键值对不存在,就会将其改为第二个参数。
32                 String in = preferences.getString(KEY, "当前数值不存在");
33                 Toast.makeText(getApplicationContext(), in, Toast.LENGTH_SHORT).show();
34             }
35         });
36         
37         findViewById(R.id.btnWrite).setOnClickListener(new View.OnClickListener() {
38             
39             @Override
40             public void onClick(View v) {
41                 editor.putString(KEY, et.getText().toString());
42                 if (editor.commit()) {
43                     Toast.makeText(getApplicationContext(), "写入成功", Toast.LENGTH_SHORT).show();
44                 }
45             }
46         });
47     }
48 
49 }
MainActivity

相关文章:

  • 2021-05-24
  • 2021-11-20
  • 2021-12-28
  • 2021-08-29
  • 2022-12-23
  • 2022-01-06
  • 2022-12-23
  • 2018-08-21
猜你喜欢
  • 2021-05-29
  • 2022-12-23
  • 2021-04-05
  • 2021-07-26
  • 2021-12-18
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案