【问题标题】:How do I make a shared library for SharedPreference?如何为 SharedPreference 创建一个共享库?
【发布时间】:2019-06-22 18:33:07
【问题描述】:

我正在开发一个包含很多模块的应用程序,我需要从我在 :app 应用程序中创建的名为 SharedPrefManagerSharedPreference 类加载数据,这是我实现的应用程序其他模块到一个名为:mediplan 的模块中,我只想检索我保存在SharedPrefManager 中的ID。

我尝试在有问题的模块:mediplan 中实现依赖项,但最终出现了很多错误,所以我返回并取消了依赖项。

SharedPrefManager 类:

package com.example.tuteur;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

public class SharedPrefManager {

    private static final String SHARED_PREF_NAME = "CIN";
    private static final String IDCONT = "con";
    private static final String malade = "malade";
    private static SharedPrefManager mInstance;
    private static Context ctx;

    public SharedPrefManager(Context context) {
        ctx = context;
    }
    public static synchronized SharedPrefManager getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new SharedPrefManager(context);
        }
        return mInstance;
    }

    public void setIdCont(String id) {
        SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(IDCONT, id);

        editor.apply();
    }

    //this method will give the logged in user
    public String getIdCont() {
        SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getString(IDCONT, null);
    }



    //this method will give the logged in user
    public void setMalade(String malade) {
        SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(malade, malade);

        editor.apply();
    }

    //this method will give the logged in user
    public String getMalade() {
        SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getString(malade, null);
    }

    //this method will log the user out
    public void logout() {
        SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();
    }
}

【问题讨论】:

    标签: android android-studio shared-libraries sharedpreferences


    【解决方案1】:

    我找到的解决方案是使用 put extras 和 put bundle 而不是使用共享库

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      • 1970-01-01
      • 1970-01-01
      • 2019-04-17
      • 2020-02-05
      相关资源
      最近更新 更多