0

I don't understand this mistake :/

I try to save the user name in a Shared Preferences but I have the null object but in my code, I have somethings : for example, if the admin connects, the user name saved is "Administrateur" but the error tells me that the object is empty.

Here is my code :

public class SharedPreferencesUtils {

    public  static final String SHARED_KEY_RESULTS= "TABLEAU";

    public SharedPreferencesUtils() {
    }

    private static WeakReference<SharedPreferences> sharedPref;
    private static Context mContext;

    private static final String PREF_NAME = "MY_PREFRRENCES";

    public synchronized static void init(Context context) {
        if (mContext == null) {
            mContext = context;
            sharedPref = new WeakReference<>(context
                    .getSharedPreferences(PREF_NAME, Activity.MODE_PRIVATE));
        }
    }

    private static SharedPreferences getSharedPref() {
        if (sharedPref == null || sharedPref.get() == null) {
            sharedPref = new WeakReference<>(mContext
                    .getSharedPreferences(PREF_NAME, Activity.MODE_PRIVATE));
        }

        return sharedPref.get();
    }


    //region STRING PREF
    public static void setStringPreference(final String key, final String value) {
        SharedPreferences.Editor editor = getSharedPref().edit();
        editor.putString(key, value);
        editor.apply();
    }

    public static String getStringPreference(final String key) {
        return getSharedPref().getString(key, null);
    }

    public static String getStringPreference(final String key, String defaultValue) {
        return getSharedPref().getString(key, defaultValue);
    }
    //endregion

    public static void removePreference(String key) {
        SharedPreferences.Editor editor = getSharedPref().edit();
        editor.remove(key);
        editor.apply();
    }


    public static void clearAllPreferences() {
        SharedPreferences.Editor editor = getSharedPref().edit();
        editor.clear();
        editor.commit();
    }

}

Main Activity

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    name_user = new String[2];

    TextView login_titre = (TextView) findViewById(R.id.login_label);

    username = (EditText) findViewById(R.id.edit_user);
    password = (EditText) findViewById(R.id.edit_password);

    Button checking = (Button) findViewById(R.id.button);

    Police police = new Police();
    police.setFont(Login.this, login_titre, "LemonMilklight.otf");

    checking.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(CheckLogin.ENDPOINT)
                    .build();
            CheckLogin api = retrofit.create(CheckLogin.class);

            api.Check(
                    username.getText().toString(),
                    password.getText().toString()).enqueue(

                    new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                            BufferedReader reader = null;

                            String output = "";
                            try {

                            reader = new BufferedReader(new InputStreamReader(response.body().byteStream()));

                                output = reader.readLine();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                            Toast.makeText(Login.this, output, Toast.LENGTH_LONG).show();

                            name_user = output.split(" ");
                            String save_name = name_user[1];

                            try {
                                SharedPreferencesUtils.setStringPreference("Utilisateur", save_name);
                            } catch (Exception e) {
                                Log.e("Erreur", e.getMessage());
                            }

Thanks for you help. :)

Aj 27
  • 2,316
  • 21
  • 29
Maxime
  • 45
  • 1
  • 2
  • 5
  • What kind of error are you getting, and where? – Lance Toth Mar 09 '18 at 13:50
  • D/save_name: Administrateur E/Erreur: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference The error is at the first try – Maxime Mar 09 '18 at 13:53
  • where you have initialised your shared preference? – Aj 27 Mar 09 '18 at 13:53
  • In case of getSharedPreferences context is the null object – Lance Toth Mar 09 '18 at 13:55
  • Yes, I try but the mistake is always present. when you say "initialised", you say : SharedPreferencesUtils shared = new SharedPreferencesUtils() ? – Maxime Mar 09 '18 at 13:55
  • I find the solution : in my SharedPreferencesUtils, I forget to launch the init function which allows to recover the context :) – Maxime Mar 09 '18 at 14:00

2 Answers2

1

Firstly this is the format for share preference (USE APPLY INSTEAD OF COMMIT)

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();

editor.putString("username", username);
editor.putString("password", password);
editor.apply();

Intent intent = new Intent(MainActivity.this, OtherActivity.class);                            
startActivity(intent);

To access:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

String username = preferences.getString("username", "fail");
String password = preferences.getString("password", "fail");

Another alternative is done here by this user (upvote him if he answered you)

Thabiso Motswagole
  • 146
  • 1
  • 2
  • 17
1

If you never call init(...) in SharedPreferencesUtils, mContext is always null

Lance Toth
  • 430
  • 3
  • 17