I try to use a fragment to open a database, however, when I click the button to begin searching, the program unexpectedly terminates and it show the error like this:
Same error I went through! It run well in MainActivity but not in my Fragment class.
I solved this problem by doing the following 2 things:
1) In Fragment class, don't declare anything globally like we do in Activity class.
For example:
public class HomeFragment extends Fragment {
// DON'T WRITE THIS HERE LIKE YOU DO IN ACTIVITY
String myArray[] = getResources().getStringArray();
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
...
}
Instead, write anything inside
onCreateView()
method.
2) Use
getActivity()
method first and then
getResource() method
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//WRITE LIKE THIS
String myArray[] = getActivity().getResources().getStringArray(R.array.itemsList);
...
}