blackreaper
blackreaper

Reputation: 69

App crashes on passing data from activity to fragment

I was working on passing the recyclerview item from activity to fragment and I found Bundle useful for that but in my fragment when I try to retrieve the data then the app crashes, so how do I fix it?

This is my activity file code for sending the data

            Bundle bundle = new Bundle();
            bundle.putString("title", title.getText().toString());
            bundle.putString("description", 
            description.getText().toString());
            bundle.putString("date", date.getText().toString());

            UpdatesActivity updatesActivity = new UpdatesActivity();
            updatesActivity.setArguments(bundle);

This is my fragment activity(named UpdatesActivity)

private List<Info> infoList = new ArrayList<>();
private InfoAdapter mAdapter;
private Button btnLogOut;
private FirebaseAuth firebaseAuth;
private String title, description, date;

public UpdatesActivity() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_updates, container, false);

    RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);

    title = getArguments().getString("title");
    description = getArguments().getString("description");
    date = getArguments().getString("date");

    mAdapter = new InfoAdapter(infoList);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
    recyclerView.setAdapter(mAdapter);

    return view;
    }
}

Now when I remove the lines for retrieving the title, description and date then the app works fine but on adding them the app crashes.

Upvotes: 0

Views: 307

Answers (1)

Fateme Afshari
Fateme Afshari

Reputation: 494

you can use from this method

 private void loadFragment(Fragment fragment) {
        Bundle bundle = new Bundle();
        bundle.putString("title", title.getText().toString());
        bundle.putString("description",
                description.getText().toString());
        bundle.putString("date", date.getText().toString());
        fragment.setArguments(bundle);
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fm.beginTransaction();
        fragmentTransaction.replace(R.id.fragmentContainer, fragment);
        fragmentTransaction.commit(); // save the changes

    }

Upvotes: 1

Related Questions