Basically I am starting to port a purely Activities application to Fragments and I am stuck nearly at the first step.
In my current application I extend application to have access to global constant and variables used to customize the application.
public class MyApplication extends Application {
private final int nbreLivres = 50;
private final String[] nomsLivres = new String[nbreLivres];
private final int colorCount = 25;
private final int[] customColors = new int[colorCount];
private SparseIntArray hmColors = new SparseIntArray();
private int mCustomFontSize = 14;
private static MyApplication instance;
...
...
public int getColorCount() {
return colorCount;
}
public int getColorFromIndex(int index) {
return customColors[index];
}
...
...
...
}
Accessing this from activities I do something like
((MyApplication) this.getApplication()).getColorCount();
and if I need to access it with an instance I do
private MyApplication mApp = MyApplication.getMyApplication();
mApp.getColorCount();
Question :
When doing these in a Fragment, for example to set the values of a list (ListFragment) to list all the colors available in my app I do
((MyApplication) getActivity().getApplication()).getColorsList();
and I tried also
MyApplication.getMyApplication().getColorsList();
both just crash at that line with a "null pointer" exception.
What have I not understand or what am I doing wrong ?
EDIT
Sorry I forget to mention it is based on the master/detail example given in Eclipse, where I try to populate the master list with my own data.
Here it is (I did not copy/paste all the useless stuff).
public class LivreListFragment extends ListFragment {
...
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1, ((MyApplication) getActivity().getApplication()).getColorsList() ));
}
}
ANSWER
Finally I simply found that I had forgotten to define my application name in my manifest file !
Now my code works as is.
However according to the answer of @CharlieCollins, I must put it in the onActivityCreated and not in the onCreate (unsafe).
Thx for your help, learning that onActivityCreated thing was important.