我正在其中有很多模块的应用程序中工作,我需要从我在其中实现了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();
}
}