0

I have in fragment1 :

  • Spinner categories.
  • RadioGroup type of ad.
  • ImageView where I get the image from gallery and I stock the path in variable path.

Fragment2 contains title of book, price.. and button back to fragment1.

    backToFrgFirst.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            FragmentTransaction transection = getFragmentManager().beginTransaction();
            AddBookPhotosFragment mfragment = new AddBookPhotosFragment();
            transection.replace(R.id.mainFrame, mfragment ).addToBackStack( "TAG" ).commit();


        }
    });

When I go back to fragment, the data is reset, and the choices of the user are not kept.

Update with code of fragment1:

public class AddBookPhotosFragment extends Fragment implements AdapterView.OnItemClickListener {

private static final String TAG = AddBookPhotosFragment.class.getSimpleName();
// Variable declared 
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    final View rootView = inflater.inflate(R.layout.fragment_add_book_photos,
            container, false);

    auth = FirebaseAuth.getInstance();
    mDatabase = FirebaseDatabase.getInstance();
    myRef = mDatabase.getReference("categories");
    spinnerCat = (Spinner) rootView.findViewById(R.id.spinner_cat_book);
    radioGroup = (RadioGroup) rootView.findViewById(R.id.type_annonce_radio_btn);
    selectImage = (ImageView) rootView.findViewById(R.id.book_picture);
    nextbtn = (Button) rootView.findViewById(R.id.next_Button_frg_photo);

    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            final List<String> catListBook = new ArrayList<String>();

            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {

                Categoriesbook book = snapshot.getValue(Categoriesbook.class);
                String catBook = book.getNom_cat();
                catListBook.add(catBook);
            }

            ArrayAdapter<String> catAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, catListBook);
            spinnerCat.setAdapter(catAdapter);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

            System.out.println("The read failed: " + databaseError.getMessage());

        }
    });

    spinnerCat.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            catlivre = (String) parent.getItemAtPosition(position);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            radiobtn = (RadioButton) rootView.findViewById(checkedId);
            rdBtnText = (String) radiobtn.getText();

        }
    });


    selectImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showFileChooser();

        }
    });


    nextbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            FragmentTransaction transection = getFragmentManager().beginTransaction();
            AddBookInfosFragment mfragment = new AddBookInfosFragment();
            Bundle bundle = new Bundle();

            bundle.putString("catSelected", catlivre);
            bundle.putString("typeAnSelected", rdBtnText);
            bundle.putString("uRI", filePath.toString());
            mfragment.setArguments(bundle);
            transection.replace(R.id.mainFrame, mfragment).addToBackStack(TAG);
            transection.commit();


        }

    });

    return rootView;

}


private void showFileChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE_REQUEST && resultCode == getActivity().RESULT_OK && data != null && data.getData() != null) {
        filePath = data.getData();
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
            selectImage.setImageBitmap(bitmap);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

}

Amal
  • 279
  • 3
  • 5
  • 21
  • 3
    Possible duplicate http://stackoverflow.com/questions/39721505/save-and-restore-fragment-state – groomy Mar 14 '17 at 15:25
  • Is the state restored properly when you go back using the physical back button (or the one in the navigation bar at the bottom of the screen)? Or does it do this only when using the back button in the action bar? – Daniel Kvist Mar 14 '17 at 16:12
  • I tried the solution but it did not work for me. @groomy – Amal Mar 14 '17 at 16:13
  • I'm using a button That I created in layout. `` @DanielKvist – Amal Mar 14 '17 at 16:18
  • @Amal Make sure you also add the transaction when switching from the first to the second fragment to the back stack, and then try calling `getFragmentManager().popBackStack()` from the "back button"'s `OnClickListener`. – Daniel Kvist Mar 14 '17 at 16:22
  • I add `getFragmentManager().popBackStack();` "back button" and i have an err `NullPointerException at ArrayAdapter catAdapter = new ArrayAdapter(getActivity(), android.R.layout.simple_spinner_item, catListBo` @DanielKvist – Amal Mar 14 '17 at 17:34
  • @Amal One more problem I see right away in the code is that you're giving the both transactions the same tag (`"TAG"`). Though in order to figure out the source of the exception It'd help if you could provide the source of the first fragment's class. – Daniel Kvist Mar 14 '17 at 19:15
  • I update the question by adding source of first fragment. @DanielKvist – Amal Mar 14 '17 at 19:35
  • 1
    @Amal Looks okay, though you should remove the code in `backToFrgFirst`'s `OnClickListener` and only call `getFragmentManager().popBackStack()`. Also, try replacing `getActivity()` with `getContext()` in the constructor of the `ArrayAdapter` in order to get rid of the null pointer exception. – Daniel Kvist Mar 14 '17 at 20:10
  • The back button works fine( fragment 2 to fragment 1) , spinner displays the categories but I still can not find the category I selected before. @DanielKvist – Amal Mar 15 '17 at 11:31
  • I'm going to post another question. I think it has nothing to do with the back button. – Amal Mar 15 '17 at 16:20

3 Answers3

1

You need to get value and save it and then set new value when get back. you can save in a file or in SharedPreference

SharedPreference sharedPref = getSharedPreference("preFileName", MODE_PRIVATE);
SharedPreference.Editor editor = sharedPref.edit();
edit.putInt("keyValue", spinner1.getSelectedItemPosition());

and then get value and set it to Spinner.

spinner1.setSelection(getSharedPreference("preFileName", MODE_PRIVATE).getInt("keyValue", 0));
Elias Fazel
  • 2,093
  • 16
  • 20
0

You can try to do it via InstanceState:

Fragment1 need to save data. In order to do it, need to override onSaveInstanceState method like this:

@Override
public void onSaveInstanceState(Bundle outState) {
    outState.putString("key1", "what_to_store");
    outState.putBoolean("checked1", true);
    //in addition put any other string, int, or whatever you want by outState.putSOMETHING

    super.onSaveInstanceState(outState);
}

After that you need to receive data in the same Fragment1 by overriding another method like this:

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

        String myString = "";
        boolean myBoolean1 = false;
        if (savedInstanceState != null) {
            myString = savedInstanceState.getString("key1");
            myBoolean1 = savedInstanceState.getBoolean("checked1");
            //do something with your myString. For example bind your image src with resource from this string            
        }
    }

So you need to store\receive all data you want to be saved: states of RadioGroup buttons, Texts, Image src and so on.

SerhiiK
  • 781
  • 8
  • 12
0

Please use saved instant state with as bundle whatever you want to keep it will alive until you call detach or system call detach