简体   繁体   English

SharedPreferences 在应用程序强制关闭最近的活动时被清除

[英]SharedPreferences cleared on app force close from recent activities

I have built an app that has two functionalities one to login the user by mobile OTP and a mainactivity to be displayed after login.我已经构建了一个应用程序,它具有两个功能,一个是通过移动 OTP 登录用户,另一个是登录后显示的 mainactivity。 After successful login, I can save the sharedpreferences and retrieve it in the other acitivity.成功登录后,我可以保存共享首选项并在其他活动中检索它。 But, when I force close/ kill the app from the main activity, the value of the shared preferences are not stored anymore when i relaunch the app.但是,当我从主要活动中强制关闭/终止应用程序时,当我重新启动应用程序时,不再存储共享首选项的值。

I have checked similar stackoverflow solutions too, but none resolved this我也检查过类似的 stackoverflow 解决方案,但没有解决这个问题

Below code is for the login method which stores the shared preferences,下面的代码是用于存储共享首选项的登录方法,

if (task.isSuccessful()) {
                        num = "+91" + InputPhoneNumber.getText().toString().trim();
                        DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("VerifiedUsers").child(num);

                        rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(@NonNull DataSnapshot snapshot) {
                                if (snapshot.hasChild("Active")) {
                                    String activeStatus = snapshot.child("Active").getValue().toString().trim();
                                    loadingBar.dismiss();
                                    if (activeStatus.equalsIgnoreCase("false")) {
                                        Toast.makeText(LoginActivity.this, "Congratulations, you're logged in successfully...", Toast.LENGTH_SHORT).show();
                                        SendUserToMainActivity();
                                    }
                                }
                            }
                        });
                    }
                         

Here, the definition of the sendtomain activity这里是sendtomain活动的定义

private void SendUserToMainActivity() {
    saveData();
    /*new AlertDialog.Builder(LoginActivity.this)
            .setTitle("EMPTY MOBILE NUMBER")
            .setMessage(num)

            // Specifying a listener allows you to take an action before dismissing the dialog.
            // The dialog is automatically dismissed when a dialog button is clicked.
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    InputPhoneNumber.setText("");
                }
            })
            .setIcon(android.R.drawable.ic_dialog_alert)
            .show();*/
    Intent mainIntent = new Intent(LoginActivity.this, MainActivity.class);
    mainIntent.putExtra("MobileNumber",num);
    startActivity(mainIntent);
    finish();
}

Below function saves the data to shared preferences in the login activity,下面 function 将数据保存到登录活动中的共享首选项中,

 public void saveData()
{
    /*SharedPreferences sharedPreferences=getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);
    SharedPreferences.Editor editor=sharedPreferences.edit();

    editor.putString("MobileNumber",num);*/
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("MobileNumber", num);
    editor.commit();
}

NOW WHEN I LAUNCH THE MAIN ACTIVITY AFTER FORCE CLOSE IT DOES NOT HAVE THE VALUES THAT WERE STORED Below are the function calls现在,当我在强制关闭后启动主要活动时,它没有存储的值下面是 function 调用

private void loadData() {
   /* final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    num = mSharedPreference.getString("MobileNumber", "Fault");*/
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
    loggedInMobileNumber= preferences.getString("MobileNumber", null);
}

 @Override
protected void onResume() {
    super.onResume();
    loadData();
    new AlertDialog.Builder(MainActivity.this)
            .setTitle("MOBILE NUMBER")
            .setMessage(loggedInMobileNumber)

            // Specifying a listener allows you to take an action before dismissing the dialog.
            // The dialog is automatically dismissed when a dialog button is clicked.
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            })
            .setIcon(android.R.drawable.ic_dialog_alert)
            .show();
}




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    loadData();
    Toast.makeText(MainActivity.this, loggedInMobileNumber, Toast.LENGTH_SHORT).show();}

For getting the phone number with which the user loged with firebase you don't have to save the phone number in preferences or in database you always have it from the current user, you can decrease complexity and code by using the following code要获取用户使用 firebase 登录的电话号码,您不必将电话号码保存在首选项或数据库中,您始终拥有当前用户的电话号码,您可以使用以下代码降低复杂性和代码

String phone =  FirebaseAuth.getInstance()
                            .getCurrentUser()
                            .getPhoneNumber()

I guess you need to provide a file where to save those values as following我想您需要提供一个文件来保存这些值,如下所示

 public void saveData()
{
    SharedPreferences preferences = getSharedPreferences("prefs",MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("MobileNumber", num);
    editor.apply(); //try apply instead of commit()
}

** Load Sharedpreferences value ** 加载 Sharedpreferences 值

private void loadData() {
   SharedPreferences preferences= 
    getSharedPreferences("prefs",MODE_PRIVATE);
    loggedInMobileNumber= preferences.getString("MobileNumber", null);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM