How to use get getApplicationContext() in Adapter Class

后端 未结 3 1334
长情又很酷
长情又很酷 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 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();
    }
    

提交回复
热议问题