Search code examples
javaandroid-studioandroid-fragmentsandroid-viewpager

Saving data from fragment to file AndroidStudio


I have Fragment1 and Fragment2. Fragment1 is a form of EditTexts which saves its data into a text file. I want the user to be able to swipe back and forth between Fragment1 and Fragment2, where each time they swipe, the data from Fragment1 is saved onto a file.

So far, I've implemented each form as a new fragment using ViewPager and used an addOnPageChangeListener to save the file each time the user swipes. This works, but the user-input data is completely empty.

This is my current code for where the user swipes to save:

    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {

                //Saves the data into an array of strings (this is a small snippet)
                Details = new String[2];

                //This line saves!
                Details[0] = "Details:\n\n";

                //This line contains only "Detail1" in the file 
                Details[1] = "Detail1: " + Detail1.getText().toString().trim() + "\n";
              
                saveToTxtFile(Details);

            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }

And my code for 'saveToTxtFile':

    private void saveToTxtFile(String[] Details) {
        if (Details != null) {

            try {
                File myDir = new File(getFilesDir().getAbsolutePath());
                FileWriter fw = new FileWriter(myDir + "/" + fileName(), false);

                for (String Detail : Details) {
                    fw.write(Detail);
                }
                fw.close();

                Toast.makeText(this, "Saved to " + getFilesDir() + "/" + fileName(), Toast.LENGTH_LONG).show();

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

            }
        }

    }

I'm pretty new to Android Studio and Java, so would appreciate some beginner-friendly tips.


Solution

  • I would not use a PageChangeListener as this is in the wrong scope and breaks the concept of using Fragments. The wrong scope is probably why getting the text of the field returns empty and the PageChangeListener is triggered too late to get details from the Fragment.

    Try using FragmentStatePagerAdapter for your adapter https://developer.android.com/reference/androidx/fragment/app/FragmentStatePagerAdapter

    As this can automatically save the state of the Fragment for later restore (It won't save it to a file though).

    If you really do want to save it to a file then trigger the saving in the Fragment, this will be the right scope.

    In the current version of ViewPager the Fragment's onPause method is called when it is no longer the primary Fragment (the one on screen), so put your save method in the Fragment's onPause.
    The Fragment's onResume method is called when a Fragment becomes the primary Fragment, this is where you would do a "Restore" from file.

    Note that on old Viewpager versions, this lifecycle behaviour had to be configure on, but now it is the default.