I want to get Application context to use with glide in non-activity class. But it's always returning null. This is the code I'm using - how might I solve this?
I created Contextor for get application context to use in non-activity model.
public class Contextor {
private static Contextor instance;
public static Contextor getInstance() {
if (instance == null)
instance = new Contextor();
return instance;
}
private Context mContext;
private Contextor() {}
public void init(Context context) {
mContext = context;
}
public Context getContext() {
return mContext;
}
}
In myRecyclerViewAdapter.
public class RecyclerViewNewfeedAdapter extends RecyclerView.Adapter<RecyclerViewNewfeedAdapter.PostViewHolder> {
private List<Post> mPostList;
private Context mContext;
class PostViewHolder extends RecyclerView.ViewHolder {
TextView username;
TextView text;
CircleImageView profileImage;
PostViewHolder(View view) {
super(view);
username = (TextView) view.findViewById(R.id.tvPostUsername);
text = (TextView) view.findViewById(R.id.tvPostText);
}
}
public RecyclerViewNewfeedAdapter(List<Post> mPostList) {
this.mPostList = mPostList;
}
@Override
public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.post_row, parent, false);
initInstances();
return new PostViewHolder(itemView);
}
private void initInstances(){
mContext = Contextor.getInstance().getContext();
}
@Override
public void onBindViewHolder(final PostViewHolder holder, int position) {
final Post post = mPostList.get(position);
FirebaseRef.mUserInfoRef.child(post.getOwnerPost()).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
holder.username.setText(dataSnapshot.child("username").getValue(String.class));
Glide.with(mContext).load(dataSnapshot.child("profileImage").getValue(String.class)).placeholder(R.drawable.ic_default_profile_image).diskCacheStrategy(DiskCacheStrategy.ALL).into(holder.profileImage);
holder.text.setText(post.getTextPost());
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public int getItemCount() {
return mPostList.size();
}
答案 0 :(得分:3)
Why this context always returned null?
because you never call init(Context context)
on Contextor.getInstance()
. Btw, it seems a little of overkill to have this object when you can easily assign parent.getContext()
to mContext
答案 1 :(得分:0)
Its because your Contextor
doesn't have any context, first give it a context then get from there.
I would suggest using adapter's contructor
like this
Context ctx;
public RecyclerViewNewfeedAdapter(List<Post> mPostList, Context context) {
this.mPostList = mPostList;
this.ctx = context;
}