Search code examples
androidandroid-intentbundle

A Bundle is null after returning back from another activity


I have a problem with a bundle. I have 2 activities(with fragments), and I want to store data in a fragment FeedListFragment.

When I rotating screen, it works just fine, but when I returning back from another activity, the bundle is null.

@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    progressBar = view.findViewById(R.id.progressBar);

    if ( savedInstanceState == null ) {
        feedProviderViewModel.getAll().observe(this, feedProviders -> {
            feedEntryViewModel.deleteAll();
            RssDownloader rssDownloader = new RssDownloader(feedProviders, this, progressBar);
        });
    }

   ...
}

And I also have onSaveInstanceState

@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
    Log.d("tag","Save instance state called");
    outState.putString(FIRST_RUN,"Downloaded");
}

Solution

  • don't use intent to back from your second activity to your first on use onBackPress

    btn_message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    

    otherwise you have to put your data into the intent that you have sent already from activity 1

    btn_message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            Intent intent = new Intent(this, YOUR ACTIVITY);
            intent.putExtra("bundle",bundle);
            startActivity(intent);
            }
        });
    

    third way to save it on SharedPreference