我正在尝试使用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; } }}
我开始使用mainactivity之前尝试检查用户名值.
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(); }
但用户名始终为null.请帮忙.谢谢
解决方法:
写下代码而不是代码将用户名保存到共享首选项中.
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","");
总结 以上是内存溢出为你收集整理的android – sharedpreferences返回null值全部内容,希望文章能够帮你解决android – sharedpreferences返回null值所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)