Получите данные общего предпочтения в адаптере - PullRequest
0 голосов
/ 29 мая 2018

Погуглил и целый день пытался получить данные общего доступа в моем адаптере.У меня есть SharedPreferenceManager класс

public class SharedPrefManager {
static SharedPreferences sharedPreferences;
static Context mContext;

static int PRIVATE_MODE = 0;

private static final String PREF_NAME = "sessionPref";

static SharedPreferences.Editor editor;

public SharedPrefManager (Context context) {
    mContext = context;
    sharedPreferences = mContext.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = sharedPreferences.edit();
}

public void saveUID(Context context,String uid){
    mContext = context;
    sharedPreferences = mContext.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("UID", uid);
    editor.commit();
}
public String getUID(){
    sharedPreferences = mContext.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    return sharedPreferences.getString("UID", "");
}
public void clear(){
    editor.clear();
    editor.apply();
}
}

Я называю SharedPrefManager в любой деятельности, подобной этой

public SharedPrefManager sharedPrefManager;
public String uid

и в onCreate()

sharedPrefManager = new SharedPrefManager(mContext);
uid = sharedPrefManager.getUID();

Теперь, как получить те же данные в адаптере, так как приведенный ниже код дает ошибку в любом адаптере

SharedPrefManager sharedPrefManager = new SharedPrefManager(context);
public String uid = sharedPrefManager.getUID();

Вот мой Adapter Class

public class MyCommentAdapter extends RecyclerView.Adapter<MyCommentAdapter.MyCommentHolder> {
Context context;
private List<MyComment> commentList;

//Here I get the null pointer error
SharedPrefManager sharedPrefManager = new SharedPrefManager(context);
public String uid = sharedPrefManager.getUID();
private DatabaseReference mDatabaseReference1=FirebaseDatabase.getInstance().getReference().child("User").child(uid).child("Comment");

int Последняя строка кодаЯ хочу получить доступ к базе данных с помощью uid, поэтому мне нужно значение uid из общих настроек

public MyCommentAdapter(Context context, List<MyComment> commentList) {
    this.context = context;
    this.commentList = commentList;
}

Ответы [ 4 ]

0 голосов
/ 29 мая 2018
public class SP {
    /**
     * @param mContext
     * @param key
     * @param value
     */
    public static void savePreferences(Context mContext, String key, String value) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value).apply();
    }

    /**
     * @param context
     * @param keyValue
     * @return
     */
    public static String getPreferences(Context context, String keyValue) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        return sharedPreferences.getString(keyValue, "");
    }

    /**
     * @param mContext
     */
    public static void removeAllSharedPreferences(Context mContext) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear().apply();
    }
}
0 голосов
/ 29 мая 2018

вам нужно инициализировать ваш sharedPreferancne класс в constructor из adpater.Примерно так:

private CustomSharedPreferences customSharedPreferences;

и затем в вашем конструкторе:

public MyCommentAdapter(Context context, List<MyComment> commentList) 
{
this.context = context;
this.customSharedPrefernces = new CustomSharedPreferences(context);
this.commentList = commentList;
}
0 голосов
/ 29 мая 2018

Прежде всего, это не правильно для такого рода вещей в вашем адаптере RecyclerView, оно замедляет вас производительность прокрутки и нарушает SRP .

НО

вы можете просто вставить ваш SharedPrefManager в свой адаптер:

public class MyCommentAdapter extends RecyclerView.Adapter<MyCommentAdapter.MyCommentHolder> {

    private Context context;
    private List<MyComment> commentList;

    private SharedPrefManager sharedPrefManager;
    public String uid;

    public MyCommentAdapter(Context context, List<MyComment> commentList, SharedPrefManager sharedPrefManager) {
        this.context = context;
        this.commentList = commentList;
        this.sharedPrefManager = sharedPrefManager
        this.uid = sharedPrefManager.getUID();
    }
}

, а затем в своей деятельности при создании адаптера вы можете добавить sharedPrefManager в егоконструктор.

0 голосов
/ 29 мая 2018

Ваш context is null.Попробуй после присвоения

SharedPrefManager sharedPrefManager ;
public String uid ;
private DatabaseReference mDatabaseReference1;
public MyCommentAdapter(Context context, List<MyComment> commentList) {
    this.context = context;
    sharedPrefManager = new SharedPrefManager(context);
    this.commentList = commentList;
    uid = sharedPrefManager.getUID();
    mDatabaseReference1=FirebaseDatabase.getInstance().getReference().child("User").child(uid).child("Comment");

}
...