Issue
I'm having problems with a webview inside a fragment. I'm getting a error message saying "java.lang.nullpointerexception" at this line: myWebView.setWebViewClient(new WebViewClient());. I have googled and googled but not found a solution. Any ideas as to what I'm missing?
FragmentB.java
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* A simple {@link Fragment} subclass.
*
*/
@SuppressLint("SetJavaScriptEnabled")
public class FragmentB extends Fragment {
public FragmentB() {
// Required empty public constructor
}
private View mContentView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mContentView = inflater.inflate(R.layout.fragment_b, container, false);
WebView myWebView = (WebView)mContentView. findViewById(R.id.webView);
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.nellienova.com");
return mContentView;
}
}
webview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Solution
Make sure you are loading the right xml file. I have done this before by mistakenly loading another layout file. You have webview.xml typed above that file but you inflating R.layout.fragment_b
Edit
Each fragment has its own layout file. You can reuse layouts and add multiple layouts to one xml file but through code your fragment will only inflate the file you refer to.
If you want to include other files you have to use include statements to pull those other files in to your xml before you can interact with objects in the other xml files. Click here for more details about include statements. Example below
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:background="@color/app_bg"
android:gravity="center_horizontal">
<include layout="@layout/titlebar"/>
<TextView android:layout_width=”match_parent”
android:layout_height="wrap_content"
android:text="@string/hello"
android:padding="10dp" />
</LinearLayout>
Click here for some good information about fragments. Spend a little time with it and it will save you lots of time troubleshooting problems.
Answered By - dsum27
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.