0

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?

Wavrik
  • 61
  • 9

1 Answers1

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);
Lucem
  • 2,912
  • 3
  • 20
  • 33
  • I put but nothing happens, always go null when he passes the validation on onViewCreated from the Fragment. – Wavrik Jun 04 '18 at 17:17
  • When I press back on my Activity B, the Activity is not destroyed I make a debug for it, and put a log in onDestroy function from Activity B never got destroyed. I put this function @Override public void onBackPressed() { Intent intent = new Intent(this, MainActivity.class); startActivityForResult(intent, 1); } to prevent this, you know? I want just to save the data from the Fragment when the user goes to another activity and when he goes back to Activity A that have Fragment A he sees the old data. – Wavrik Jun 04 '18 at 17:40
  • @Wavrik adding more content to the answer – Lucem Jun 04 '18 at 17:43
  • Hi Lucem, thank you for your help. I see in this thread from stack overflow that is not a good practice savedInstanceState to persistence data. https://stackoverflow.com/questions/151777/saving-android-activity-state-using-save-instance-state And must do what you said, OnPause() or OnResume() but how I do that? If go to OnPause and my variable will lost? after change activity how I will restore it? Another thing, I don't want the Shared Preference solution. – Wavrik Jun 04 '18 at 17:53
  • Its actually the simpler way to go for. Would you like me to edit the answer with the alternative? @Wavrik – Lucem Jun 04 '18 at 17:57
  • I will love Lucem. Shared Preference is the only way? – Wavrik Jun 04 '18 at 18:05
  • One more question Lucem. I just use onSaveInstanceState when the orientation change? Is not for data persistence when i change the activity? – Wavrik Jun 04 '18 at 19:06
  • Okay, then you can save the data stil with the instance. look at this : https://stackoverflow.com/questions/29208086/save-the-position-of-scrollview-when-the-orientation-changes#answer-29208325 – Lucem Jun 05 '18 at 18:47