1 共享参数的用法
SharedPreferences是Android的一个轻量级存储工具,采用的存储结构是Key-Value的键值对方式。
共享参数的存储介质是符合XML规范的配置文件。
保存路径是:/data/data/应用包名/shared_prefs/文件名.xml 下面是一个共享参数的XML文件示例:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map>
<string name="name">Mr Lee</string>
<int name="age" value="30" />
<boolean name="married" value="true" />
<float name="weight" value="100.0" />
</map>
共享参数的使用场景:
(1)简单且孤立的数据。若是复杂且相互间有关的数据,则要保存在数据库中。
(2)文本形式的数据。若是二进制数据,则要保存在文件中。
(3)需要持久化存储的数据。在App退出后再次启动时,之前保存的数据仍然有效。 实际开发中,共享参数经常存储的数据有App的个性化配置信息、用户使用App的行为信息、临时需要保存的片段信息等。
写入数据
package com.example.chapter06.util;
import android.annotation.SuppressLint;
import android.text.TextUtils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
@SuppressLint("SimpleDateFormat")
public class DateUtil {
// 获取当前的日期时间
public static String getNowDateTime(String formatStr) {
String format = formatStr;
if (TextUtils.isEmpty(format)) {
format = "yyyyMMddHHmmss";
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(new Date());
}
// 获取当前的时间
public static String getNowTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(new Date());
}
// 获取当前的时间(精确到毫秒)
public static String getNowTimeDetail() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
return sdf.format(new Date());
}
}
package com.example.chapter06.util;
import android.content.Context;
import android.widget.Toast;
public class ToastUtil {
public static void show(Context ctx, String desc) {
Toast.makeText(ctx, desc, Toast.LENGTH_SHORT).show();
}
}
package com.example.chapter06;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.chapter06.util.DateUtil;
import com.example.chapter06.util.ToastUtil;
public class ShareWriteActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
private SharedPreferences mShared; // 声明一个共享参数对象
private EditText et_name;
private EditText et_age;
private EditText et_height;
private EditText et_weight;
private boolean bMarried = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share_write);
et_name = findViewById(R.id.et_name);
et_age = findViewById(R.id.et_age);
et_height = findViewById(R.id.et_height);
et_weight = findViewById(R.id.et_weight);
CheckBox ck_married = findViewById(R.id.ck_married);
ck_married.setOnCheckedChangeListener(this);
findViewById(R.id.btn_save).setOnClickListener(this);
// 从share.xml中获取共享参数对象
// mShared = getSharedPreferences("share", MODE_PRIVATE);
mShared=getSharedPreferences("share",MODE_PRIVATE);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
bMarried = isChecked;
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_save) {
String name = et_name.getText().toString();
String age = et_age.getText().toString();
String height = et_height.getText().toString();
String weight = et_weight.getText().toString();
if (TextUtils.isEmpty(name)) {
ToastUtil.show(this, "请先填写姓名");
return;
} else if (TextUtils.isEmpty(age)) {
ToastUtil.show(this, "请先填写年龄");
return;
} else if (TextUtils.isEmpty(height)) {
ToastUtil.show(this, "请先填写身高");
return;
} else if (TextUtils.isEmpty(weight)) {
ToastUtil.show(this, "请先填写体重");
return;
}
SharedPreferences.Editor editor = mShared.edit(); // 获得编辑器的对象
editor.putString("name", name); // 添加一个名叫name的字符串参数
editor.putInt("age", Integer.parseInt(age)); // 添加一个名叫age的整型参数
editor.putLong("height", Long.parseLong(height)); // 添加一个名叫height的长整型参数
editor.putFloat("weight", Float.parseFloat(weight)); // 添加一个名叫weight的浮点数参数
editor.putBoolean("married", bMarried); // 添加一个名叫married的布尔型参数
editor.putString("update_time", DateUtil.getNowDateTime("yyyy-MM-dd HH:mm:ss"));
editor.commit(); // 提交编辑器中的修改
ToastUtil.show(this, "数据已写入共享参数");
}
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="40dp" >
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="姓名:"
android:textColor="@color/black"
android:textSize="17sp" />
<EditText
android:id="@+id/et_name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="3dp"
android:layout_marginTop="3dp"
android:layout_toRightOf="@+id/tv_name"
android:background="@drawable/editext_selector"
android:gravity="left|center"
android:hint="请输入姓名"
android:inputType="text"
android:maxLength="12"
android:textColor="@color/black"
android:textSize="17sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="40dp" >
<TextView
android:id="@+id/tv_age"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="年龄:"
android:textColor="@color/black"
android:textSize="17sp" />
<EditText
android:id="@+id/et_age"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="3dp"
android:layout_marginTop="3dp"
android:layout_toRightOf="@+id/tv_age"
android:background="@drawable/editext_selector"
android:gravity="left|center"
android:hint="请输入年龄"
android:inputType="number"
android:maxLength="2"
android:textColor="@color/black"
android:textSize="17sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="40dp" >
<TextView
android:id="@+id/tv_height"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="身高:"
android:textColor="@color/black"
android:textSize="17sp" />
<EditText
android:id="@+id/et_height"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="3dp"
android:layout_marginTop="3dp"
android:layout_toRightOf="@+id/tv_height"
android:background="@drawable/editext_selector"
android:gravity="left|center"
android:hint="请输入身高"
android:inputType="number"
android:maxLength="3"
android:textColor="@color/black"
android:textSize="17sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="40dp" >
<TextView
android:id="@+id/tv_weight"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="体重:"
android:textColor="@color/black"
android:textSize="17sp" />
<EditText
android:id="@+id/et_weight"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="3dp"
android:layout_marginTop="3dp"
android:layout_toRightOf="@+id/tv_weight"
android:background="@drawable/editext_selector"
android:gravity="left|center"
android:hint="请输入体重"
android:inputType="numberDecimal"
android:maxLength="5"
android:textColor="@color/black"
android:textSize="17sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="40dp" >
<CheckBox
android:id="@+id/ck_married"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:checked="false"
android:text="已婚"
android:textColor="@color/black"
android:textSize="17sp" />
</RelativeLayout>
<Button
android:id="@+id/btn_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="保存到共享参数"
android:textColor="@color/black"
android:textSize="17sp" />
</LinearLayout>
读取数据
package com.example.chapter06;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Map;
@SuppressLint("DefaultLocale")
public class ShareReadActivity extends AppCompatActivity {
private TextView tv_share;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share_read);
tv_share = findViewById(R.id.tv_share);
readSharedPreferences(); // 从共享参数中读取信息
}
// 从共享参数中读取信息
private void readSharedPreferences() {
// 从share.xml中获取共享参数对象
SharedPreferences shared = getSharedPreferences("share", MODE_PRIVATE);
String desc = "共享参数中保存的信息如下:";
// 获取共享参数保存的所有映射配对信息
Map<String, Object> mapParam = (Map<String, Object>) shared.getAll();
// 遍历该映射对象,并将配对信息形成描述文字
for (Map.Entry<String, Object> item_map : mapParam.entrySet()) {
String key = item_map.getKey(); // 获取该配对的键信息
Object value = item_map.getValue(); // 获取该配对的值信息
if (value instanceof String) { // 如果配对值的类型为字符串
desc = String.format("%s\n %s的取值为%s", desc, key,
shared.getString(key, ""));
} else if (value instanceof Integer) { // 如果配对值的类型为整型数
desc = String.format("%s\n %s的取值为%d", desc, key,
shared.getInt(key, 0));
} else if (value instanceof Float) { // 如果配对值的类型为浮点数
desc = String.format("%s\n %s的取值为%f", desc, key,
shared.getFloat(key, 0.0f));
} else if (value instanceof Boolean) { // 如果配对值的类型为布尔数
desc = String.format("%s\n %s的取值为%b", desc, key,
shared.getBoolean(key, false));
} else if (value instanceof Long) { // 如果配对值的类型为长整型
desc = String.format("%s\n %s的取值为%d", desc, key,
shared.getLong(key, 0L));
} else { // 如果配对值的类型为未知类型
desc = String.format("%s\n参数%s的取值为未知类型", desc, key);
}
}
if (mapParam.size() <= 0) {
desc = "共享参数中保存的信息为空";
}
tv_share.setText(desc);
}
}