onSaveInstanceState null in Fragment everytime

时间:2018-06-04 17:02:29

标签: android android-fragments android-activity

I search everywhere and for the solution but not find it, I need some help.

I have an app that has Two activity's, Activity A and Activity B, but B have fragments, the first fragment from B, have an important data that I don't want to lose when the user press back when going to Activity A.

My problem is this every time I'm back to Activity A and go to B, my Data go empty because android clear it, so I made some search and changes on the code and still not find the solution. Now my code :

ACTIVITY A

  fbReceive.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                startActivity(new Intent(MainActivity.this, OmniActivity.class));

            }
        });

I call B from this line and when they go to B this is the code :

ACTIVITY B

public class OmniActivity extends BaseActivity {

private View parent_view;

private TabLayout tab_layout;

FragmentOmni fragmentOmni     = new FragmentOmni();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_omni_om);
    parent_view = findViewById(R.id.container);

    Tools.setSystemBarColor(this, R.color.new_purple_O200);

    openFragment(fragmentOmni);

    initToolbar();
    initComponent();

}

public void openFragment(final Fragment fragment) {

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.replace(R.id.containerView, fragment, fragment.getTag());
    transaction.addToBackStack(null);
    transaction.commit();

}

@Override
public void onBackPressed() {

   Intent intent = new Intent(this, MainActivity.class);
   startActivityForResult(intent, 1);

}

    private void initToolbar() {

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("Voltar");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    toolbar.getNavigationIcon().setColorFilter(getResources().getColor(android.R.color.white), PorterDuff.Mode.SRC_ATOP);

    toolbar.setNavigationOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(OmniActivity.this, MainActivity.class);
                startActivityForResult(intent, 1);

            }
    });

}

And when the application executes OpenFragment() they go to this code from Fragment :

FRAGMENT A

public class FragmentOmni extends Fragment {

RecyclerView recyclerView;
MDOmniturn controller;


List<HashMap<String, String>> listproduct;
private ArrayList<Product> producttypelist;
Product tpobjproduct;
private ActionMode actionMode;
private ActionModeCallback actionModeCallback;


private ListProductAdapter lpAdapter;

private NestedScrollView nested_scroll_view;

private ImageButton bt_toggle_input;
private Button      bt_hide_input;
private View        lyt_expand_input;

EditText edOmni, edMani,edEan ;

LinearLayout layoutNoResult;

Handler time;
TextWatcher textexample;


private ProgressBar progressBarProduct;

LinearLayout linearLayout;


public FragmentOmni() {
}

public static FragmentOmni newInstance() {
    FragmentOmni fragment = new FragmentOmni();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if(savedInstanceState != null){

        producttypelist = savedInstanceState.getParcelableArrayList("list");

    }

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View root = inflater.inflate(R.layout.fragment_omni, container, false);

    return root;
}

@Override
public void onSaveInstanceState(Bundle outState) {

    outState.putParcelableArrayList("list", producttypelist);

    super.onSaveInstanceState(outState);

}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {

    if (savedInstanceState != null) {

        producttypelist = savedInstanceState.getParcelableArrayList("list");

    }


    initexpand(view);

    linearLayout = (LinearLayout) view.findViewById(R.id.container);

    edOmni = (EditText) view.findViewById(R.id.edOmni);
    edMani = (EditText) view.findViewById(R.id.edBManifesto);
    edEan  = (EditText) view.findViewById(R.id.edEan);

    progressBarProduct = (ProgressBar) view.findViewById(R.id.progressBarProduct);

    layoutNoResult = (LinearLayout) view.findViewById(R.id.layoutNoResult);
    recyclerView   = (RecyclerView) view.findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.addItemDecoration(new LineItemDecoration(getActivity(), LinearLayout.VERTICAL));
    recyclerView.setHasFixedSize(true);

    controller      = new MDOmniturn(getActivity());
    producttypelist = new ArrayList<>();
    listproduct     = new ArrayList<>();

    addListenerTextChange(edOmni);

    //set data and list adapter
    lpAdapter = new ListProductAdapter(getActivity(), producttypelist);
    recyclerView.setAdapter(lpAdapter);
    lpAdapter.setOnClickListener(new ListProductAdapter.OnClickListener() {
        @Override
        public void onItemClick(View view, Product obj, int pos) {

            if (lpAdapter.getSelectedItemCount() > 0) {

                enableActionMode(pos);

            } else {

                // read the inbox which removes bold from the row
                Product product = lpAdapter.getItem(pos);
                Toast.makeText(getActivity(), "Read: " + product.prd_description, Toast.LENGTH_SHORT).show();

            }

        }

        @Override
        public void onItemLongClick(View view, Product obj, int pos) {
            enableActionMode(pos);
        }
    });

    actionModeCallback = new ActionModeCallback();

}

The savedInstanceState from FRAGMENT A always go NULL, what i'm doing wrong?

1 个答案:

答案 0 :(得分:0)

Replace your code to the following order

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    outState.putParcelableArrayList("list", producttypelist);    
}

It might be possible you are expecting data during the wrong state too. For example, the savedInstanceState will always be null the first time an Activity is started which also points to your fragment, but may be non-null if an Activity is destroyed during rotation, because onCreate is called each time activity starts or restarts.

This line transaction.addToBackStack(null); is unnecessary. You can save the fragment state on its onStop() and onPause() and restore onResume() and onCreate().

You can remove the onBackPressed() in Activity B now



Alternatively, you can use Shared Preferences. When exiting the application, (onBackPressed, onPause ...) save the item you want. For Example the high score of a game.

 activity.getSharedPreferences(getString(R.string.app_name), 
            Context.MODE_PRIVATE).edit().putInt("score", highScore).apply();

And retrieving the score would be:

int value = activity.getSharedPreferences(getString(R.string.app_name), 
            Context.MODE_PRIVATE).getInt("score", 0);