Android Studio:SharedPreferences在活动之间无效

时间:2017-03-29 19:14:52

标签: android session sharedpreferences

我目前正在开发一个Android应用程序,我希望使用JDBC为SQL和SharedPreferences添加一个登录/注销系统来处理会话,SQL工作正常,但是当我从登录活动转到主要活动并尝试获取共享首选项中的值,它返回默认值。

这是我的登录活动:

private TextView usernameHeader, passwordHeader;
private EditText username, password;
private Button loginButton;
private Handler alertHandler;
private String userRes, passwdRes;
SharedPreferences sharedPreferences;
public static final String MySession = "MySession";
public static final String nameField = "nameKey";
public static final String passwordField = "passwordKey";

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

    loginButton = (Button) findViewById(R.id.loginButton);

    username = (EditText) findViewById(R.id.username);
    password = (EditText) findViewById(R.id.passwd);

    loginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            sqlThread.start(); //The loginIntent is called inside the thread using a handler
        }
    });

}

public void loginIntent(){

    try{
        sharedPreferences = getSharedPreferences(MySession, Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = sharedPreferences.edit();

        editor.putString(nameField, userRes);
        editor.putString(passwordField, passwdRes);
        editor.apply();
        //editor.commit();

    }catch (Exception ex){
        ex.printStackTrace();
    }

    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
    startActivity(intent);

}

这是我的主要活动:

SharedPreferences sharedPreferences;
private String name;

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

    submitButton = (Button) findViewById(R.id.submitButton);

    mMapView = (MapView) findViewById(mapView);
    map = new ArcGISMap(Basemap.Type.TOPOGRAPHIC, 34.056295, -117.195800, 16);
    mMapView.setMap(map);

    sharedPreferences = getSharedPreferences(LoginActivity.MySession, Context.MODE_PRIVATE);

    name = (String) sharedPreferences.getString(LoginActivity.nameField,"");

    Toast.makeText(MainActivity.this,name,Toast.LENGTH_LONG).show();
}

Toast输出为空。

2 个答案:

答案 0 :(得分:0)

尝试editor.commit()

editor.apply()是异步的。并且您的LoginActivity直接跳转到主要活动并请求存储的信息。 可能是MainActivity在将字符串提交到存储之前请求字符串。

答案 1 :(得分:0)

您是否尝试过检查变量userRespasswdRes的值?根据您在帖子中提供的代码,它们可能尚未初始化。