SharedPreferences

public class MainActivity extends AppCompatActivity {
private Button bt;
private Button btn;
private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt = (Button) findViewById(R.id.bt);
        btn = (Button) findViewById(R.id.btn);
        tv = (TextView) findViewById(R.id.tv);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
                editor.putString("name","tom");
                editor.putInt("age",15);
                editor.putBoolean("married",false);
                editor.apply();
            }
        });
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sh = getSharedPreferences("data",MODE_PRIVATE);
                String name = sh.getString("name","");
                int age = sh.getInt("age",0);
                Boolean married = sh.getBoolean("married",false);
                tv.setText(name);
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}

建议存之前要先清除以前的数据,不论有没有,如果要清除就   editor.clear();
   editor.commit();

posted @ 2017-08-07 22:05  劳猿外  阅读(125)  评论(0编辑  收藏  举报