How to change fragment's textView's text from activity

I cannot find how to change fragment's textview from an Activity. I have 4 files :

MainActivity.java
activity_main.xml
FragmentClass.java
frag_class.xml

frag_class.xml has textView, I want to change the text from MainActivity.java. FragmentClass extends Fragment, this fragment is displayed in MainActivity FragmentClass has:

public void changeText(String text){
 TextView t = (TextView) this.getView().findViewById(R.id.tView);
 t.setText(text);
}

and in MainActivity I tried this:

FragmentClass fc = new FragmentClass();
fc.changeText("some text");

But sadly this code gives me NullPointerException at fc.changeText("some text"); I've also tried changing the text directly from MainActivity with:

 TextView t = (TextView) this.getView().findViewById(R.id.tView);
 t.setText(text);

which Failed.

[EDIT] The full code is here


Solution 1:

You can find the instance of Fragment by using,

For support library,

YourFragment fragment_obj = (YourFragment)getSupportFragmentManager().
                                              findFragmentById(R.id.fragment_id);

else

YourFragment fragment_obj = (YourFragment)getFragmentManager().
                                             findFragmentById(R.id.fragment_id); 

Then create a method in the Fragment that updates your TextView and call that method using fragment_obj like,

fragment_obj.updateTextView();

Solution 2:

From activity to Fragment by Fragment Transaction:

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); 
    }
    public static void changeFragmentTextView(String s) {
        Fragment frag = getFragmentManager().findFragmentById(R.id.yourFragment);
        ((TextView) frag.getView().findViewById(R.id.textView)).setText(s);  
    }
}

Solution 3:

@Lalit answer is correct but I see that you dont need to create a function like fragment_obj.updateTextView();. I set all my view as class level objects and was able to update the textview directly.

fragmentRegister.textViewLanguage.setText("hello mister how do you do");

Note: If you need to perform more than one action then having a function is the way to go.