How to use get getApplicationContext() in Adapter Class

后端 未结 3 1330
长情又很酷
长情又很酷 2020-12-07 06:16

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

相关标签:
3条回答
  • 2020-12-07 06:57

    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();
    }
    
    0 讨论(0)
  • 2020-12-07 07:02

    Try this

    You can pass Context in your Constructor of your BlogRecyclerAdapter

    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 );
    
    0 讨论(0)
  • 2020-12-07 07:05

    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.

    0 讨论(0)
提交回复
热议问题