user2774429
user2774429

Reputation: 201

Android: Sending data to Fragments

I'm trying to simply send data from my Activity class to my fragment, but when I'm trying to call "setText(String text)" in my fragment the program crashes.

ActivityClass:

Fragment_green green = new Fragment_green();
        transaction.replace(R.id.infoFragment, green);
        transaction.addToBackStack(null);
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        transaction.commit();
        green.setText("bar"); //Works okay this far

My Fragment_green:

public class Fragment_green extends Fragment {

String textShow;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    return inflater.inflate(R.layout.fragment_green, container, false);
}

public void setText(String text){
    TextView textView = (TextView) getView().findViewById(R.id.textGreen);
    textView.setText(text); //Crash :(
}}

Everything else works. I can change the fragment to another and so on. I've seen a few similar posts, but when I'm trying to implent those, other problems occur.

I appreciate all helpfull answers!

Upvotes: 1

Views: 80

Answers (1)

HannahMitt
HannahMitt

Reputation: 1020

If you're certain the textview is in your fragment layout, then its probably a lifecycle error. The fragment's view hasn't been inflated when you try to access the textview.

Passing information to a fragment this way isn't recommended. Try passing the string through a bundle, and setting the text in the textview when onCreateView is called.

Upvotes: 1

Related Questions