我有一个第一次启动LoginActivity的主Activity。这里一切都好。当用户登录时,用户的信息被保存在sharedpreferences中(向ApiRest发出请求),所以这个只在第一次启动登录的功能工作正常,因为下次我启动应用程序时,我会留在mainActivity中。
这个主活动有3个片段(在viewpager中),这3个片段在创建时自动请求从API获取信息。
我的问题是在mainActivity的appbar中,我有一个注销用户的菜单项。我的意图是将应用重定向到loginActivity,并清除Activity堆栈和sharedpreferences。
但我被重定向到登录活动,但当我关闭应用程序并再次打开它时,它不尊重我在主活动中的方法(如果是第一次,它必须重定向到LoginActivity),并创建3个片段,立即开始发出请求,但它们没有参数(它们为null或0,因为我清除了共享首选项),因此应用程序崩溃。
为什么第一次打开LoginActivity的方法被省略了?
下面是我的MainActivity,它的方法在注销后失败或省略:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Variables variableGlobal = (Variables)getApplicationContext();
SharedPreferences sharedPreferences= getSharedPreferences("firstTime",this.MODE_PRIVATE);
boolean firstTime = sharedPreferences.getBoolean("firstTime",true);
if(firstTime){
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putBoolean("firstTime", false);
edit.commit();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}....
以下是我的注销代码:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.logoutmain) {
//Here I clear the sharedpref datos which contains the user information
SharedPreferences pref = getSharedPreferences("datos",MODE_PRIVATE);
SharedPreferences.Editor editorpref = pref.edit();
editorpref.clear();
editorpref.commit();
//Here I clear the sharedPref that contains the value (boolean) to say the app if it is the first time or not
SharedPreferences pref2 = getSharedPreferences("firstTime",this.MODE_PRIVATE);
SharedPreferences.Editor editorpref2 = pref2.edit();
editorpref2.putBoolean("firstTime",true);
editorpref2.commit();
System.out.println("shared pref cleared");
Intent intent=new Intent(getApplicationContext(),MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
return true;
}...
以下是我的登录活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnLogin= (Button)findViewById(R.id.btnLogin);
api= ApiUtils.getAPIService();
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
login();
}
});
}
当我运行我的应用程序时,检查它是否是第一次运行它启动到LoginActivity的方法工作正常,它只在第一次和下一次启动,我总是在主活动中打开,但当我注销时,它将我重定向到登录并清除堆栈和sharedpref,* 但忽略 * 检查第一次的方法,并使我保持在主活动中,应用程序崩溃。为什么?
1条答案
按热度按时间vecaoik11#
我在你的逻辑中看到了一个问题,快速修复将在你的MainActivity中使用下面的代码: