NegeroKiddero
NegeroKiddero

Reputation: 41

How do I add WebView to one of the fragments

I'm trying to add WebView to my android app. To do so, I'm following this tutorial - https://www.youtube.com/watch?v=TUXui5ItBkM

If I put Webview in activity_main, the website is displayed, although this is not what I want.

I have 3 fragments, Livestream, NewsArticles and Settings. When I add WebView to the NewsArticles fragment like so:

<WebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

the app crashes. I'm not sure what the problem is. I don't seem to find any bugs/errors popup in android studio as well. This is the MainActivity's code:

webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://www.alt-info.com");

I've internet traffic permission enabled as well.

Upvotes: 0

Views: 471

Answers (1)

SatvikVejendla
SatvikVejendla

Reputation: 459

If you're using a fragment, then you have to specify this:

Replace this following code

@Override public View onCreateView(@NonNull LayoutInflater inflater,@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
    return inflater.inflate(R.layout.fragment_articles, container, false);
}

with this:

@Override public View onCreateView(@NonNull LayoutInflater inflater,@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.fragment_articles, container, false);
    webView = (WebView) view.findViewById(R.id.webview);
}

When you use fragments, you have to say "view.findViewById()". You have the add "view" in front of "findViewById" EVERY TIME you initialize an object.

Also, if the app crashes, there definitely is an error that should pop up in Android Studio. Click on "Logcat" once you run it and check for any red text.

Upvotes: 2

Related Questions