Search code examples
androidandroid-webviewandroid-viewmodel

Url not loading in Webview using ViewModel


I am trying to load multiple URLs from drawer menu onDestinationChanged using ViewModel. In my WebViewModel class, below is the setUrl and getUrl methods.

public class WebViewModel extends ViewModel {
    private String TAG = this.getClass().getSimpleName();
    private final MutableLiveData < String > url = new MutableLiveData < > ();

    public void setUrl(String newUrl) {
        Log.i(TAG, "SET URL: " + newUrl);
        url.setValue(newUrl);
    }

    public LiveData < String > getUrl() {
        if ((url == null)) {
            setUrl("https://example.com");
        }
        return url;
    }
}

and in MainActivity Class

private WebViewModel webViewModel;

I am trying to pass url adddress like this

 @Override
 public void onDestinationChanged(@NonNull NavController controller,
     @NonNull NavDestination destination, @Nullable Bundle arguments) {
     webViewModel = ViewModelProviders.of(MainActivity.this).get(WebViewModel.class);
     if (destination.getId() == R.id.nav_gallery) {
         webViewModel = ViewModelProviders.of(MainActivity.this).get(WebViewModel.class);
         webViewModel.setUrl("https://stackoverflow.com/");
     } else if (destination.getId() == R.id.nav_slideshow) {} else {
         toolbar.setVisibility(View.VISIBLE);
     }
 }

in WebViewModel Class, If I set any URL address manually, this url loads in the the fragment WebView. but when I pass URL from MainActivity Class through navigation, WebView is not loading any URL.

Further in the WebView fragment I'm using below code

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    webViewModel = ViewModelProviders.of(this).get(WebViewModel.class);
    webViewModel.getUrl().observe(getViewLifecycleOwner(), new Observer < String > () {
        @Override
        public void onChanged(@Nullable String url) {
            webView.loadUrl(url);
        }

    });
}

Solution

  • You created view model 2 times from activity and fragment I think both objects are different, if you setValue in activity, it won't get affected in the fragment as view model is different. try maintain same object.