【Android Studio】数据持久化(二)SharedPreferences
作者:互联网
package com.example.myapplication; import androidx.appcompat.app.AppCompatActivity; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button=findViewById(R.id.button1); Button button2=findViewById(R.id.button2); button.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",18); editor.putBoolean("married",false); //提交文件 editor.apply(); } }); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //创建一个SharePreferences对象 SharedPreferences pref=getSharedPreferences("data",MODE_PRIVATE); //通过这个对象获取数据 String name = pref.getString("Name", "_ _"); int age = pref.getInt("Age", 500); boolean married = pref.getBoolean("married", true); //打印数据 Log.d("MainActivity",name); Log.d("MainActivity",""+age); Log.d("MainActivity",""+married); } }); } }
标签:Log,married,Studio,editor,SharedPreferences,import,Android,android,View 来源: https://www.cnblogs.com/RikkaXl/p/15554515.html