如何检查共享preferences字符串为空或空的Andr​​oid * [英] how to check the SharedPreferences string is empty or null *android

查看:164
本文介绍了如何检查共享preferences字符串为空或空的Andr​​oid *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查共享preferences串用它来存储用户名和密码,如果用户名和密码不是null或空,将被引导到家里,否则,如果用户名和密码为空,它会被定向到登录页面。

I want to check a string in SharedPreferences used it to store username and password, so if username and password is not null or empty it will be directed to home, otherwise if the username and password is empty it will be directed to login page.

这是我的 code 以选中共享preferences字符串,但它不工作。

This is my code to check the SharedPreferences string, but it is not working..

if(PreferenceConnector.USERNAME!=null){
    Intent intent = new Intent(MainActivity.this,MainHome_Activity.class);
    startActivity(intent);
} else {
   Intent intent = new Intent(MainActivity.this,LoginFormPegawai_Activity.class);
   startActivity(intent);
}

我试图通过与这个code举杯检查它,我想这之后,我得到共享preferences字符串不为空或空..

I tried to check it through toast with this code, and after I tried this, I get SharedPreferences string is not null or empty..

btn_logout_pegawai.setOnClickListener(new OnClickListener() {
     public void onClick(View v) {

      //remove the SharedPreferences string
      PreferenceConnector.getEditor(this).remove(PreferenceConnector.USERNAME)
            .commit();
      PreferenceConnector.getEditor(this).remove(PreferenceConnector.PASSWORD)
            .commit();  

//checking the SharedPreferences  string
         if(PreferenceConnector.USERNAME!=null){
            Toast.makeText(MainHome_Activity.this,"not null", Toast.LENGTH_SHORT).show();       
         }
         else {
           Toast.makeText(MainHome_Activity.this,"null", Toast.LENGTH_SHORT).show();
        }
    }
 });

如何正确检查共享preferences字符串是否其空或空?

How can I correctly check the SharedPreferences string whether its empty or null?

谢谢..

推荐答案

做到这一点:

SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String username = myPrefs.getString("USERNAME",null);
String password = myPrefs.getString("PASSWORD",null);

如果用户名和密码是present,他们将有一个值否则会空。

if username and password are present, they will have a value otherwise they will be null.

if (username != null && password != null )
{
    //username and password are present, do your stuff
}

您不必单独检查他们的presence。试图找回自己的价值将返回null(如果没有present)或值(如present)自动完成。

You don't have to check their presence separately. Trying to retrieve their value will return null ( if not present ) or the value ( if present ) automatically.

这篇关于如何检查共享preferences字符串为空或空的Andr​​oid *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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