转载请注明出处:SharedPreferences数据存储_Mr_Leixiansheng的博客-CSDN博客
步骤:
1、创建SharedPreferences.Editor对象
SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE);
2、存储数据 xx.put(key,value)
3、创建SharedPreferences
SharedPreferences read = getSharedPreferences("data", MODE_PRIVATE);
4、读取数据xxx.getxx(key,"")
代码如下:
package com.example.administrator.sharedpreferences;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button button,button2;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.show);
button = (Button) findViewById(R.id.button);
button2 = (Button) 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.putBoolean("boolen", false);
//添加整型
editor.putInt("age", 20);
//提交
editor.commit();
Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show();
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//读取数据
SharedPreferences read = getSharedPreferences("data", MODE_PRIVATE);
//读取字符型
String name = read.getString("name", "");
//读取整型
String age = String.valueOf(read.getInt("age", 0));
//显示读取的数据
textView.setText("get name is " + name + "\n"
+ "get age is " + age);
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.administrator.sharedpreferences.MainActivity">
<TextView
android:id="@+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="43dp"
android:layout_marginTop="81dp"
android:id="@+id/button" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/button"
android:layout_alignParentEnd="true"
android:layout_marginEnd="46dp"
android:id="@+id/button2" />
</RelativeLayout>