今天在学习数据存储的时候,刚刚接触到SharedPreferences,开始的时候用的方式是我注释的那种方式,在网上看视频也是那样用的,可是我的app就是打不开,然后在网上找答案,package com.example.zhao.menu; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; /** * Created by zhao on 2017/5/14. */ public class sharepreferenced extends Activity { /* SharedPreferences mySharedPreferences;*/ EditText editText ; CheckBox checkBox; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sharedpreferencelayout); editText = (EditText) findViewById(R.id.editText); checkBox = (CheckBox) findViewById(R.id.checkBox); /* mySharedPreferences = sharepreferenced.this.getSharedPreferences("test", Activity.MODE_PRIVATE); if(mySharedPreferences!=null) { editText.setText(mySharedPreferences.getString("name","")); checkBox.setChecked(mySharedPreferences.getBoolean("yes",false)); } Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putString("name", editText.getText().toString()); editor.putBoolean("yes",checkBox.isChecked()); editor.commit(); } });*/ } public void init() { SharedPreferences sharedPreferences = getSharedPreferences("test", Activity.MODE_PRIVATE); String name = sharedPreferences.getString("name", ""); String habit = sharedPreferences.getString("habit", ""); Toast.makeText(this, "读取数据如下:"+"\n"+"name:" + name + "\n" + "habit:" + habit, Toast.LENGTH_LONG).show(); } public void store(View view) { SharedPreferences mySharedPreferences = sharepreferenced.this.getSharedPreferences("test", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putString("name", "karl"); editor.putString("habit", "sleep"); editor.commit(); Toast.makeText(this, "数据成功写入SharedPreferences!" , Toast.LENGTH_LONG).show(); } }
找了2个多小时也没解决,最后在android的脚本之家上找到了这种方式,就是SharedPreferences要封装在每个方法中用这样才不会报错
SharedPreferences 的注意事项
最新推荐文章于 2019-04-06 14:53:50 发布