Lately i've been stuck! I have one Activity (not my MainActivity, I mean, it is not where I created this Fragment), and I need to pass some data. I've already tried to pass using Bundle, using getter, but the same issue appears: "Attempt to invoke virtual method {...} on a null object." at the line where I call the Bundle in the Fragment. I am new at this, so I'm sorry if this is a simple question and I didn't understand. Below the relevant parts of my code:
On Activity (not the main activity):
public void save(){
myGoal = spinnerGoals.getSelectedItem().toString();
Bundle bundle = new Bundle();
bundle.putString("goal", myGoal);
GoalFragment goalFragment = new GoalFragment();
goalFragment.setArguments(bundle);
}
On Fragment (where I want to put this 'goal')
private TextView goal;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate( R.layout.fragment_goal, container, false);
goal = view.findViewById(R.id.myGoalText);
Bundle bundle = getArguments();
if (bundle != null) {
final String myGoal = bundle.getString("goal");
goal.setText(myGoal);
}
return view;
}
On MainActivity (where I created the Fragments):
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment() )
.commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_goal:
selectedFragment = new GoalFragment();
break;
case R.id.nav_info:
selectedFragment = new InfoFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment)
.commit();
return true;
}
};
Please, I've lost much time trying to solve this by myself hahaha. If anyone can help me, i'd appreciate that!