简体   繁体   中英

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. 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

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

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,

 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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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