@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();
}
});
}
当我运行此代码时,一切都很好,但是当我添加行
时mapFragment.setUrl("www.examplestuff.com");
应用程序崩溃尝试在空对象引用上调用虚拟方法'void android.webkit.WebView.loadUrl(java.lang.String)'
My Fragment类看起来像这样
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;
}
同样调用方法this.setURL()
并正常工作。
我做错了什么? FragmentManager是否无法访问片段???的实例WebView
答案 0 :(得分:2)
这是因为当你调用setUrl
时,它会调用这个方法:
public void setUrl(String url) {
thisURL = url;
mapView.loadUrl(thisURL);
}
第mapView.loadUrl(thisURL);
行访问mapView
。但是,您可能会在Android系统调用setUrl
之前调用onCreateView
,因此mapView
为空,从而导致崩溃。
public void setUrl(String url) {
thisURL = url;
if(mapView != null) {
mapView.loadUrl(thisURL);
}
}
和
@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
然后mapFragment.setUrl("www.examplestuff.com");
会起作用
更好的解决方案是了解更多活动&当setUrl
处于无效状态时,片段生命周期并且不调用Fragment
:-)当片段为时,您可能正在调用setUrl
,而实际上您应该将Url作为意图额外传递创建。 https://developer.android.com/training/basics/fragments/communicating.html