I have an activity which does a fragment transaction
DetailFragment newFragment = new DetailFragment();
transaction.replace(R.id.mylist, newFragment);
transaction.addToBackStack(null);
transaction.commit();
that works fine. Now I know within my activity a dynamic string I need to replace in the layout I have in newFragment. I thought that I can call after transaction.commit() just something like
newFragment.setMyString("my dynamic value");
And in the newFragment.java I have
public void setMyString(String s)
{
TextView tv = (TextView) getActivity().findViewById(R.id.myobject);
tv.setText(s);
}
The point is that getActivity() returns null. How can I get the context I need to find my layout elements?
Edit:
I try to follow the route using a bundle as this seems to be the cleanest way. So I have changed my code:
Bundle b = new Bundle();
b.putString("text", "my dynamic Text");
DetailFragment newFragment = new DetailFragment();
transaction.replace(R.id.mylist, newFragment);
transaction.addToBackStack(null);
transaction.commit();
My fragment onCreateView looks like this:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.mylayout, container, false);
TextView t = (TextView) v.findViewById(R.id.texttobereplaced);
t.setText(savedInstanceState.getString("text");
}
It seems that savedInstranceState is empty. Where should I find my bundle?
Edit2:
missed the getArguments() in the reply. is working now.
Make sure you call
getActivity()
in or afteronAttach()
, as before then it will returnnull
.Your
Fragment
hasn't attached to theActivity
yet, which also means your layout hasn't been inflated yet (See the Fragment lifecycle). The best solution here would be to add yourString
value as an argument to theFragment
via theFragment.setArguments(Bundle)
method. This can be retrieved in the receivingFragment
via theFragment.getArguments()
method.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 :
I know it does'nt make really much sense but that is how i am running my code and it works fine :)
if u need to call getActivity in OnCreateView, move all ur code from onCreateView to onActivityCreate and only left lines
in onCreateView
but i have a funny situation.
in My onActivityCreated
Sometime the onActivityCreated wont run (correctly!?) and hence the spinner s1 become empty.