myFragment and myFragment2 both return null for below code. Not sure what the problem is. This solution didn't solve the problem unfortunately, it is not a duplicate.
MainActivity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
NonceInputFragment nonceInputFragment = new NonceInputFragment();
transaction.add(R.id.nonce_input_fragment,nonceInputFragment,"test");
transaction.commit();
// It crashes on this line:
getSupportFragmentManager().executePendingTransactions();
NonceInputFragment myFragment = (NonceInputFragment) getSupportFragmentManager().findFragmentById(R.id.nonce_input_fragment);
NonceInputFragment myFragment2 = (NonceInputFragment) getSupportFragmentManager().findFragmentByTag("test");
}
}
nonce_input.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/nonce_input_fragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/tvLabel"
android:layout_gravity="center_horizontal" />
</LinearLayout>
NonceInputFragment
public class NonceInputFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.nonce_input, container, false);
return view;
}
}
Error message:
java.lang.RuntimeException: Unable to start activity ComponentInfo{name.com.viewpagercode/name.com.viewpagercode.MainActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f0b0056 (name.com.viewpagercode:id/nonce_input_fragment) for fragment NonceInputFragment{cece542 #0 id=0x7f0b0056 test}