M
M
MadeChaos2017-02-19 14:21:57
Java
MadeChaos, 2017-02-19 14:21:57

How to properly implement SharedPreferences?

Good afternoon, I'm a newbie, there was a problem when implementing SharedPreferences, it always returns a default value.
MainActivity.java

private PreferenceEditor userPref;

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        SharedPreferences preference = this.getSharedPreferences("user_pref", Context.MODE_PRIVATE);
        userPref = new PreferenceEditor(preference);
        userPref.addUser(userDevice);
    }
 protected void onResume() {
        super.onResume();
        Toast.makeText(getApplicationContext(),"ID юзера:" + userPref.getUser(), Toast.LENGTH_LONG).show();
    }

PreferenceEditor.java //Class for working with preferences
package com.test.test.model;

import android.content.SharedPreferences;

public class PreferenceEditor {
    private SharedPreferences preference;

    public PreferenceEditor(SharedPreferences preference){
        this.preference = preference;
    }

    public void addUser(User user){
        SharedPreferences.Editor editor = preference.edit();
        editor.putLong("id", user.getId());
        editor.commit();
    }

    public long getUser(){
        return preference.getLong("id", -1);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MadeChaos, 2017-02-19
@MadeChaos

Sori, the mistake was on my part, mixed up 2 objects.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question