0

I want to display the RelativeLayout called "content" in an activity when there is internet connectivity and replace it with another layout called "noInternet" when there is no connectivity. The same logic should be implemented when the app is opened.

I followed this, this and this I created a network receiver like this:

public class ConnectionChangeReceiver extends BroadcastReceiver {
    static boolean connectivity;
    @Override
    public void onReceive(Context context, Intent intent )
    {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE );
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if ( activeNetworkInfo != null && activeNetworkInfo.isConnected() )
        {
            connectivity = true;
        }
        else {
            connectivity = false;
        }
    }

    public static boolean hasConnectivity(){
        return connectivity;
    }
}

In my manifest, I added this under application tag :

<receiver android:name="com.myPackage.ConnectionChangeReceiver"
    android:label="NetworkConnection">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
    </intent-filter>
</receiver>

and under the manifest tag:

<uses-permission android:name="android.permission.INTERNET" />

I have my activity layout like this:

<RelativeLayout....>
     ....
     <RelativeLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_centerInParent="true"
         android:id="@+id/noInternet"
         android:visibility="gone">
     <RelativeLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_centerInParent="true"
         android:id="@+id/content">
     ...
</RelativeLayout>

To switch the layouts I wrote this code in the onCreate() method of the activity :

if(ConnectionChangeReceiver.hasConnectivity()){
    noInternet.setVisibility(View.GONE);
    content.setVisibility(View.VISIBLE);
} else {
    content.setVisibility(View.GONE);
    noInternet.setVisibility(View.VISIBLE);
}

The problem is that the layouts are supposed to switch upon changing internet connectivity, but they do not. I tried invalidate()[see this] and handler [see this], but nothing seems to work.

Where did I go wrong?

Community
  • 1
  • 1
kds23
  • 296
  • 3
  • 17

1 Answers1

0

After struggling with it for almost a day, here's what fixed my problem:

I added the below code in my activity:

@Override
public void onBackPressed(){
    finish();
}
kds23
  • 296
  • 3
  • 17