11

ユーザー名とパスワードを保存するために使用される SharedPreferences の文字列を確認したいので、ユーザー名とパスワードが null または空でない場合はホームに送られ、それ以外の場合はユーザー名とパスワードが空の場合はログイン ページに送られます。

これは、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 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();
        }
    }
 });

SharedPreferences 文字列が空か null かを正しく確認するにはどうすればよいですか?

ありがとう..

4

4 に答える 4

33

これを行う:

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

ユーザー名とパスワードが存在する場合、それらは値を持ち、存在しない場合は null になります。

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

それらの存在を個別に確認する必要はありません。それらの値を取得しようとすると、null (存在しない場合) または値 (存在する場合) が自動的に返されます。

于 2012-12-17T07:56:18.403 に答える
3
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:
}

幸運を!

于 2012-12-17T08:08:52.680 に答える
2

これを試して

  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);
   }
于 2012-12-17T07:53:51.157 に答える