2017-04-15 38 views
0
@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(); 
     } 
    }); 
} 

當運行此代碼一切都很好,但是當我添加行的Android片段管理器空對象引用

mapFragment.setUrl("www.examplestuff.com"); 

應用程序崩潰與嘗試調用虛擬方法「無效android.webkit。 WebView.loadUrl(java.lang.String中)」對空對象引用

我的片段類看起來像這樣

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

你把片段靜態地放在你的xml中(你不能)?顯示xml你的片段在哪裏.. – miljon

+0

不,只是WebView是在片段的xml中 - 但片段本身並不是在任何佈局xml中靜態的。我需要的方法在我的呼叫點可見並可訪問。 –

回答

2

這是因爲當你調用setUrl它會調用這個方法:

public void setUrl(String url) { 
    thisURL = url; 
    mapView.loadUrl(thisURL); 
} 

mapView.loadUrl(thisURL);訪問mapView。但是,在Android系統調用onCreateView之前,您可能會調用setUrl,因此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");會工作


一個更好的解決辦法是瞭解更多的活動&片段的生命週期,而不是調用setUrlFragment處於無效狀態:-)當你真的應該通過U時,你可能會打電話setUrl rl作爲片段創建時的意圖附加。 https://developer.android.com/training/basics/fragments/communicating.html

+0

Thx Dude。工作正常。我期待生命週期:) –