【问题标题】:SharedPreference cannot save data across activitiesSharedPreference 无法跨活动保存数据
【发布时间】:2016-01-06 08:34:06
【问题描述】:

我正在处理一个启动屏幕,它将根据 SharedPreference 存储的值确定用户之前是否已注册。

请允许我再问一次这个问题,因为我已经阅读了很多帮助/教程和示例,但它没有一点帮助。我已经被困在这里 2 天了...任何帮助都非常感谢。

涉及 2 项活动。该应用程序以 SplashScreen 活动启动,然后如果 sharepreference 文件返回非空(表示用户之前注册过),它将启动 mainactivity。否则,如果 sharepreference 文件返回 null(表示第一次用户,它将用户带到注册活动)...

问题:每当应用程序重新启动(即使用户已注册),它总是会进入注册页面!请帮忙 !!

SPLASHSCREEN 活动代码

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

    Thread timerThread = new Thread(){
        public void run(){
            try{
                sleep(3000);
            }catch(InterruptedException e){
                e.printStackTrace();
            }finally{

            }
        }
    };
    timerThread.start();

}

protected void onStart() {
    super.onStart();
    openNextActivity();
}

public void openNextActivity(){

    SharedPreferences sp = getSharedPreferences("pref", 0);
    if (sp.contains("Name")) {
        Intent intent = new Intent(SplashScreen.this, MainActivity.class);
        startActivity(intent);
    } else {
        Intent intent = new Intent(SplashScreen.this, Registration.class);
        startActivity(intent);
    }

}

@Override
protected void onPause() {
    super.onPause();
    finish();
}

下面是注册活动的代码...

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

    etName = (EditText) findViewById(R.id.etName);
    etEmail = (EditText) findViewById(R.id.etEmail);
    etMobilePhone = (EditText) findViewById(R.id.etMobilePhone);
    tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); // imei

    btnSubmit = (Button) findViewById(R.id.btnSubmit);
    btnSubmit.setOnClickListener(this);


}


public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btnSubmit:
            writePref();
            break;
    }
    finish();
}


private void writePref() {

    String userName  = etName.getText().toString();             //prepare variables values for write
    String userPhone  = etMobilePhone.getText().toString();     //prepare variables values for write
    String userEmail  = etEmail.getText().toString();           //prepare variables values for write
    String userImei = tel.getDeviceId().toString();             //prepare variables values for write

    SharedPreferences sp = getSharedPreferences("pref", 0);     //sharepreference
    SharedPreferences.Editor editor = sp.edit();                //sharepreference
    editor.putString(Name, userName);                           //write sharepreferences
    editor.putString(Phone, userPhone);                         //write sharepreferences
    editor.putString(Email, userEmail);                         //write sharepreferences
    editor.putString(Imei, userImei);                           //write sharepreferences
    editor.commit();                                            //sharepreference

    Toast toast = Toast.makeText(getApplicationContext(), "updated sharepreferences", Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL,0,50);
    toast.show();

}

请指引我正确的方向。感谢您阅读和回复。

【问题讨论】:

  • 首先,当您执行 putString() 时,Name 的值是什么。第二而不是包含尝试以这种方式使用它if(sp.getString("Name")!="")
  • Name 的值将基于来自 layout_screen 的任何用户键入,用户输入。另外,我在此之前尝试了 if(sp.getString("Name")!="") 的 if 语句,即使在用户注册后,应用程序仍然会进行注册。有什么想法吗?
  • 替换 editor.putString(Name, userName); with editor.putString("Name", userName);
  • 试试我说的方法,看看它是否仍然为空

标签: android sharedpreferences


【解决方案1】:

将您的 openNextActivity() 方法更改为:

public void openNextActivity(){

    SharedPreferences sp = getSharedPreferences("pref", 0);
    String defaultValue = "na";
    String storedValue = sp.getString("Name", defaultValue);

    if (!storedValue.equalsIgnoreCase("na")) {
        Intent intent = new Intent(SplashScreen.this, MainActivity.class);
        startActivity(intent);
    } else { //if you get default value i.e. "na"
        Intent intent = new Intent(SplashScreen.this, Registration.class);
        startActivity(intent);
    }

}

不是检查键是否存在,而是检查它的值。如果未找到键,则返回默认值,并检查返回的值。

更新(来自 Jelle 下面的评论):同时更改您的 RegistrationActivity。把editor.putString(Name, userName);改成editor.putString("Name", userName);

【讨论】:

  • 同时更改您的RegistrationActivity。将 editor.putString(Name, userName); 更改为 editor.putString("Name", userName); 如果您同时更改这两个内容,它将起作用。
  • !sp.contains("Name").equalsIgnoreCase("na") 无法编译。布尔原语没有方法。我想你的意思可能是!storedValue.equalsIgnoreCase(defaultValue);
  • true,它是一个布尔值。
  • 我的错。因为我在文本编辑器中编辑错过了替换该部分。现在变了。它应该是if (!storedValue.equalsIgnoreCase("na"))。声明了要放在这里的变量,但错过了替换。感谢您指出。
【解决方案2】:

谢谢大家...想分享解决方案...

SharedPreferences sp = getSharedPreferences("pref", 0);     //sharepreference
    SharedPreferences.Editor editor = sp.edit();                //sharepreference
    editor.putString("Name", userName);                           //write sharepreferences
    editor.putString("Phone", userPhone);                         //write sharepreferences
    editor.putString("Email", userEmail);                         //write sharepreferences
    editor.putString("Imei", userImei);                           //write sharepreferences
    editor.commit();                                            //sharepreference

显然,解决方案是“”......感谢所有优秀的人......

【讨论】:

  • 如果您不知道为什么引号会有所不同:双引号内的文本被解释为字符串文字。如果省略引号,则编译器正在寻找该名称的变量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-27
  • 1970-01-01
  • 1970-01-01
  • 2016-10-09
  • 1970-01-01
相关资源
最近更新 更多