【发布时间】: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);
-
试试我说的方法,看看它是否仍然为空