Nemo Nobody Nemo Nobody - 17 days ago 5
Android Question

Manipulating variables within Fragment Classes

With the following Fragment class:

public class TestFrag extends Fragment {

public TextView tViewA;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.mainmenu, container, false);
tViewA = (TextView)view.findViewById(R.id.texta);
return view;
}

public void setTViewText(String textToSet){
tViewA.setText(textToSet);
}
}


and the MainActivity class:

public class MainActivity extends FragmentActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}


public void doStuff(View view){
TestFrag myf = new TestFrag ();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.container, myf);
transaction.commit();

myf.setTViewText("test");
}
}


When calling setTViewText text the app will crash giving a null pointer exception.

The TextView is declared in the XML

<TextView
android:text="Change Me"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="24dp"
android:layout_marginTop="19dp"
android:id="@+id/texta" />


I've been trying to figure this out for awhile now. Whats the correct way to declare and manipulate variables in fragment classes?

Answer

The problem with your method is that you're trying to set a string to the textView which is not yet rendered on the fragment. so your setTViewText() is called before the onCreateView(). You can call the setTViewText() only after the system calls onCreateView() method which is where you assign the reference to the textView to tViewA.

You should use setArgument() method to pass values to fragment.

TestFrag myf = new TestFrag ();
Bundle args = new Bundle();
args.putString("arg_text", your_string);
myf.setArgument(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.container, myf);
transaction.commit();

Inside the onCreateView of the fragment you can access this value by

String yourString = getArgument().getString("arg_text");
tv.setText(yourString);