【发布时间】:2019-06-22 18:33:07
【问题描述】:
我正在开发一个包含很多模块的应用程序,我需要从我在 :app 应用程序中创建的名为 SharedPrefManager 的 SharedPreference 类加载数据,这是我实现的应用程序其他模块到一个名为: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