如何在android中有效的sharedpreference值? [英] How to valid sharedpreference value in android?

查看:63
本文介绍了如何在android中有效的sharedpreference值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 splashscreen 活动中检查所有这些,

I am checking all these at splashscreen activity,

所以我给这个,

SharedPreferences spf = getSharedPreferences("myprfs", Context.MODE_PRIVATE);
SharedPreferences.Editor spe = spf.edit();
String name = spf.getString("name","");
String id = spf.getString("id","");
String class = spf.getString("class","");
String roll = spf.getString("roll","");
spe.commit();

 if((spe != null) && (name != null) && (id != null) && (class != null) && (roll != null)){
     Intent i = new Intent(Startpage.this,Welcome.class);
     startActivity(i);
     Startpage.this.finish();

 }
 else{
     Intent i = new Intent(Startpage.this,MainActivity.class);
     startActivity(i);
     Startpage.this.finish();
 }

当我打开应用启动页面时,直接移动到欢迎页面,

when I open app startup page directly moves to welcome page,

但是当共享首选项中没有保存值时,我想将 splashscreen 页面移动到 MainActivity

but I want to move splashscreen page to MainActivity when there is no values saved in shared-preferences

我按照this获得共享偏好值

谁能建议我如何给出这种条件

can any one suggest me how to give condition in this kind

推荐答案

String name = spf.getString("name","");

如果它不存在,则此方法创建一个共享首选项,默认值作为第二个参数.因此,在您的情况下,当用户第一次访问应用程序时,共享首选项将保存为空字符串作为值.

This method creates a shared pref if it doesn't exist already with the default value as the second argument. So in your case, shared pref are saved with empty string as value when user visited the app for first time.

只需将您的默认值更改为 null,因为您的检查针对的是 null 值,它会起作用 -

Just change your default value to null since your checks are on null value and it will work -

String name = spf.getString("name",null);

这篇关于如何在android中有效的sharedpreference值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