您的位置:首页 > Web前端

基于SP(SharedPreferences)的基本使用以及实际应用介绍

2017-04-25 16:55 465 查看
  SharedPreferences是android平台上的一个比较轻量级的存储类,主要是保存一些常用的配置比如账号密码,登录用户头像信息,用户使用点击登录判断是否第一次使用是否加载引导页,以及存取一些比较少量且类型简单的数据。

废话不多说直接进入正题,首先先介绍SP的几种简单的存取方式方法:

1)首先是准备工作,先创建一个工程,在MainActivity的XML中设置两个按钮,如下图所示:

  之后回到MainActivity中,绑定id和设置点击事件就不多说了,一个按钮负责存储信息到SP中,一个按钮负责读取SP中的内容。

2)这是自己写的存储SP的方法,当点击存储按钮后,将固定的信息存储到名为“Keeping”的SP中,“Keeping”代表文件名,此文件是可以在你的手机中找到的,“MODE_PRIVATE”代表文件类型,此文件类型代表私有化,不可被外部其它应用所访问(要是能被其他应用访问到那就坏了...)下面的代码就包括了几种基本类型数据的存储数据、移除某项数据、以及全部清除的方法(我都已经打好注释了
写的很详细 相信都能看懂),无论存什么类型的数据,put方法中都会有两个参数,类似于Map中的key - value,只有通过key才能取出value中的数据,值得注意的是无论是存储还是移除某项数据后都一定要记得提交!!!

private void save() {
// 初始化SP对象
// 两个参数 第一个参数是存储的文件名字
// 第二个参数是文件类型,MODE_PRIVATE意思为文件是私有化的
// 外部的程序不可以访问
// 这是为了保证安全
SharedPreferences.Editor editor = getSharedPreferences("keeping",MODE_PRIVATE).edit();
editor.putBoolean("first?",true);
editor.putString("How long","18+18+18");
editor.putInt("How many times",7);
editor.putFloat("I am tired",0.1f);
editor.putString("isFinish?","Feeling the body was emptied");

// 加完数据 一定要提交!!!!!!!
editor.commit();
// 移除某一个值
editor.remove("isFinish?").commit();
// 清空 (记住一定要提交)
editor.clear();
editor.commit();
}


3)下面是SP的读取,如下代码是点击读取按钮中的方法,读取步奏同样要定义一个SharedPreferences,这个要与上面的创建有所不同记得区别开来,这个sp是用来根据名字来查找应用中的SP文件,在通过key值取出value中的数据,值得注意的是get方法中也同样有两个参数,第一个为key值,第二个是假如没有取到就赋给这个key一个默认值。
private void read() {
// 现在要将存储的信息提取出来
SharedPreferences sp = getSharedPreferences("keeping",MODE_PRIVATE);
// 获取信息时有两个参数
// 第一个参数是key值
// 第二个参数是默认值 就是如果没有从文件中提取出来信息,那么就用默认值给对象赋值
boolean isFirst = sp.getBoolean("first?",false);
String str = sp.getString("Wow","我是如果没有取到值的话,那么我就是默认值");
float secondBoy = sp.getFloat("I am tired",0.3f);
int wolfAndTiger = sp.getInt("How many times",99);

Log.d("ok", isFirst + str + secondBoy + wolfAndTiger);
}


  这是进行editor.clear后的log值(因为都被清空了,所以显示的都是设置的默认值):

  这是存储后没有editor.clear的log值(key值正确的话取到的就是value中的值,key不正确取到的就是默认值):

  已上是SP的基本使用方式,通过我的简单介绍和代码中的注释,我想大家已经有了一个大概的了解了,接下来我将介绍SP的两种比较常见的应用方式:

一:用户第一次下载使用某App时都会有一个引导页,我在下面的介绍中会设置三页的ViewPager来表示引导页,当滑到引导页最后一页时点击图片进入到我们刚才上面写的MainActivity中,用户第一次安装使用会出现引导页,但是除去第一次点击进入应用之外,就都不会再次显示引导页了(除非卸载重新安装)。下面看代码:

1)首先在MainActivity中(在刚才上面写的Demo中继续操作,没有另外创建新工程)的onCreate生命周期中写下如下代码:

SharedPreferences sp = getSharedPreferences("Launcher",MODE_PRIVATE)<
1018a
span style="color:#cc7832;">;
boolean isFirst = sp.getBoolean("isFirst",true);
if (isFirst){
Intent intent = new Intent(this,GuideActivity.class);
startActivity(intent);
finish();
}
setContentView(R.layout.activity_main);


  直接取一个任意的SP文件中的boolean类型的一个key值,因为这个“Launcher”SP文件不存在,所以isFirst的值就被默认为true,所以在setContentView方法还没有走到的时候就跳转到了引导页中(注意setContentView要写在下面)下图为引导页GuideActivity中的代码:

