简体   繁体   中英

How to pass data from Activity to already created Fragment?

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!

Create a method in Fragment which you want to receive data, then invoke the method in Activity.

Write this code in Activity:

 Bundle bundle = new Bundle();
 bundle.putString("goal", myGoal);
 fragmentObj.sendData(bundle);

write code in Fragment:

public void sendData(Bundle bundle){
      String myGoal = bundle.getString("goal");
}

If the Activity(not main activity) was created from your fragment, you could use

startActivityForResult()

method to receive data after the activity is ended, read about it more here

If that is not the case, you need to persist (in storage) the data using Preferences or Room Database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM