简体   繁体   中英

Not able to read/write data properly from shared preferences from different activities

I am trying to check if a user has already logged into my android application using shared preference.

I have a flash screen where I try to read userID from the shared preferences and if the userID is not present I will start the login activity or else I will redirect to the home activity.

Flash Screen :

  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    final int vendorId = prefs.getInt("vendorId", 0);
    if (0 == vendorId) {
        /* New Handler to start the Menu-Activity
     * and close this Splash-Screen after some seconds.*/
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
            /* Create an Intent that will start the Menu-Activity. */
                Intent mainIntent = new Intent(WelcomeFlashScreen.this, LoginActivity.class);
                WelcomeFlashScreen.this.startActivity(mainIntent);
                WelcomeFlashScreen.this.finish();
            }
        }, SPLASH_DISPLAY_LENGTH);
    }
    else
    {
            /* New Handler to start the Menu-Activity
     * and close this Splash-Screen after some seconds.*/
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
            /* Create an Intent that will start the Menu-Activity. */
                Intent mainIntent = new Intent(WelcomeFlashScreen.this, HomeActivity.class);
                mainIntent.putExtra(Constants.VENDOR_ID,vendorId);
                WelcomeFlashScreen.this.startActivity(mainIntent);
                WelcomeFlashScreen.this.finish();
            }
        }, SPLASH_DISPLAY_LENGTH);
    }
}

And I in the login activity if the login is successful I have the below code to populate the data to shared preferences.

if ("success".equals(status)&&"".equals(errorCode)) {
                String vendorId = rootJsonObject.get("data").getAsJsonObject().get("id").getAsString();
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                prefs.edit().putString(Constants.VENDOR_ID, vendorId).commit();
                loginSucces();
            }

I debugged through the code and saw that no exception is coming while reading/writing from the preferences but somehow even after putting the data in loginActivity I am not able to read the data from the flash screen activity.

Thanks in advance.

您正在使用putString(...)编写字符串,但尝试使用getInt(...)将其作为Int读取

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