我会在用户第一次打开应用程序时保存用户名和密码,并将其存储在 SharedPreferences 对象中。我在他第二次输入时检查数据,如果数据不为空,那么我就进入了应用程序。我的做法如下:
private SharedPreferences dhj;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dhj = this.getSharedPreferences("DHJ", MODE_WORLD_READABLE);
if(dhj.getString("username", null) != null) {
setContentView(R.layout.main);
// do some stuff...
}
else {
setContentView(R.layout.login);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
loginButton = (Button) findViewById(R.id.loginButton);
loginButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor dhjEditor = dhj.edit();
dhjEditor.putString("username", username.getText().toString());
dhjEditor.putString("password", password.getText().toString());
setContentView(R.layout.main);
}
});
// do some other stuff...
}
}
但是每次我打开应用程序时,系统都会要求我输入用户名和密码。
我究竟做错了什么?如何才能实现所需的功能?
谢谢。
最佳答案
请注意,editor.commit()
函数是执行文件系统操作的同步函数。从主线程调用它(您的代码似乎在主线程中运行)可能 - 在不幸的情况下 - 抛出 ANR,因为文件系统操作可能会停止并从而阻塞主线程。
我会使用 editor.apply()
函数,因为它会立即更新共享首选项的内存缓存,然后创建一个工作线程并将值写入您的共享首选项从那里读取文件(工作线程不会阻塞主线程)。
http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply ()
关于android - 共享首选项android基本问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7027568/