0

I have an activity that loaded a string array directly into it

private String[] questions = {"Q1", "Q2", "Q3"};
private String[] answers= {"A1", "A2", "A3"};

I wanted to change it to load from a resource file

Resource File named Questions

<string-array name="questions">
    <item>Q1</item>
    <item>Q2</item>
    <item>Q3</item>
</string-array>

<string-array name="answers">
    <item>A1</item>
    <item>A2</item>
    <item>A3</item>
</string-array>

Changed the string array to

private String[] questions = getResources().getStringArray(R.array.questions);
private String[] answers= getResources().getStringArray(R.array.answers);

When I changed it to pull the string array from my resource file it gives me

java.lang.IllegalStateException: My_Fragment{38ad4cd} not attached to Activity
th3ramr0d
  • 484
  • 1
  • 7
  • 23

1 Answers1

1

What's going on?

What your actual code does is that it tries to access the resources when the Fragment is instantiated, which is wrong because the resources won't be available unless your Fragment is attached to some Activity.

Plus

The call getResources() is just a shortcut to getActivity().getResources(). My guess is that its implementation looks like this:

if(isAttached()) {
    return getActivity().getResources();
} else {
    throw new RuntimeException("Fragment is not attached...");
}

Solution

Move this initialization:

private String[] questions = getResources().getStringArray(R.array.questions);
private String[] answers = getResources().getStringArray(R.array.answers);

To your onCreateView method:

private String[] questions;
private String[] answers;

public void onCreateView(...){
    // ...
    questions = getResources().getStringArray(R.array.questions);
    answers = getResources().getStringArray(R.array.answers);
    // ...
}

Note

You're safe to move this initialization anywhere in between onAttach and onDetach callbacks. Check the fragment life-cycle to get a clear idea.

Similar question but with an activity

App crashing when fetching from string ressources.