林志谋 灵思致远 1周前

1. 实验内容简介

SharedPreferences类,它是一个轻量级的存储类,特别适合用于保存软件配置参数。使用SharedPreferences保存数据,其背后是用xml文件存放数据,文件存放在/data/data/<package name>/shared_prefs目录下,可以通过File Expore浏览。

SharedPreferences存储数据有四个步骤:

第一步:获取SharedPreferences对象:

调用Context对象的getSharedPreferences()方法;

调用Activity对象的getPreferences()方法;

如:SharedPreferencesmysp=MainActivity.this.getSharedPreferences("MYDATA",MODE_PRIVATE); 

第二步:获取SharedPreferences.Editor对象:

Editor editor=mysp.edit();

第三步:根据不同的存储类型,调用相应的putXXX方法存储数据,或者getXXX()方法读取数据

putString (String key, String value);

putInt (String key, int value);

putBoolean (String key, Boolean value);

getString (String key, String defvalue);

getInt (String key, int defvalue);

getBoolean (String key, Boolean defvalue);

第四步:保存时需要提交当前数据

editor.commit();

 

2. UI界面布局

SharedPreferences共享参数应用


对应的大纲:

SharedPreferences共享参数应用


实际运行效果:

 

SharedPreferences共享参数应用


3. 代码编写和调试

public class MainActivity extends Activity {

    EditText  editTextName;// 声明变量

    EditText editTextNo;

    Button buttonSave;

    Button buttonRead;

    SharedPreferences  mysp;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        //绑定控件

        editTextName=(EditText)findViewById(R.id.editTextName);

        editTextNo=(EditText)findViewById(R.id.editTextNo);

        buttonSave=(Button)findViewById(R.id.buttonSave);

        buttonRead=(Button)findViewById(R.id.buttonRead);

        mysp=MainActivity.this.getSharedPreferences("MYDATA",MODE_PRIVATE);

        buttonSave.setOnClickListener(newView.OnClickListener() {

            @Override

            public void onClick(View v) {

                Stringname=editTextName.getText().toString();

                intno=Integer.parseInt(editTextNo.getText().toString());

                Editoreditor=mysp.edit();

                editor.putString("Name",name);

                editor.putInt("No",no);

                editor.commit();

                }

        });

        buttonRead.setOnClickListener(newView.OnClickListener() {

            @Override

            public void onClick(View v) {

                String  name=mysp.getString("Name", "Null");

                int  no=mysp.getInt("No", 0);

                Toast.makeText(MainActivity.this,"姓名:"+name+" 座号:"+Integer.toString(no),Toast.LENGTH_SHORT).show();

                }

        });

               

    }

}

SharedPreferences共享参数应用

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-03-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案