Hello. Please help with fragments in android.
I have Activity which extends FragmentActivity to where I'm adding/replacing fragments dynamically. activity.xml and fragment.xml are the xml files. MyFragment class extends Fragment

public class MyFragment extends Fragment {
    TextView t;
    View view;
    public static Fragment newInstance(){
        MyFragment myFrag = new MyFragment();
        return myFrag;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment, container, false);

        return view;
    public void changeText(){
        t = (TextView) view.findViewById(R.id.randNum);

In my activity class I have fragText() method which is called on button click.

    public void fragText(){
        String tagName = "tpTag";
        Fragment fr =  MyFragment.newInstance();
        getSupportFragmentManager().beginTransaction().replace(R.id.frag, fr, tagName).commit();
        MyFragment tp = (MyFragment) getSupportFragmentManager().findFragmentByTag(tagName);

and tp.changeText(); gives me NullPointerException. Could please help me with the problem?
here is full code of 4 files:http://pastebin.com/NQBieFLi

There is a delay between instance being call and the textView being created. Since there is no textView app throws exception. Having a delay solved the problem.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.