Skip to content
Advertisement

showing refresh page button when there is no internet connection

I have an activity that requires an internet connection, and I put a progress bar for loading pages, but when there is no internet connection from the user the progress bar is always VISIBLE, like the code below

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BlogModel blogModel = new ViewModelProvider(this).get(BlogModel.class);
        blogModel.getBlogList().observe(this,getBlog);
        blogModel.setBlog("extra_blog");


        showLoad(true);
}

private Observer<ArrayList<BlogItem>> getBlog = new Observer<ArrayList<BlogItem>>() {
    @Override
    public void onChanged(ArrayList<BlogItem> blogItems) {
        if (blogItems != null){
            adapter.setData(blogItems);
        }
        showLoad(false);
    }
};

private void showLoad(Boolean state){
    if (state){
        progressBar.setVisibility(View.VISIBLE);
    }
    else {
        progressBar.setVisibility(View.GONE);
    }
}

and what I want is, when there is no internet connection, the progress bar has the status of GONE and immediately showing the button, and this button will function to refresh the activity, is there any solution related to this matter?

Advertisement

Answer

You have to check if you are connected to the internet like this:

boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED || 
        connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
    //we are connected to a network
    connected = true;
}
else
    // not connected
    connected = false;

Just set Progresssbar Gone when you are not connected. You will need this permission in your manifest:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement