Issue
@JavascriptInterface
public void switchView() {
//sync the BottomBar Icons since a different Thread is running
Handler refresh = new Handler(Looper.getMainLooper());
refresh.post(new Runnable() {
public void run()
{
MapFragment mapFragment = new MapFragment();
FragmentManager fragmentManager = ((MainActivity) mContext).getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content, mapFragment);
transaction.commit();
}
});
}
When i run this code everything is fine, but when i add the line
mapFragment.setUrl("www.examplestuff.com");
the app crashes with Attempt to invoke virtual method 'void android.webkit.WebView.loadUrl(java.lang.String)' on a null object reference
My Fragment class looks like this
public WebView mapView;
private String thisURL;
public void setUrl(String url) {
thisURL = url;
mapView.loadUrl(thisURL);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map,container, false);
mapView = (WebView)view.findViewById(R.id.mapView);
this.setUrl("file:///android_asset/www/MapView.html");
mapView.setWebViewClient(new WebViewClient());
WebSettings webSettings = mapView.getSettings();
webSettings.setJavaScriptEnabled(true);
//allow cross origin - like jsonP
webSettings.setAllowUniversalAccessFromFileURLs(true);
return view;
}
Also call there the method this.setURL() and works fine.
What I am doing wrong? Has the FragmentManager no access of the instance WebView of the fragment???
Solution
This be because when you call setUrl it invokes this method:
public void setUrl(String url) {
thisURL = url;
mapView.loadUrl(thisURL);
}
the line mapView.loadUrl(thisURL); accesses the mapView. However you are likely calling setUrl before the Android system has called onCreateView, therefore mapView is null, causing said crash.
public void setUrl(String url) {
thisURL = url;
if(mapView != null) {
mapView.loadUrl(thisURL);
}
}
and
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map,container, false);
mapView = (WebView)view.findViewById(R.id.mapView);
if(thisUrl != null) {
mapView.loadUrl(thisURL);
}
... other code
Then mapFragment.setUrl("www.examplestuff.com"); would work
A better solution would be to understand more the Activity & Fragment lifecycles and not call setUrl when the Fragment is in an invalid state :-) You are probably calling setUrl when really you should be passing the Url as an intent extra when the fragment is created. https://developer.android.com/training/basics/fragments/communicating.html
Answered By - Blundell
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.