null对象引用上的android.content.Context.getSharedPreferences(java.lang.String,int)'

时间:2018-03-09 13:46:56

标签: java android compiler-errors sharedpreferences

我不明白这个错误:/

我尝试将用户名保存在共享首选项中,但我有空对象,但在我的代码中,我有一些东西:例如,如果管理员连接,保存的用户名是“Administrateur”,但错误告诉我该对象是空的。

这是我的代码:

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();
    }

}

主要活动

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());
                            }

谢谢你的帮助。 :)

2 个答案:

答案 0 :(得分:1)

如果您从未在init(...)中致电SharedPreferencesUtilsmContext始终为空

答案 1 :(得分:0)

首先,这是共享偏好(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);

访问:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

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

另一种选择是通过这个user来完成的(如果他回答你的话,请给予他)