我如何为SharedPreference创建共享库?

问题描述 投票:0回答:1

我正在其中有很多模块的应用程序中工作,我需要从我在其中实现了SharedPreference应用程序的SharedPrefManager应用程序中称为:app的类中加载数据。其他模块合并到名为: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个回答
0
投票
我发现的解决方案是使用put extras和put bundle而不是使用共享库
© www.soinside.com 2019 - 2024. All rights reserved.