检查共享首选项是否存在

时间:2016-02-28 11:07:19

标签: android sharedpreferences

尝试检查是否存在共享首选项。我需要的是允许用户到达页面,如果他们之前在这里(即共享偏好存在并且不等于“”)或者如果他们第一次在应用程序上将它们放到欢迎页面(即共享首选项为空白,因为用户尚未输入任何数据)。

public class PersonalDetails extends Activity {
        private SharedPreferences sharedPreferences;  


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_personal_details);


if (sharedPreferences.contains("")) {
          Intent intent = new Intent(PersonalDetails.this, Welcome.class);
            startActivity(intent);
        }

2 个答案:

答案 0 :(得分:0)

<强>尝试

public class PersonalDetails extends Activity {
    private SharedPreferences sharedPreferences;  


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_personal_details);


      if (isFirstTime()){
        Intent intent = new Intent(PersonalDetails.this,Welcome.class);
        startActivity(intent);
        }
      }



private boolean isFirstTime() {
    SharedPreferences preferences = getPreferences(MODE_PRIVATE);
    boolean ranBefore = preferences.getBoolean("RanBefore", false);
    if (!ranBefore) {
        // first time
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("RanBefore", true);
        editor.commit();
    }
    return !ranBefore;
}

答案 1 :(得分:0)

我认为getPreferences需要两个输入,如下所示。

public abstract SharedPreferences getSharedPreferences(String name,
        int mode);
// Example 
getSharedPreferences("your_app_name", MODE_PRIVATE);