Android load data on fragment on network connection

Viewed 114

Hi I am new to android development and trying to implment a tabbed activity with individual fragment for each tab. My layout looks as below

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_gravity="bottom"
        app:itemIconTint="@color/bottom_navigation"
        app:itemTextAppearanceInactive="@style/Widget.AppTheme.Button.TextButton.Small"
        app:itemTextColor="@color/bottom_navigation"
        app:labelVisibilityMode="labeled"
        app:menu="@menu/drawer_menu" />

</RelativeLayout>

and the activity

class MainFeedActivity : AppCompatActivity, BottomNavigationView.OnNavigationItemSelectedListener,
        BottomNavigationView.OnNavigationItemReselectedListener{
  override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        navigationBottomView.setOnNavigationItemSelectedListener(::onNavigationItemSelected)
        navigationBottomView.setOnNavigationItemReselectedListener(::onNavigationItemReselected)
        //set navigationBottomView to right depending of the item selected
  }
  
}

The problem is when internet connection is not available the fragment get loads but once the internet connection comes on navigating to that fragment the data does not get loaded, what changes shall I make to enusre that data gets loaded on network reconnection?

1 Answers

if you have network connection on/off listener then you have to pass state of internet to every fragment in your bottom navigation. Create an interface and extend an interface to fragments in bottom navigation

interface NetState{
    fun onStateChanged(isAvailable: Boolean)
}

Then based on network state change pass it to fragments

    supportFragmentManager.fragments.forEach { 
        if (it is NetState)
            it.onStateChanged(true)
    }
Related