Difference between using context and being active in a fragment?
I'm really curious. I have a context:
Context context= getActivity();
when i use context
in fragment for ui things like webview app give me NullPointerException (Forceclose) but when i use getActivity()
it works well. who cares!? Let me explain the usage. I have actions called "A" and "B". activity "B" inherits NavigationDrawer and Actionbar from activity "B". So there is:
public class B extends A
We know the NavigationDrawer has main content. activity "B" is using a fragment for the main content and I am using context in that fragment. I'm surprised 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 plain TextView
instead of WebView.
source to share
Let me guess ... do you have a NullPointerException? Because it seems like your value is context
always null since you are declaring it like this:
public Context context = getActivity();
The reason is that this line of code is triggered when the Fragment is created and while it is not attached to any activity, so getActivity () always returns null. If you want your code to work. Please post
context = getActivity()
somewhere else in the fragment's lifecycle.
source to share