为什么这个上下文总是返回null?
问题描述:
我想获得应用程序上下文以便在非活动类中使用glide。 但它总是返回null。这是我正在使用的代码 - 我该如何解决这个问题?为什么这个上下文总是返回null?
我创建了Contextor以获取应用程序上下文以在非活动模型中使用。
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;
}
}
在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();
}
答
为什么这种情况下总是返回null?
因为您从未拨打init(Context context)
对Contextor.getInstance()
。顺便说一句,似乎有点矫枉过正有这个对象时,你可以轻松地分配给parent.getContext()
mContext
+0
谢谢@Blackbelt这是我的错。解决了它 – LIPONEF
答
它,因为你的Contextor
没有任何背景,首先提供了一个环境,然后从那里。
我会建议使用适配器的contructor
这样
Context ctx;
public RecyclerViewNewfeedAdapter(List<Post> mPostList, Context context) {
this.mPostList = mPostList;
this.ctx = context;
}
它,因为你的'Contextor'没有任何背景,首先提供了一个环境,然后从那里。 –
你在哪里启动了Contextor – 6155031