Skip to content Skip to sidebar Skip to footer

Android: Fragment Cannot Get Activity

I have an activity which does a fragment transaction DetailFragment newFragment = new DetailFragment(); transaction.replace(R.id.mylist, newFragment); transaction.addToBackStack(nu

Solution 1:

Make sure you call getActivity() in or after onAttach(), as before then it will return null.

Solution 2:

Your Fragment hasn't attached to the Activity yet, which also means your layout hasn't been inflated yet (See the Fragment lifecycle). The best solution here would be to add your String value as an argument to the Fragment via the Fragment.setArguments(Bundle) method. This can be retrieved in the receiving Fragment via the Fragment.getArguments() method.

Solution 3:

So i am also using the same fragment transaction manager and the only problem i can see with your code is that you define the TextView tv inside your onCreateView method of your newFragment class and then instantiate it as like this :

publicclassAboutFragmentextendsFragment {

    @Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Viewv= inflater.inflate(R.layout.newFragment, container, false);
        TextViewtv= (TextView) v.findViewById(R.id.textview);
        return v;
    }

    publicvoidsetMyString(String s) {
        tv.setText(s);
    }
}

I know it does'nt make really much sense but that is how i am running my code and it works fine :)

Solution 4:

if u need to call getActivity in OnCreateView, move all ur code from onCreateView to onActivityCreate and only left lines

Viewv= inflater.inflate(R.layout.xxxx, container, false);
    return v;

in onCreateView

but i have a funny situation.

in My onActivityCreated

Spinners1= (Spinner) getActivity().findViewById(R.id.bitlength);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
            getActivity(), R.array.bitlengths,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    s1.setAdapter(adapter);

Sometime the onActivityCreated wont run (correctly!?) and hence the spinner s1 become empty.

Post a Comment for "Android: Fragment Cannot Get Activity"