Search code examples
androidurlwebviewandroid-activity

Unable to load url in webview


I'm trying to load a URL in a webview but I keep getting an error. (see below)

this is the code that should load the URL at startup:

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

    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }

    WebView mywebview1;

       mywebview1 = (WebView)findViewById(R.id.myownwebview);
       mywebview1.loadUrl("http://www.mad-sharky.com");
}

I have a webview in my XML file with id "myownwebview". Whenever i start the projecti get the error message shown in the picture:

enter image description here

I searched a lot and most of the answers I found tell that the URL is written to the view before it is created and therefore it throws an exception. It is supposed to be after "seContentView". But in my case it is after setContentView so I can't find what is causing it.

Debug screen image:

enter image description here


Solution

  • probably the fragment transaction is causing the exception, so comment this code:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
       /* if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }*/
    
    
        WebView mywebview1;
    
           mywebview1 = (WebView)findViewById(R.id.myownwebview);
           mywebview1.loadUrl("http://www.mad-sharky.com");
    
    
    }
    

    or load the url into the WebView from the PlaceholderFragment