安卓-SharedPreferences返回null值

12
我正在尝试使用sharedpreferences来检查用户在开始使用应用程序之前是否已经登录。当用户登录时,我会将用户名保存在shredpreferences中。
Login.java
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);     
        Button btnLogin = (Button) findViewById(R.id.buttonlogin);      
        btnLogin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View adapt) {
                EditText usernameEditText = (EditText) findViewById(R.id.EditUserName);
                userName = usernameEditText.getText().toString();
                EditText passwordEditText = (EditText) findViewById(R.id.EditPassword);
                userPassword = passwordEditText.getText().toString();               
                if (userName.matches("") && userPassword.matches("")) {
                    toast("Please enter Username and Password");
                    return;
                } else if (userName.matches("") || userName.equals("")) {
                    toast("Please enter Username");
                    return;
                } else if (userPassword.matches("") || userPassword.equals("")) {
                    toast("Please enter Password");
                    return;
                } else {
                    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("MEM1", userName);
                    editor.commit();
                    new DownloadFilesTask().execute();
                }           
            }
        });
    }

    private void toast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }

    private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
        protected void onPreExecute() {
        }

        protected void onPostExecute(Void result) {
            toast("user logged in");
            startActivity(new Intent(Login.this, MainActivity.class));
            finish();
        }

        @Override
        protected Void doInBackground(Void... params) {         
            return null;
        }
    }

}

我试图在启动主活动之前检查用户名的值。

SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    String username =sharedPreferences.getString("MEM1", "");
    if(username.equalsIgnoreCase("")||username.length()==0)
    {
        toast("username is null");
        startActivity(new Intent(MainActivity.this, Login.class));
        finish();
    }

但是用户名始终为空。请帮忙,谢谢。


1
如果您的用户名曾经为null,您的应用程序将崩溃,因为不可能调用空值的方法。如果您想检查空字符串,最好使用isEmpty()。 - The incredible Jan
3个回答

27

调用getPreferences意味着你必须在同一个活动中。使用getSharedPreferences允许你在不同的活动之间共享偏好设置。只需在调用getSharedPreferences("这里是偏好设置名称", MODE_PRIVATE);时定义一个偏好设置的名称即可。


17

请使用以下代码将用户名保存到共享偏好设置中,而不是您的代码。

SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putString("MEM1", userName);
editor.commit();

使用以下代码以获取首选项值。

SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String username = myPrefs.getString("MEM1","");

4
你好,我来自未来。在API 17中,MODE_WORLD_READABLE已被弃用,它表示“创建可供全局读取的文件非常危险,并且可能导致应用程序存在安全漏洞”。解决方案是使用MODE_PRIVATE - Wiguna R

1
private final String TAXI_SPREF = "TAXI_SHARED_PREFERENCES";

//set-save data to shared preferences
SharedPreferences.Editor sPEditor = getSharedPreferences(TAXI_SPREF, MODE_PRIVATE).edit();
sPEditor.putInt("USERID", etUserID.getText().toString());
sPEditor.putString("EMAIL", etEmail.getText().toString());
sPEditor.apply();

//get data from shared preferences

SharedPreferences sharedPreferences = getSharedPreferences(TAXI_SPREF, MODE_PRIVATE);
int userID = sharedPreferences.getInt("USERID", 0);
string email = sharedPreferences.getString("EMAIL", 0);
////////     or         /////
String email = getSharedPreferences(TAXI_SPREF, MODE_PRIVATE).getString("EMAIL","EMPTY");
    if (!email.equals("EMPTY")){
        etEmail.setText(email);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接