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
Create a Adapter constructor and at the time of sending list data send one another parameter context from main class.
this in Fragment
blogRecyclerAdapter = new BlogRecyclerAdapter(blog_list,getContext());
blog_list_view.setLayoutManager(new LinearLayoutManager(container.getContext()));
blog_list_view.setAdapter(blogRecyclerAdapter);
this is in adapter
public BlogRecyclerAdapter(List<BlogPost> blog_list,Context context){
this.blog_list = blog_list;
this.context=context;
}
Then you can use this context as getApplicationContext();
in adapter class
disable button at the time of no internet.
if(!isNetworkAvailable()){
like_btn.setClickable(false); }
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
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 );
Without sending parameter you can achecive the same thing when you are calling your network checking method use your method like below
isNetworkStatusAvialable( holder.blogLikeBtn.getContext())
Instead of passing getApplicationContext() method you can get the context from any view that you have.
By using above approach, I am passing context of the same button that was clicked. Hope that helps you as well.