问题描述
我正在使用Firebase通过博客文章填充我的BlogRecycleadapter并从Like Buttons获取Likes但是当设备离线并且用户按下Like按钮时,应用程序崩溃...所以我正在尝试实现isNetworkavailaible的第二个条件如果声明..以下
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();
}
但是我在 getApplicationContext(),从少数谷歌搜索,我发现 getApplicationContext()
不适用于Class,但仅适用于活动。
But I'm gettning errror in getApplicationContext()
, from few google search , I found that getApplicationContext()
is not availaibe for Class but only for activity.
那么如何在这里实现getApplicationContext?
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();
}
}
和我正在调用适配器类的HOmeFragment是
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();
}
}
}
}
});
}
}
提前致谢。
推荐答案
试试这个
public BlogRecyclerAdapter(List < BlogPost > blog_list, Context context) {
this.blog_list = blog_list;
this.context = context;
}
firebaseFirestore = FirebaseFirestore.getInstance(context);
firebaseAuth = FirebaseAuth.getInstance(context);
Glide.with(context).applyDefaultRequestOptions(placeholderOption).load(image).into(blogUserImage);
BlogRecyclerAdapter adapter= new BlogRecyclerAdapter( blog_list, YourActivity.this );
这篇关于如何在Adapter Class中使用get getApplicationContext()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!