2012-12-17 130 views
7

我想檢查SharedPreferences中的一個字符串是否用它來存儲用戶名和密碼,所以如果用戶名和密碼不爲空或空它將被定向到home,否則如果用戶名和密碼是空的,它將被引導到登錄頁面。如何檢查SharedPreferences字符串爲空或空* android

這是我代碼檢查SharedPreferences字符串,但它不工作..

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

我試圖通過吐司此代碼來檢查它,我想這之後,我得到SharedPreferences字符串不爲空或空...

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

如何正確檢查SharedPreferences字符串是否爲空或空?

謝謝..

回答

22

這樣做:

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

如果用戶名和密碼都存在,他們將有一個價值,否則他們會爲空。

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

您不必單獨檢查他們的存在。嘗試檢索它們的值將自動返回null(如果不存在)或值(如果存在)。

+0

感謝,其工作.. –

+0

高興地幫助。祝你好運! –

+0

@AnupCowkur你可以檢查了這一點http://stackoverflow.com/questions/36959279/how-do-i-use-a-dialogue-in-my-android-app-just-before-the-start-of-服務 – Abhishek

1

試試這個

if(PreferenceConnector.getString("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); 
} 
2
public static final String DEFAULT_VALUE = "default"; 
public static final String ANY_FIELD = "any_field"; 

SharedPreferences prefs = context.getPreferences(Activity.MODE_PRIVATE); 
String text = prefs.getString(ANY_FIELD, DEFAULT_VALUE); 
if (text.equals(DEFAULT_VALUE)) { 
    //TODO: 
} else { 
    //TODO: 
} 

祝你好運!

-1

如果(appSettings.contains(Constants.WEATHER_SUBN_POSTION)){

 savedSubPostion = appSettings.getInt(Constants.WEATHER_SUBN_POSTION, 0); 
    } 

首先檢查其包含值

-1

只是通過方法檢查大小sp.getAll()。大小