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:
I had this issue in my android activity.The mistake was my Toast was not getting the context or I would prefer to call it reference of the activity.
Previous code:-
Toast.makeText(context, "Session Expire..!", Toast.LENGTH_SHORT).show();
Corrected Code:-
Toast.makeText(activityname.this, "Session Expire..!", Toast.LENGTH_SHORT).show();
You can't do MainActivity parent=(MainActivity) getActivity();
before onAttach()
and after onDetach()
.
Since, you are doing at the time of fragment instantiation. The method getActivity
will always return null. Also as far as possible don't try to keep your Activity
reference in your Fragment
. This could cause memory leak if the reference is not nullified properly.
Use getActivity()
or getContext()
wherever possible.
Change your Toast
as below:
Toast.makeText(getContext(), "Please check the number you entered",
Toast.LENGTH_LONG).show();
or
Toast.makeText(getActivity(), "Please check the number you entered",
Toast.LENGTH_LONG).show();
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);
...
}