There is a fragment:

public class CurrentFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_current, null); return view; } public void GetCurrInfo(String url){ final WebView current_web = (WebView) view.findViewById(R.id.current_web); } } 

But when I want to connect the WebView in the GetCurrInfo method, the view is red. I know why it does not work, but I do not know how to do it right.

enter image description here

  • one
    Make getView() with try/catch NPE, or view class variable - Jarvis_J
  • getView() works. Do I have to use NPE processing? - Roman Shubenko pm
  • one
    no, not at all obligatory, but theoretically situations may arise when the function is called and the fragment has not yet been loaded. A try/catch will help in such rare cases not to fly the entire program. - Jarvis_J

1 answer 1

The variable View view declared in the onCreateView method and, therefore, is a local variable of this method. Those. it is visible / available only in this method. In other methods, it is not visible, what the compiler tells you.

In this case, you can either use the getView() fragment method or, better, declare WebView currentWeb a class field, initialize it in the onCreateView method and use this variable in the method:

 public class CurrentFragment extends Fragment { private WebView currentWeb; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_current, null); currentWeb = (WebView) view.findViewById(R.id.current_web); return view; } public void getCurrInfo(String url){ currentWeb.loadUrl(url); } }