public class GuideActivity extends AppCompatActivity {
private ArrayList<View> data;
private ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guide);

// 我们要存储启动的状态(是不是第一次启动)
SharedPreferences.Editor editor = getSharedPreferences("Launcher",MODE_PRIVATE).edit();
editor.putBoolean("isFirst",false);
editor.commit();

data = new ArrayList<>();
viewPager = (ViewPager) findViewById(R.id.vp);
View view1 = getLayoutInflater().inflate(R.layout.viewone,null);
View view2 = getLayoutInflater().inflate(R.layout.viewone,null);
View view3 = getLayoutInflater().inflate(R.layout.viewone,null);

data.add(view1);
data.add(view2);
data.add(view3);
MyAdapter adapter = new MyAdapter(this);
adapter.setData(data);
viewPager.setAdapter(adapter);

view3.findViewById(R.id.img).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(GuideActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
});
}
}


  在GuideActivity中在进行SP的存储,key为isFirst,value为false,代表用户进入过引导页,意为已经不再需要进入引导页了,其它的ViewPager滑动三张图片作为引导页比较的简单也与本题无关,就不再详细解释了。运行的效果就是安装APK后,第一次进入应用会进到引导页中,滑动到最后一页点击图片进入到MainActivity中,关闭应用后再二次三次... ...打开应用就会直接进入到MainActivity而不再进入到引导页了,除非卸载在安装。

二、第二个SP的应用点在登录页的用户名和密码的存储或是三方登陆后的用户基本信息的存储(如头像,账户名Id等)下面代码是模仿登录页进行的SP存储账号密码的操作(还是在刚才的Demo中写新代码就可以,记住要改主入口哦~):

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private EditText etName,etPsw;
private CheckBox checkBox;
private Button button;
private SharedPreferences.Editor editor;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);

etName = (EditText) findViewById(R.id.et_name);
etPsw = (EditText) findViewById(R.id.et_pass);
checkBox = (CheckBox) findViewById(R.id.checkbox_login);
button = (Button) findViewById(R.id.btn_login);

button.setOnClickListener(this);

SharedPreferences preferences = getSharedPreferences("Login",MODE_PRIVATE);
boolean isFirst = preferences.getBoolean("isFirst",false);
if (isFirst){
String name = preferences.getString("name","请输入账号");
String psw = preferences.getString("psw", "请输入密码");
etName.setText(name);
etPsw.setText(psw);
checkBox.setChecked(true);
}

}

@Override
public void onClick(View view) {
login();
}

private void login() {
editor = getSharedPreferences("Login",MODE_PRIVATE).edit();
if (checkBox.isChecked()){
String name = etName.getText().toString();
String psw = etPsw.getText().toString();
editor.putBoolean("isFirst",true);
editor.putString("name",name);
editor.putString("psw",psw);
editor.commit();
}else {
editor.clear().commit();
}
Intent intent = new Intent(this,GuideActivity.class);
startActivity(intent);
}
}


  下方为XML文件代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_login"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.kevin.day12_sp.LoginActivity">

<EditText
android:id="@+id/et_name"
android:hint="请输入账号"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<EditText
android:id="@+id/et_pass"
android:hint="请输入密码"
android:textSize="20sp"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<CheckBox
android:id="@+id/checkbox_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="记住密码"/>

<Button
android:id="@+id/btn_login"
android:text="登录"
android:textSize="30sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>


  运行代码后,只要点击的checkBox是勾选状态,退出在打开应用就会将SP中的数据显示在EditText中,取消勾选就会清空SP中的数据,来起到记住账号密码的作用(已上代码都很简单,是我认为的目前SP的几种常用方式以及粗浅的使用)但是值得注意的是SharedPreferences目前不支持多线程的使用!!!切记切记切记... ...如有写的不清楚或是不懂的地方,可以 <点击打开链接> 此处进入到GitHub中下载原项目代码。

  SP是比较简单,但是较为常用的东西,最近在总结ServerSocket的使用,因为还没有总结完成所以还没有写,但是最初给自己的任务是每周都要更新博客,所以总结了一下SP的基本使用,为一些自学Android或是刚刚接触Android开发的小伙伴提供那一点微不足道的帮助,还是那句话写博客是为了提高自己的水平,提高分为复习总结归纳、学习研发新的技术、转载分享好的亦或是今后会对自己有帮助的博客帖子,希望自己能够坚持将写博客进行到底~~能够有大神为我指路或是指教的请下面留言,我会一一回复谢谢。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android app 博客
相关文章推荐