Open Activity if you don’t have internet

Asked

Viewed 716 times

0

I have two Activity one has a webview and another is a page where if there is no internet should be displayed it.

The problem is, when there is no connection, there is an error and it says that the application has stopped instead of opening Activity "error_webview".

Someone knows how to fix this?

  package brasil500.brasil500;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends Activity {
//Faz a verificacao da conexao com a internet
//Fim da Verifica��o de conexao com a internet

    private static final String TAG = "MainActivity";

    private WebView wv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        // If a notification message is tapped, any data accompanying the notification
        // message is available in the intent extras. In this sample the launcher
        // intent is fired when the notification is tapped, so any accompanying data would
        // be handled here. If you want a different intent fired, set the click_action
        // field of the notification message to the desired intent. The launcher intent
        // is used when no click_action is specified.
        //
        // Handle possible data accompanying notification message.
        // [START handle_data_extras]
        if (getIntent().getExtras() != null) {
            for (String key : getIntent().getExtras().keySet()) {
                Object value = getIntent().getExtras().get(key);
                Log.d(TAG, "Key: " + key + " Value: " + value);
            }
        }
        // [END handle_data_extras]
















        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wv = (WebView) findViewById(R.id.webView);
        wv.setWebViewClient(new WebViewClient());
        final WebSettings ws= wv.getSettings();
        ws.setJavaScriptEnabled(true);
        ws.setSupportZoom(false);
        //news implementation
        ws.setSaveFormData(true);
        wv.loadUrl("https://terra.com.br"); 
        wv.getSettings().setUseWideViewPort(true);
        wv.getSettings().setLoadWithOverviewMode(true);
        wv.setWebChromeClient(new WebChromeClient());


        //Barra de Progress StackOverflow
       /* ProgressDialog progress = new ProgressDialog();
        progress.setMessage("Carregando");
        progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progress.setIndeterminate(true);
        progress.show();*/


        //Barra de Progresso / Carregando
       final ProgressBar Pbar;
        Pbar = (ProgressBar) findViewById(R.id.progressBar);


        wv.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                if (progress < 100 && Pbar.getVisibility() == ProgressBar.GONE) {
                    Pbar.setVisibility(ProgressBar.VISIBLE);
                }
                Pbar.setProgress(progress);
                if (progress == 100) {
                    Pbar.setVisibility(ProgressBar.GONE);

                }
            }
        });
        //Fim da Barra de Progresso / Carregando

        //Verifica se a internet está ativa no aparelho
       /* ConnectivityManager cManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
        NetworkInfo ninfo = cManager.getActiveNetworkInfo();
        if(ninfo!=null && ninfo.isConnected()){
            Toast.makeText(this,"Conectado na internet", Toast.LENGTH_LONG).show();
        }else{
                //Caso não tenha internet, Recarrega a SplashScreen
                    Intent i = new Intent(MainActivity.this, splash_screen.class);
                    startActivity(i);
               //Caso não tenha internet, Recarrega a SplashScreen

            Toast.makeText(this,"Sua Internet Precisa estar Ativa. Estamos Tentando conectar...", Toast.LENGTH_LONG).show();
        }
*/

        /* Caso a pagina da web não funciona*/
        wv.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Intent i = new Intent(MainActivity.this, error_webview.class);
                startActivity(i);

            }
        });
         /* Fim:: Caso a pagina da web não funciona*/


        }

//Fecha a Aplicacao Quando pressionar o botao voltar
@Override
public void onBackPressed(){

    if (wv.canGoBack()) {
        wv.goBack();
    } else {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}
   //Fecha a Aplicacao Quando pressionar o botao voltar

//Volta o Webview quando clicar em volta


//Volta o Webview quando clicar em volta

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

1 answer

0


First you need to check if there is connection using the method isOnline() (is only an alternative), this before you set your WebView. For example:

private WebView wv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    /* essa linha tem que estar fora da condição, senão dará erro 
    dentro do seu onCreate() */
    wv = (WebView) findViewById(R.id.webView);

    if (isOnline()) {
        wv.setWebViewClient(new WebViewClient());
        final WebSettings ws = wv.getSettings();
        ws.setJavaScriptEnabled(true);
        ws.setSupportZoom(false);
        ws.setSaveFormData(true);
        wv.loadUrl("https://terra.com.br");
        wv.getSettings().setUseWideViewPort(true);
        wv.getSettings().setLoadWithOverviewMode(true);
        wv.setWebChromeClient(new WebChromeClient());

    } else {
        /* deve cair aqui caso não haja internet */
        Intent i = new Intent(MainActivity.this, ActivitySemInternet.class);
        startActivity(i);
    }
}
/**
* Este método verifica se há conexão com internet
*/
public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

In the AndroidManifest.xml it is necessary to grant permission regarding the state of your network using the ACCESS_NETWORK_STATE. Behold:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  • Oh my brother you again rs, we are already becoming partners in stackoverflow rs, but for now I only get your help as I am Noob in the segment rs. So I didn’t have what goes inside of ` if(isOnline(here**)){ ´

  • I saw the link you told me, but would you put it inside the if or outside? &#xA;&#xA;public boolean isOnline() {&#xA; ConnectivityManager cm =&#xA; (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);&#xA; NetworkInfo netInfo = cm.getActiveNetworkInfo();&#xA; return netInfo != null && netInfo.isConnectedOrConnecting(); }

  • placed below **private Webview wv; ; private webview wv; private webview wv; public Boolean isOnline() {&#xA; ConnectivityManager cm =&#xA; (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);&#xA; NetworkInfo netInfo = cm.getActiveNetworkInfo();&#xA; return netInfo != null && netInfo.isConnectedOrConnecting(); } didn’t work out

  • @Felipeedwardsvanstocher vlw dude! In my profile here from Stackoverflow has my Linkedin. If you prefer, you can add me there!

  • @Felipeedwardsvanstocher we will delete these comments here, because otherwise the answer gets too much comment. ehuhe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.