【问题标题】:android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference [duplicate]android.content.Context.getSharedPreferences(java.lang.String, int)' 在空对象引用上[重复]
【发布时间】:2018-08-18 02:39:03
【问题描述】:

我不明白这个错误:/

我尝试将用户名保存在共享首选项中,但我有空对象,但在我的代码中,我有一些东西:例如,如果管理员连接,保存的用户名是“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());
                            }

感谢您的帮助。 :)

【问题讨论】:

  • 你遇到什么样的错误,在哪里?
  • D/save_name: Administrateur E/Erreur: 尝试在空对象引用上调用虚拟方法 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)'错误是在第一次尝试
  • 你在哪里初始化了你的共享偏好?
  • 如果 getSharedPreferences 上下文是空对象
  • 是的,我尝试过,但错误总是存在。当你说“初始化”时,你说: SharedPreferencesUtils shared = new SharedPreferencesUtils() ?

标签: java android compiler-errors sharedpreferences


【解决方案1】:

如果您从未在SharedPreferencesUtils 中调用init(...),则mContext 始终为空

【讨论】:

    【解决方案2】:

    首先这是共享偏好的格式(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 在这里完成了另一种选择(如果他回答了你,请给他投票)

    【讨论】:

      猜你喜欢
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多