Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
840 views
in Technique[技术] by (71.8m points)

how to check the SharedPreferences string is empty or null *android

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.

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);
}

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();
        }
    }
 });

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

Thanks..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Do this:

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

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
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...