为什么这个上下文总是返回 null?

Why this context always returned null?

我想获取应用程序上下文以在非activity class 中与滑行一起使用。 但它总是返回空值。这是我正在使用的代码 - 我该如何解决这个问题?

我创建了 Contextor 以获取要在非 activity 模型中使用的应用程序上下文。

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();
}

Why this context always returned null?

因为您从未在 Contextor.getInstance() 上调用 init(Context context)。顺便说一句,当您可以轻松地将 parent.getContext() 分配给 mContext

时,拥有这个对象似乎有点矫枉过正

这是因为你的 Contextor 没有任何上下文,先给它一个上下文然后从那里获取。

我建议像这样使用适配器的 contructor

Context ctx;

public RecyclerViewNewfeedAdapter(List<Post> mPostList, Context context) {
    this.mPostList = mPostList;
    this.ctx = context;
}