如何在适配器类中使用 get getApplicationContext() [英] How to use get getApplicationContext() in Adapter Class
问题描述
我正在使用 Firebase 用博客文章填充我的 BlogRecycleadapter 并从 Like Buttons 获得 Likes 但当设备离线并且用户按下 Like Button 时,应用程序崩溃......所以我也在尝试实现 isNetworkavailaible 的第二个条件if 语句..如下
if (!task.getResult().exists() && isNetworkStatusAvialable(getApplicationContext())){映射<字符串,对象>likesMap = new HashMap<>();likesMap.put("timestamp", FieldValue.serverTimestamp());firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).set(likesMap);} 别的 {firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).delete();}
但是我在 getApplicationContext()
中遇到了错误,从几个谷歌搜索中,我发现 getApplicationContext()
不适用于 Class,而只能用于活动.
那么我如何在这里实现 getApplicationContext??
我的 Recycle 适配器的全部代码是
package com.nepalpolice.cdp;导入 android.content.Context;导入 android.net.ConnectivityManager;导入 android.net.NetworkInfo;导入 android.os.Build;导入 android.support.annotation.NonNull;导入 android.support.v7.widget.RecyclerView;导入 android.text.format.DateFormat;导入 android.view.LayoutInflater;导入 android.view.View;导入 android.view.ViewGroup;导入 android.widget.ImageView;导入 android.widget.TextView;进口 com.bumptech.glide.Glide;导入 com.bumptech.glide.request.RequestOptions;导入 com.google.android.gms.tasks.OnCompleteListener;导入 com.google.android.gms.tasks.Task;导入 com.google.firebase.auth.FirebaseAuth;导入 com.google.firebase.firestore.DocumentSnapshot;导入 com.google.firebase.firestore.EventListener;导入 com.google.firebase.firestore.FieldValue;导入 com.google.firebase.firestore.FirebaseFirestore;导入 com.google.firebase.firestore.FirebaseFirestoreException;导入 com.google.firebase.firestore.QuerySnapshot;导入 java.util.Date;导入 java.util.HashMap;导入 java.util.List;导入 java.util.Map;导入 de.hdodenhof.circleimageview.CircleImageView;公共类 BlogRecyclerAdapter 扩展 RecyclerView.Adapter{公共列表<博客帖子>博客列表;公共上下文上下文;私有 FirebaseFirestore firebaseFirestore;私有 FirebaseAuth firebaseAuth;public BlogRecyclerAdapter(List blog_list,Context context){this.blog_list = blog_list;this.context=上下文;}@覆盖公共 ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {查看视图 = LayoutInflater.from(parent.getContext()).inflate(R.layout.blog_list_item, parent, false);上下文 = parent.getContext();firebaseFirestore = FirebaseFirestore.getInstance();firebaseAuth = FirebaseAuth.getInstance();返回新的 ViewHolder(view);}@覆盖公共无效 onBindViewHolder(最终 ViewHolder 持有人,int 位置){holder.setIsRecyclable(false);final String blogPostId = blog_list.get(position).BlogPostId;final String currentUserId = firebaseAuth.getCurrentUser().getUid();String desc_data = blog_list.get(position).getDesc();holder.setDescText(desc_data);String image_url = blog_list.get(position).getImage_url();holder.setBlogImage(image_url);String user_id = blog_list.get(position).getUser_id();//用户数据将在此处检索...firebaseFirestore.collection("Users").document(user_id).get().addOnCompleteListener(new OnCompleteListener() {@覆盖public void onComplete(@NonNull Task task) {如果(任务.isSuccessful()){String userName = task.getResult().getString("name");String userImage = task.getResult().getString("image");holder.setUserData(userName, userImage);} 别的 {//Firebase 异常}}});长毫秒 = blog_list.get(position).getTimestamp().getTime();String dateString = DateFormat.format("MM/dd/yyyy", new Date(millisecond)).toString();holder.setTime(dateString);//获取点赞数firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").addSnapshotListener(((Main2Activity) context),new EventListener() {@覆盖public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {如果 (!documentSnapshots.isEmpty()){int count = documentSnapshots.size();holder.updateLikesCount(count);}别的{持有者.updateLikesCount(0);}}});//获取赞firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).addSnapshotListener(((Main2Activity) context),new EventListener() {@覆盖public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {如果(documentSnapshot.exists()){如果 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {holder.blogLikeBtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_accent));}别的 {holder.blogLikeBtn.setImageDrawable(context.getResources().getDrawable(R.mipmap.action_like_accent));}} 别的 {如果 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {holder.blogLikeBtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_gray));}别的{holder.blogLikeBtn.setImageDrawable(context.getResources().getDrawable(R.mipmap.action_like_gray));}}}});//喜欢特征holder.blogLikeBtn.setOnClickListener(new View.OnClickListener() {@覆盖公共无效onClick(查看视图){firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {@覆盖public void onComplete(@NonNull Task task) {if (!task.getResult().exists() && isNetworkStatusAvialable(getApplicationContext())){映射<字符串,对象>likesMap = new HashMap<>();likesMap.put("timestamp", FieldValue.serverTimestamp());firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).set(likesMap);} 别的 {firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).delete();}}});}});}@覆盖公共 int getItemCount() {返回 blog_list.size();}公共类 ViewHolder 扩展 RecyclerView.ViewHolder {私人视图 mView;私有 TextView descView;私有 ImageView 博客ImageView;私人 TextView 博客日期;私人 TextView 博客用户名;私有 CircleImageView 博客用户图像;私人 ImageView blogLikeBtn;私人 TextView blogLikeCount;公共 ViewHolder(查看 itemView){超级(项目视图);mView = itemView;}公共无效setDescText(字符串descText){descView = mView.findViewById(R.id.blog_desc);descView.setText(descText);blogLikeBtn = mView.findViewById(R.id.blog_like_btn);}public void setBlogImage(String downloadUri){blogImageView = mView.findViewById(R.id.blog_image);RequestOptions requestOptions = new RequestOptions();requestOptions.placeholder(R.drawable.image_placeholder);Glide.with(context).applyDefaultRequestOptions(requestOptions).load(downloadUri).into(blogImageView);}公共无效设置时间(字符串日期){blogDate = mView.findViewById(R.id.blog_date);blogDate.setText(date);}public void setUserData(字符串名称,字符串图像){blogUserImage = mView.findViewById(R.id.blog_user_image);blogUserName = mView.findViewById(R.id.blog_user_name);blogUserName.setText(name);RequestOptions placeholderOption = new RequestOptions();placeholderOption.placeholder(R.drawable.profile_placeholder);Glide.with(context).applyDefaultRequestOptions(placeholderOption).load(image).into(blogUserImage);}public void updateLikesCount (int count){blogLikeCount = mView.findViewById(R.id.blog_like_count);blogLikeCount.setText(count + "喜欢");}}public static boolean isNetworkStatusAvialable(上下文上下文){连接管理器厘米 =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo activeNetwork = cm.getActiveNetworkInfo();返回 activeNetwork != null &&activeNetwork.isConnectedOrConnecting();}}
我调用适配器类的 HOmeFragment 是
package com.nepalpolice.cdp;导入 android.os.Bundle;导入 android.support.v4.app.Fragment;导入 android.support.v7.widget.LinearLayoutManager;导入 android.support.v7.widget.RecyclerView;导入 android.view.LayoutInflater;导入 android.view.View;导入 android.view.ViewGroup;导入 android.widget.Toast;导入 com.google.firebase.auth.FirebaseAuth;导入 com.google.firebase.firestore.DocumentChange;导入 com.google.firebase.firestore.DocumentSnapshot;导入 com.google.firebase.firestore.EventListener;导入 com.google.firebase.firestore.FirebaseFirestore;导入 com.google.firebase.firestore.FirebaseFirestoreException;导入 com.google.firebase.firestore.Query;导入 com.google.firebase.firestore.QuerySnapshot;导入 java.util.ArrayList;导入 java.util.List;/*** 一个简单的 {@link Fragment} 子类.*/公共类 HomeFragment 扩展 Fragment {私人 RecyclerView blog_list_view;私人列表<BlogPost>博客列表;私有 FirebaseFirestore firebaseFirestore;私有 FirebaseAuth firebaseAuth;私人 BlogRecyclerAdapter blogRecyclerAdapter;私有 DocumentSnapshot lastVisible;私人布尔 isFirstPageFirstLoad = true;公共 HomeFragment() {//必需的空公共构造函数}@覆盖公共视图 onCreateView(LayoutInflater inflater,最终的 ViewGroup 容器,捆绑savedInstanceState) {查看视图 = inflater.inflate(R.layout.fragment_home, container, false);blog_list = new ArrayList<>();blog_list_view = view.findViewById(R.id.blog_list_view);firebaseAuth = FirebaseAuth.getInstance();blogRecyclerAdapter = new BlogRecyclerAdapter(blog_list);blog_list_view.setLayoutManager(new LinearLayoutManager(container.getContext()));blog_list_view.setAdapter(blogRecyclerAdapter);if(firebaseAuth.getCurrentUser() != null) {firebaseFirestore = FirebaseFirestore.getInstance();blog_list_view.addOnScrollListener(new RecyclerView.OnScrollListener() {@覆盖public void onScrolled(RecyclerView recyclerView, int dx, int dy) {super.onScrolled(recyclerView, dx, dy);布尔达到底部 = !recyclerView.canScrollVertically(1);如果(到达底部){String desc = lastVisible.getString("desc");Toast.makeText(container.getContext(), "Reached : " + desc, Toast.LENGTH_SHORT).show();loadMorePost();}}});查询 firstQuery = firebaseFirestore.collection("Posts").orderBy("timestamp", Query.Direction.DESCENDING).limit(3);firstQuery.addSnapshotListener(getActivity(), new EventListener() {@覆盖public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {如果(isFirstPageFirstLoad){lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1);}for (DocumentChange doc : documentSnapshots.getDocumentChanges()){if (doc.getType() == DocumentChange.Type.ADDED) {字符串 blogPostId = doc.getDocument().getId();BlogPost blogPost = doc.getDocument().toObject(BlogPost.class).withId(blogPostId);如果(isFirstPageFirstLoad){blog_list.add(blogPost);}别的 {blog_list.add(0,blogPost);}blogRecyclerAdapter.notifyDataSetChanged();;}}isFirstPageFirstLoad = false;}});}//膨胀这个片段的布局返回视图;}public void loadMorePost(){查询 nextQuery = firebaseFirestore.collection("Posts").orderBy("时间戳", Query.Direction.DESCENDING).startAfter(lastVisible).limit(3);nextQuery.addSnapshotListener(getActivity(), new EventListener() {@覆盖public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {如果 (!documentSnapshots.isEmpty()){lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1);for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {if (doc.getType() == DocumentChange.Type.ADDED) {字符串 blogPostId = doc.getDocument().getId();BlogPost blogPost = doc.getDocument().toObject(BlogPost.class).withId(blogPostId);blog_list.add(blogPost);blogRecyclerAdapter.notifyDataSetChanged();}}}}});}}
提前致谢.
试试这个
<块引用>您可以在 BlogRecyclerAdapter
Context
public BlogRecyclerAdapter(List < BlogPost > blog_list, Context context) {this.blog_list = blog_list;this.context = 上下文;}
<块引用>
这样使用
firebaseFirestore = FirebaseFirestore.getInstance(context);firebaseAuth = FirebaseAuth.getInstance(context);Glide.with(context).applyDefaultRequestOptions(placeholderOption).load(image).into(blogUserImage);
<块引用>
像这样调用您的BlogRecyclerAdapter
BlogRecyclerAdapter adapter= new BlogRecyclerAdapter( blog_list, YourActivity.this );
I am using Firebase to populate my BlogRecycleadapter with blog post and get Likes from Like Buttons but when device is offline and user press Like Button , then app crashes...So I'm trying to implement second condition of isNetworkavailaible too in if statement ..as below
if (!task.getResult().exists() && isNetworkStatusAvialable(getApplicationContext())){
Map<String, Object> likesMap = new HashMap<>();
likesMap.put("timestamp", FieldValue.serverTimestamp());
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).set(likesMap);
} else {
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).delete();
}
But I'm gettning errror in getApplicationContext()
, from few google search , I found that getApplicationContext()
is not availaibe for Class but only for activity.
So how can I implement getApplicationContext here??
My whole code of Recycle adapter is
package com.nepalpolice.cdp;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.hdodenhof.circleimageview.CircleImageView;
public class BlogRecyclerAdapter extends RecyclerView.Adapter<BlogRecyclerAdapter.ViewHolder> {
public List<BlogPost> blog_list;
public Context context;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth firebaseAuth;
public BlogRecyclerAdapter(List<BlogPost> blog_list,Context context){
this.blog_list = blog_list;
this.context=context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blog_list_item, parent, false);
context = parent.getContext();
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseAuth = FirebaseAuth.getInstance();
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.setIsRecyclable(false);
final String blogPostId = blog_list.get(position).BlogPostId;
final String currentUserId = firebaseAuth.getCurrentUser().getUid();
String desc_data = blog_list.get(position).getDesc();
holder.setDescText(desc_data);
String image_url = blog_list.get(position).getImage_url();
holder.setBlogImage(image_url);
String user_id = blog_list.get(position).getUser_id();
//User Data will be retrieved here...
firebaseFirestore.collection("Users").document(user_id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
String userName = task.getResult().getString("name");
String userImage = task.getResult().getString("image");
holder.setUserData(userName, userImage);
} else {
//Firebase Exception
}
}
});
long millisecond = blog_list.get(position).getTimestamp().getTime();
String dateString = DateFormat.format("MM/dd/yyyy", new Date(millisecond)).toString();
holder.setTime(dateString);
//Get Likes Count
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").addSnapshotListener(((Main2Activity) context),new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (!documentSnapshots.isEmpty()){
int count = documentSnapshots.size();
holder.updateLikesCount(count);
}else{
holder.updateLikesCount(0);
}
}
});
//Get Likes
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).addSnapshotListener(((Main2Activity) context),new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
if (documentSnapshot.exists()){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.blogLikeBtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_accent));
}
else {
holder.blogLikeBtn.setImageDrawable(context.getResources().getDrawable(R.mipmap.action_like_accent));
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.blogLikeBtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_gray));
}else{
holder.blogLikeBtn.setImageDrawable(context.getResources().getDrawable(R.mipmap.action_like_gray));
}
}
}
});
//like Feature
holder.blogLikeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (!task.getResult().exists() && isNetworkStatusAvialable(getApplicationContext())){
Map<String, Object> likesMap = new HashMap<>();
likesMap.put("timestamp", FieldValue.serverTimestamp());
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).set(likesMap);
} else {
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).delete();
}
}
});
}
});
}
@Override
public int getItemCount() {
return blog_list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private View mView;
private TextView descView;
private ImageView blogImageView;
private TextView blogDate;
private TextView blogUserName;
private CircleImageView blogUserImage;
private ImageView blogLikeBtn;
private TextView blogLikeCount;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDescText(String descText){
descView = mView.findViewById(R.id.blog_desc);
descView.setText(descText);
blogLikeBtn = mView.findViewById(R.id.blog_like_btn);
}
public void setBlogImage(String downloadUri){
blogImageView = mView.findViewById(R.id.blog_image);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.image_placeholder);
Glide.with(context).applyDefaultRequestOptions(requestOptions).load(downloadUri).into(blogImageView);
}
public void setTime(String date) {
blogDate = mView.findViewById(R.id.blog_date);
blogDate.setText(date);
}
public void setUserData(String name, String image){
blogUserImage = mView.findViewById(R.id.blog_user_image);
blogUserName = mView.findViewById(R.id.blog_user_name);
blogUserName.setText(name);
RequestOptions placeholderOption = new RequestOptions();
placeholderOption.placeholder(R.drawable.profile_placeholder);
Glide.with(context).applyDefaultRequestOptions(placeholderOption).load(image).into(blogUserImage);
}
public void updateLikesCount (int count){
blogLikeCount = mView.findViewById(R.id.blog_like_count);
blogLikeCount.setText(count + "Likes");
}
}
public static boolean isNetworkStatusAvialable (Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}
}
and my HOmeFragment from where I'm calling adapter class is
package com.nepalpolice.cdp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentChange;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class HomeFragment extends Fragment {
private RecyclerView blog_list_view;
private List<BlogPost> blog_list;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth firebaseAuth;
private BlogRecyclerAdapter blogRecyclerAdapter;
private DocumentSnapshot lastVisible;
private Boolean isFirstPageFirstLoad = true;
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
blog_list = new ArrayList<>();
blog_list_view = view.findViewById(R.id.blog_list_view);
firebaseAuth = FirebaseAuth.getInstance();
blogRecyclerAdapter = new BlogRecyclerAdapter(blog_list);
blog_list_view.setLayoutManager(new LinearLayoutManager(container.getContext()));
blog_list_view.setAdapter(blogRecyclerAdapter);
if(firebaseAuth.getCurrentUser() != null) {
firebaseFirestore = FirebaseFirestore.getInstance();
blog_list_view.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
Boolean reachedBottom = !recyclerView.canScrollVertically(1);
if(reachedBottom){
String desc = lastVisible.getString("desc");
Toast.makeText(container.getContext(), "Reached : " + desc, Toast.LENGTH_SHORT).show();
loadMorePost();
}
}
});
Query firstQuery = firebaseFirestore.collection("Posts").orderBy("timestamp", Query.Direction.DESCENDING).limit(3);
firstQuery.addSnapshotListener(getActivity(), new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (isFirstPageFirstLoad){
lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1);
}
for (DocumentChange doc : documentSnapshots.getDocumentChanges()){
if (doc.getType() == DocumentChange.Type.ADDED) {
String blogPostId = doc.getDocument().getId();
BlogPost blogPost = doc.getDocument().toObject(BlogPost.class).withId(blogPostId);
if (isFirstPageFirstLoad){
blog_list.add(blogPost);
}else {
blog_list.add(0,blogPost);
}
blogRecyclerAdapter.notifyDataSetChanged();;
}
}
isFirstPageFirstLoad = false;
}
});
}
// Inflate the layout for this fragment
return view;
}
public void loadMorePost(){
Query nextQuery = firebaseFirestore.collection("Posts")
.orderBy("timestamp", Query.Direction.DESCENDING)
.startAfter(lastVisible)
.limit(3);
nextQuery.addSnapshotListener(getActivity(), new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (!documentSnapshots.isEmpty()){
lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1);
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
String blogPostId = doc.getDocument().getId();
BlogPost blogPost = doc.getDocument().toObject(BlogPost.class).withId(blogPostId);
blog_list.add(blogPost);
blogRecyclerAdapter.notifyDataSetChanged();
}
}
}
}
});
}
}
Thanks in advance.
Try this
You can pass
Context
in your Constructor of yourBlogRecyclerAdapter
public BlogRecyclerAdapter(List < BlogPost > blog_list, Context context) {
this.blog_list = blog_list;
this.context = context;
}
use like this
firebaseFirestore = FirebaseFirestore.getInstance(context);
firebaseAuth = FirebaseAuth.getInstance(context);
Glide.with(context).applyDefaultRequestOptions(placeholderOption).load(image).into(blogUserImage);
call your
BlogRecyclerAdapter
like this
BlogRecyclerAdapter adapter= new BlogRecyclerAdapter( blog_list, YourActivity.this );
这篇关于如何在适配器类中使用 get getApplicationContext()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!