How to load second URL if first one fails to load? – Android Studio WebView

Issue

So here is some context. I made IP camera for my backyard, using MotionEyeOS, that I can connect to using cameras local IP address when I’m on my local network, I also set up DDNS for it so I can connect to it anywhere from the internet. The problem is when I try to connect with my DDNS link when I am on my local network – it doesn’t work. So I want to make an app that would automatically connect me to camera regardless of whether I’m on my local network or not.

I’ve been searching internet for couple of hours and didn’t find anything that could be helpful.

So my question is how do I do it? Note I’m not looking for someone to write code for me, I’m just asking for guidance in right direction, I will figure out the rest myself.

Thanks in advance!

Solution

I figured it out myself.

I used function onReceivedError to see if the page failed to load, if so I would just load the second link. I used this stackoverflow question for reference.

Here is the code that works:

package com-example.myapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

String url1  "http://192.168.1.1";
String url2  "http://192.168.1.2";

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

    final WebView myWebView  (WebView) findViewById(R.id.webView);


    myWebView.setWebViewClient(new WebViewClient() {


        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
        {
            Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();


                myWebView.loadUrl(url2);


        }


    });

    myWebView.loadUrl(url1);


    }


}

Answered By – M.E. Team

Leave a Comment