Eljas
Eljas

Reputation: 1207

How to call new layout when there is no network connection?

Ok here is my problem:

I'm going to start new activity when there isn't internet connection, but new activity screen is black. New activity should show ImageView...

CHECK CONNECTIVITY AND START NEW ACTIVITY:

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
    if (!info.isConnected()) {
    }
}
else {
    startActivity(new Intent(main.this, no_connection.class));
}

NO_CONNECTION ACTIVITY:

    package com.hello.hello;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;

public class no_connection extends Activity {


        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.connection_error);
            ImageView image = (ImageView) findViewById(R.id.image_verkkovirhe);

      }
}

AND HERE IS CONNECTION_ERROR LAYOUT:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" 
  android:id="@+id/connection_error" 
  android:fitsSystemWindows="true" android:orientation="vertical">



        <ImageView 
        android:src="@drawable/verkkovirhe" 
        android:layout_width="fill_parent" 
        android:id="@+id/image_verkkovirhe" 
        android:layout_height="fill_parent" 
        android:clickable="false" 
        android:fitsSystemWindows="true" 
        android:visibility="visible"></ImageView>


    </RelativeLayout>

OR

Maybe I can only change layout when there isn't network connection? When I try this I get force close?

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (info != null) {
        if (!info.isConnected()) {
        }
    }
    else {
        setContentView(R.layout.connection_error );
    }

Upvotes: 1

Views: 1584

Answers (1)

user874649
user874649

Reputation:

If you are starting a new activity from a service you should use the FLAG_ACTIVITY_NEW_TASK flag. It should look like this:

Intent intent = new Intent(main.this, no_connection.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

Upvotes: 1

Related Questions