tyczj
tyczj

Reputation: 73741

webview is always null

I have a WebViewFragment and when trying to get the webview to use, it gives me a null pointer

public class BallInfoFragment extends WebViewFragment {
long id;

public BallInfoFragment(long id){
    this.id = id;
}

@Override
public void onCreate(Bundle state){
    super.onCreate(state);
    String ball = new String();
    Cursor c = getActivity().getContentResolver().query(Balls.CONTENT_URI,new String[] {Balls.ID,Balls.BALL},Balls.ID+"="+id,null,null);
    c.moveToFirst();
    ball = c.getString(1);
    WebView wv = getWebView();  //getWebView always gives me null

why is it null?

Upvotes: 0

Views: 738

Answers (2)

Alex Lockwood
Alex Lockwood

Reputation: 83303

Jivings is correct, but to clarify most of the time you'll want to retrieve and attach your views in the onCreateView method, which is where inflation of the parent view hierarchy occurs. The default implementation of onCreateView in WebViewFragment attaches the WebView to the parent view for you, so you don't need to worry about it in this case (the same is true with similar classes such as ListFragment). I thought it was worth mentioning. If you simply want to retrieve your view from the Activity's view layout, you should do this in onActivityCreated, as at this is called only after the Activity's layout has been created. In the code above, you are retrieving the view before it has been attached, and getWebView is correctly returning null.

Make sure you understand the Fragment lifecycle, it's really important!

Upvotes: 2

Jivings
Jivings

Reputation: 23250

You have to put the code within the onActivityCreated() function instead. This is called after the WebView has been instantiated.

@Override
public void onActivityCreated(Bundle savedInstanceState) { 
  // your code here.
  WebView wv = getWebView();
}

onCreate is called when the activity is created, before the WebView has been.

Upvotes: 1

Related Questions