简体   繁体   English

SharedPreferences值未更新

[英]SharedPreferences value is not updating

I make a sharedpreference , but every time i call it it just dont update the value 我设置了sharedpreference,但是每次调用它时都不会更新值

package com.example.david.tesztapp;

 import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.provider.SyncStateContract;
import android.util.Log;

public  class SessionManagement {

// Shared Preferences
SharedPreferences pref;

// Editor for Shared preferences
Editor editor;

// Context
Context _context;

// Shared pref mode
int PRIVATE_MODE = 0;


private static SessionManagement sInstance;

// Sharedpref file name
private static final String PREF_NAME = "LoginSession";

// All Shared Preferences Keys
public static final String IS_LOGIN = "IsLoggedIn";

// User name (make variable public to access from outside)
 public  static final String KEY_NAME = "name";

// Email address (make variable public to access from outside)
//public static final String KEY_EMAIL = "email";

// Constructor
public SessionManagement(Context context){
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME,PRIVATE_MODE);
    editor = pref.edit();
    //editor.clear();
}

public static synchronized void initializeInstance(Context context) {
    if (sInstance == null) {
        sInstance = new SessionManagement(context);
    }
}

public static synchronized SessionManagement getInstance() {
    if (sInstance == null) {
        throw new IllegalStateException(SessionManagement.class.getSimpleName() +
                " is not initialized, call initializeInstance(..) method first.");
    }
    return sInstance;
}
/**
 * Create login session
 * */
public void createLoginSession(String name){

    editor.clear();
    editor.apply();
    // Storing login value as TRUE

    editor.putBoolean(IS_LOGIN, true);

    // Storing name in pref
   editor.putString(KEY_NAME, name);

    // Storing email in pref
  //  editor.putString(KEY_EMAIL, email);

    // commit changes
    editor.apply();

    Log.i("Editor",""+IS_LOGIN);
}

/**
 * Check login method wil check user login status
 * If false it will redirect user to login page
 * Else won't do anything
 * */
public void checkLogin(){
    // Check login status
    if(!this.isLoggedIn()){
        // user is not logged in redirect him to Login Activity
        Intent i = new Intent(_context, LoginActivity.class);
        // Closing all the Activities
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Add new Flag to start new Activity
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Staring Login Activity
        _context.startActivity(i);
    }


}



/**
 * Get stored session data
 * */
public HashMap<String, String> getUserDetails(){
    HashMap<String, String> user = new HashMap<String, String>();
    // user name
     user.put(KEY_NAME, pref.getString(KEY_NAME, null));

    // user email id
   // user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));

    // return user
    return user;
}

/**
 * Clear session details
 * */
public void logoutUser(){
    // Clearing all data from Shared Preferences
    editor.clear();
    editor.commit();

    // After logout redirect user to Loing Activity
    Intent i = new Intent(_context, LoginActivity.class);
    // Closing all the Activities
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    // Add new Flag to start new Activity
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    // Staring Login Activity
    _context.startActivity(i);
}

/**
 * Quick check for login
 * **/
// Get Login State
public boolean isLoggedIn(){
    return pref.getBoolean(IS_LOGIN, false);

}
}

and then i call it in asynctask 然后我在asynctask中称它为

@Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread
        pdLoading.dismiss();

       Log.i("Result "," "+result);



        if(result.equalsIgnoreCase("true")){
            /* Here launching another activity when login successful. If you persist login state
            use sharedPreferences of Android. and logout button to clear sharedPreferences.
             */
            Log.i("User ","  correct ");

            session.createLoginSession("USER");


            Intent intent = new Intent(getApplicationContext(),SuccessActivity.class);
            startActivity(intent);
            finish();


        }else if (result.equalsIgnoreCase("false")){

            // If username and password does not match display a error message
           Toast toast = Toast.makeText(LoginActivity.this, "Helytelen felhasználónév vagy jelszó", Toast.LENGTH_LONG);
            toast.show();

        } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {

            Toast toast = Toast.makeText(LoginActivity.this, "Csatlakozási hiba történt!", Toast.LENGTH_LONG);
            toast.show();

        }

        Log.i("Sess ",""+session.IS_LOGIN);

and added this to oncreate 并将其添加到oncreate

SessionManagement session = new SessionManagement(getApplicationContext());

in DDMS i see thar sharedpreference is created but its just dont update the value 在DDMS中,我看到thar sharedpreference已创建,但它只是不更新​​值

Can you try this 你可以试试这个吗

public void createLoginSession(String name){
     editor = pref.edit();
    editor.putBoolean(IS_LOGIN, true);
   editor.putString(KEY_NAME, name);
    // commit change
    editor.commit(); // replace commit with apply
    Log.i("Editor",""+IS_LOGIN);
}

Update 更新

Use Application Class 使用应用程序类别

public class ApplicationBase extends Application {

    public static SharedPreferences mSharedPreferences;
    public static SharedPreferences.Editor editor;

    @Override
    public void onCreate() {
        super.onCreate();
        mSharedPreferences = getSharedPreferences("MYPREF", MODE_PRIVATE);
        editor = mSharedPreferences.edit();
    }

    public static SharedPreferences getmSharedPreferences() {
        return mSharedPreferences;
    }

    public static void setmSharedPreferences(SharedPreferences mSharedPreferences) {
        ApplicationBase.mSharedPreferences = mSharedPreferences;
    }

    public static SharedPreferences.Editor getEditor() {
        return editor;
    }

    public static void setEditor(SharedPreferences.Editor editor) {
        ApplicationBase.editor = editor;
    }
}

Define this in Application class 在应用程序类中定义

// All Shared Preferences Keys
public static final String IS_LOGIN = "IsLoggedIn";

// User name (make variable public to access from outside)
 public  static final String KEY_NAME = "name";

Add Like This 像这样添加

ApplicationBase.getEditor().putBoolean(IS_LOGIN,true).commit();
ApplicationBase.getEditor().putString(KEY_NAME, name).commit();

Get like this 像这样

ApplicationBase.getmSharedPreferences().getString(KEY_NAME, "");
ApplicationBase.getmSharedPreferences().getBoolean(IS_LOGIN, false);

Do this change and let me know it works or not.. 进行此更改,然后让我知道它是否有效。

    public void createLoginSession(String name)
{
editor.putBoolean(IS_LOGIN, true);
editor.putString(KEY_NAME, name);
editor.apply();
Log.i("Editor",""+IS_LOGIN);
}

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

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