3

I am really wondering. I have a Context:

Context context= getActivity();

when I use context in a Fragment for UI things like webview app gives me NullPointerException (Forceclose) but when I use getActivity() that works well. what is difference!? Let me explain usage. I have a activities named "A" and "B". activity "B" inherit NavigationDrawer and Actionbar from activity "B". SO there is:

public class B extends A

We know in NavigationDrawer there is a main content. activity "B" uses a Fragment to feed main content and I uses Context in that fragment. I am really wondering again! sorry for bad English.

Edit: here is my code:

public class PlaceholderFragment extends Fragment {

public Context context = getActivity();
private static final String ARG_SECTION_NUMBER = "section_number";

public PlaceholderFragment() {
}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_text, container, false);
        String text = "<html><head><link href=\"file:///android_asset/style_css.css\" rel=\"stylesheet\" type=\"text/css\"></head> <body class=\"body\"> title1 <hr> <div align=\"center\"> <img src= "+imagePath1_1+" width= \"95% \" /></div>les1</body></html>";

        WebView webView= new WebView(context);
        webView.loadDataWithBaseURL(null,text, "text/html", "UTF-8", null);
        return rootView;
    }
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((enhanced) activity).onSectionAttached(
                getArguments().getInt(ARG_SECTION_NUMBER));
    }
}

if I use getActivity(); directly this code works. What I tried: changed context to public and final and used a simple TextView instead of WebView.

David
  • 2,129
  • 25
  • 34

1 Answers1

5

Let me guess ...you got NullPointerException? Because it seems like your context value is always null since you declare it like this:

public Context context = getActivity();

The reason is this line of code run when Fragment is created and that time it doesn't attach to any Activity yet so getActivity() always return null. If you do want to make your code work. Please place context = getActivity() somewhere else in Fragment's lifecycle.

Garg
  • 2,731
  • 2
  • 36
  • 47
nuuneoi
  • 1,788
  • 1
  • 17
  • 14
  • 1
    Yup, from the Android dev guide: "Caution: If you need a Context object within your Fragment, you can call getActivity(). However, be careful to call getActivity() only when the fragment is attached to an activity. When the fragment is not yet attached, or was detached during the end of its lifecycle, getActivity() will return null." – adao7000 Jun 27 '15 at 21:30