There is an Activity and Fragment , you need to pass a variable of type int Id from Activity to Fragment for further use, I tried through the bundle and all the time the NullPointerException error crashes and refers to the fact that nothing comes to the variable Id
Attempt to invoke virtual method 'int android.os.Bundle.getInt (java.lang.String)' on a null object reference
Code in Fragment :
public class MapFragment extends Fragment implements View.OnClickListener private int id; public static MapFragment newInstance(String key,int value) { MapFragment fragment = new MapFragment(); Bundle bundle = new Bundle(); bundle.putInt(key,value); fragment.setArguments(bundle); return fragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.map_fragment, container, false); id = this.getArguments().getInt("id"); return view; } } And the code in the Activity :
public class ChooseWarActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_choose_war); int id = 15; MapFragment fragmentID = MapFragment.newInstance("id",id); } } Tell me how can I do it differently or what is my mistake, otherwise I already broke my head?
UPD
Could this be related to the type of adding a fragment? It seemed to do according to a template and when you press the button, a fragment appears, it suddenly clarifies something
public class GameActivity extends AppCompatActivity { private MapFragment gameFragment; private FragmentManager manager; private FragmentTransaction transaction; protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.game_layout); manager = getSupportFragmentManager(); gameFragment = new MapFragment(); textView = (TextView) findViewById(R.id.gameInfo); button = (Button) findViewById(R.id.gameStartbtn); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { transaction = manager.beginTransaction(); transaction.add(R.id.container, gameFragment); transaction.commit(); } }); } }