Send data between fragments












0















I have used this tutorial to learn how to pass data between fragments:



https://www.journaldev.com/14207/android-passing-data-between-fragments



And it works perfectly if I have two fragments. But my application needs more (7) fragments. The fragments are tabs on a tablayout. When I switch back and forth between two tabs next to eachother it's good. But as soon as I switch from tab0 to a tab further away (tab5), send message, then check it on tab0, the EditText gets back it's original value.



When I change the value of an EditText, I change the value of the tab's title. And it updates properly. (I go from tab0 to tab5, send the message, tab0's title changes, so the message is received.) But when I go back to tab0, it changes back it's original value (and also it's tab title, but that is correct working).



It's like the desired changes happen, but when I switch back, it gets back the original value. Does it have something to do with destroying and savedInstances? How to get rid of this?



In STab.java (code of a tab):



@Override
public void onAttach(Context context) {
super.onAttach(context);

try {
SD = (SendData) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
interface SendData {
void setStructureBonusTileSpinner(int position, int currentTabNumber);
}

protected void setStructureBonusTileSpinner(int position){
spinnerStructureBonusTile.setSelection(position);
}


Also in STab.java, in the onViewCreated method:



spinnerStructureBonusTile.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
SD.setStructureBonusTileSpinner(spinnerStructureBonusTile.getSelectedItemPosition(), tabNumber);
}
});


In MainActivity.java which implements STab.SendData:



@Override
public void setStructureBonusTileSpinner(int position, int currentTabNumber) {

for(int i = 0; i < mSectionsPagerAdapter.getCount(); i++){

if(i != currentTabNumber) {
String tag = "android:switcher:" + R.id.container + ":" + i;
STab f = (STab) getSupportFragmentManager().findFragmentByTag(tag);
if(f != null){
f.setStructureBonusTileSpinner(position);
}
}

}

}









share|improve this question

























  • Please show some code .

    – Arpit Agarwal
    Nov 18 '18 at 8:49











  • Not going to make an answer because it's just a blind shot, but if it works with 2 fragments, and it doesn't with more, they are probably just being refreshed on the switch, try with this: mViewPager.setOffscreenPageLimit(fragmentCount - 1)

    – JMedinilla
    Nov 18 '18 at 8:56











  • @JMedinilla Great, that worked actually. Thank you! Put it in an answer, please, then I can mark it.

    – Siriann
    Nov 18 '18 at 9:00
















0















I have used this tutorial to learn how to pass data between fragments:



https://www.journaldev.com/14207/android-passing-data-between-fragments



And it works perfectly if I have two fragments. But my application needs more (7) fragments. The fragments are tabs on a tablayout. When I switch back and forth between two tabs next to eachother it's good. But as soon as I switch from tab0 to a tab further away (tab5), send message, then check it on tab0, the EditText gets back it's original value.



When I change the value of an EditText, I change the value of the tab's title. And it updates properly. (I go from tab0 to tab5, send the message, tab0's title changes, so the message is received.) But when I go back to tab0, it changes back it's original value (and also it's tab title, but that is correct working).



It's like the desired changes happen, but when I switch back, it gets back the original value. Does it have something to do with destroying and savedInstances? How to get rid of this?



In STab.java (code of a tab):



@Override
public void onAttach(Context context) {
super.onAttach(context);

try {
SD = (SendData) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
interface SendData {
void setStructureBonusTileSpinner(int position, int currentTabNumber);
}

protected void setStructureBonusTileSpinner(int position){
spinnerStructureBonusTile.setSelection(position);
}


Also in STab.java, in the onViewCreated method:



spinnerStructureBonusTile.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
SD.setStructureBonusTileSpinner(spinnerStructureBonusTile.getSelectedItemPosition(), tabNumber);
}
});


In MainActivity.java which implements STab.SendData:



@Override
public void setStructureBonusTileSpinner(int position, int currentTabNumber) {

for(int i = 0; i < mSectionsPagerAdapter.getCount(); i++){

if(i != currentTabNumber) {
String tag = "android:switcher:" + R.id.container + ":" + i;
STab f = (STab) getSupportFragmentManager().findFragmentByTag(tag);
if(f != null){
f.setStructureBonusTileSpinner(position);
}
}

}

}









share|improve this question

























  • Please show some code .

    – Arpit Agarwal
    Nov 18 '18 at 8:49











  • Not going to make an answer because it's just a blind shot, but if it works with 2 fragments, and it doesn't with more, they are probably just being refreshed on the switch, try with this: mViewPager.setOffscreenPageLimit(fragmentCount - 1)

    – JMedinilla
    Nov 18 '18 at 8:56











  • @JMedinilla Great, that worked actually. Thank you! Put it in an answer, please, then I can mark it.

    – Siriann
    Nov 18 '18 at 9:00














0












0








0








I have used this tutorial to learn how to pass data between fragments:



https://www.journaldev.com/14207/android-passing-data-between-fragments



And it works perfectly if I have two fragments. But my application needs more (7) fragments. The fragments are tabs on a tablayout. When I switch back and forth between two tabs next to eachother it's good. But as soon as I switch from tab0 to a tab further away (tab5), send message, then check it on tab0, the EditText gets back it's original value.



When I change the value of an EditText, I change the value of the tab's title. And it updates properly. (I go from tab0 to tab5, send the message, tab0's title changes, so the message is received.) But when I go back to tab0, it changes back it's original value (and also it's tab title, but that is correct working).



It's like the desired changes happen, but when I switch back, it gets back the original value. Does it have something to do with destroying and savedInstances? How to get rid of this?



In STab.java (code of a tab):



@Override
public void onAttach(Context context) {
super.onAttach(context);

try {
SD = (SendData) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
interface SendData {
void setStructureBonusTileSpinner(int position, int currentTabNumber);
}

protected void setStructureBonusTileSpinner(int position){
spinnerStructureBonusTile.setSelection(position);
}


Also in STab.java, in the onViewCreated method:



spinnerStructureBonusTile.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
SD.setStructureBonusTileSpinner(spinnerStructureBonusTile.getSelectedItemPosition(), tabNumber);
}
});


In MainActivity.java which implements STab.SendData:



@Override
public void setStructureBonusTileSpinner(int position, int currentTabNumber) {

for(int i = 0; i < mSectionsPagerAdapter.getCount(); i++){

if(i != currentTabNumber) {
String tag = "android:switcher:" + R.id.container + ":" + i;
STab f = (STab) getSupportFragmentManager().findFragmentByTag(tag);
if(f != null){
f.setStructureBonusTileSpinner(position);
}
}

}

}









share|improve this question
















I have used this tutorial to learn how to pass data between fragments:



https://www.journaldev.com/14207/android-passing-data-between-fragments



And it works perfectly if I have two fragments. But my application needs more (7) fragments. The fragments are tabs on a tablayout. When I switch back and forth between two tabs next to eachother it's good. But as soon as I switch from tab0 to a tab further away (tab5), send message, then check it on tab0, the EditText gets back it's original value.



When I change the value of an EditText, I change the value of the tab's title. And it updates properly. (I go from tab0 to tab5, send the message, tab0's title changes, so the message is received.) But when I go back to tab0, it changes back it's original value (and also it's tab title, but that is correct working).



It's like the desired changes happen, but when I switch back, it gets back the original value. Does it have something to do with destroying and savedInstances? How to get rid of this?



In STab.java (code of a tab):



@Override
public void onAttach(Context context) {
super.onAttach(context);

try {
SD = (SendData) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
interface SendData {
void setStructureBonusTileSpinner(int position, int currentTabNumber);
}

protected void setStructureBonusTileSpinner(int position){
spinnerStructureBonusTile.setSelection(position);
}


Also in STab.java, in the onViewCreated method:



spinnerStructureBonusTile.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
SD.setStructureBonusTileSpinner(spinnerStructureBonusTile.getSelectedItemPosition(), tabNumber);
}
});


In MainActivity.java which implements STab.SendData:



@Override
public void setStructureBonusTileSpinner(int position, int currentTabNumber) {

for(int i = 0; i < mSectionsPagerAdapter.getCount(); i++){

if(i != currentTabNumber) {
String tag = "android:switcher:" + R.id.container + ":" + i;
STab f = (STab) getSupportFragmentManager().findFragmentByTag(tag);
if(f != null){
f.setStructureBonusTileSpinner(position);
}
}

}

}






android fragment android-tablayout






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 18 '18 at 9:24







Siriann

















asked Nov 18 '18 at 8:42









SiriannSiriann

92111




92111













  • Please show some code .

    – Arpit Agarwal
    Nov 18 '18 at 8:49











  • Not going to make an answer because it's just a blind shot, but if it works with 2 fragments, and it doesn't with more, they are probably just being refreshed on the switch, try with this: mViewPager.setOffscreenPageLimit(fragmentCount - 1)

    – JMedinilla
    Nov 18 '18 at 8:56











  • @JMedinilla Great, that worked actually. Thank you! Put it in an answer, please, then I can mark it.

    – Siriann
    Nov 18 '18 at 9:00



















  • Please show some code .

    – Arpit Agarwal
    Nov 18 '18 at 8:49











  • Not going to make an answer because it's just a blind shot, but if it works with 2 fragments, and it doesn't with more, they are probably just being refreshed on the switch, try with this: mViewPager.setOffscreenPageLimit(fragmentCount - 1)

    – JMedinilla
    Nov 18 '18 at 8:56











  • @JMedinilla Great, that worked actually. Thank you! Put it in an answer, please, then I can mark it.

    – Siriann
    Nov 18 '18 at 9:00

















Please show some code .

– Arpit Agarwal
Nov 18 '18 at 8:49





Please show some code .

– Arpit Agarwal
Nov 18 '18 at 8:49













Not going to make an answer because it's just a blind shot, but if it works with 2 fragments, and it doesn't with more, they are probably just being refreshed on the switch, try with this: mViewPager.setOffscreenPageLimit(fragmentCount - 1)

– JMedinilla
Nov 18 '18 at 8:56





Not going to make an answer because it's just a blind shot, but if it works with 2 fragments, and it doesn't with more, they are probably just being refreshed on the switch, try with this: mViewPager.setOffscreenPageLimit(fragmentCount - 1)

– JMedinilla
Nov 18 '18 at 8:56













@JMedinilla Great, that worked actually. Thank you! Put it in an answer, please, then I can mark it.

– Siriann
Nov 18 '18 at 9:00





@JMedinilla Great, that worked actually. Thank you! Put it in an answer, please, then I can mark it.

– Siriann
Nov 18 '18 at 9:00












2 Answers
2






active

oldest

votes


















0














The off screen page limit is set to 1 by default, so those fragments beyond the two next to each other that you say that work, are being recreated from the adapter.



If you are not going to perform heavy tasks, it would be enough just changing that limit.



mViewPager.setOffScreenPageLimit(fragmentCount - 1)


PD: Just as a tip, you should never have more than 3 tabs, it would be better if you could think on a better aproach rather than this.



PD2: You should also post relevant code






share|improve this answer
























  • Fair enough, I added some code. In this case, no heavy tasks, and a little more tabs are just fine. If I had more, I'd definitely use something else. Thanks again!

    – Siriann
    Nov 18 '18 at 9:26



















1














If you transfer data from Fragment A to B, then do as below.



1.Fragment A -> Base Activity -> Fragment B (Not recommend)
You can transfer the data by using parent activity.
2.Using Bundle object.



public static Fragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53359179%2fsend-data-between-fragments%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    The off screen page limit is set to 1 by default, so those fragments beyond the two next to each other that you say that work, are being recreated from the adapter.



    If you are not going to perform heavy tasks, it would be enough just changing that limit.



    mViewPager.setOffScreenPageLimit(fragmentCount - 1)


    PD: Just as a tip, you should never have more than 3 tabs, it would be better if you could think on a better aproach rather than this.



    PD2: You should also post relevant code






    share|improve this answer
























    • Fair enough, I added some code. In this case, no heavy tasks, and a little more tabs are just fine. If I had more, I'd definitely use something else. Thanks again!

      – Siriann
      Nov 18 '18 at 9:26
















    0














    The off screen page limit is set to 1 by default, so those fragments beyond the two next to each other that you say that work, are being recreated from the adapter.



    If you are not going to perform heavy tasks, it would be enough just changing that limit.



    mViewPager.setOffScreenPageLimit(fragmentCount - 1)


    PD: Just as a tip, you should never have more than 3 tabs, it would be better if you could think on a better aproach rather than this.



    PD2: You should also post relevant code






    share|improve this answer
























    • Fair enough, I added some code. In this case, no heavy tasks, and a little more tabs are just fine. If I had more, I'd definitely use something else. Thanks again!

      – Siriann
      Nov 18 '18 at 9:26














    0












    0








    0







    The off screen page limit is set to 1 by default, so those fragments beyond the two next to each other that you say that work, are being recreated from the adapter.



    If you are not going to perform heavy tasks, it would be enough just changing that limit.



    mViewPager.setOffScreenPageLimit(fragmentCount - 1)


    PD: Just as a tip, you should never have more than 3 tabs, it would be better if you could think on a better aproach rather than this.



    PD2: You should also post relevant code






    share|improve this answer













    The off screen page limit is set to 1 by default, so those fragments beyond the two next to each other that you say that work, are being recreated from the adapter.



    If you are not going to perform heavy tasks, it would be enough just changing that limit.



    mViewPager.setOffScreenPageLimit(fragmentCount - 1)


    PD: Just as a tip, you should never have more than 3 tabs, it would be better if you could think on a better aproach rather than this.



    PD2: You should also post relevant code







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 18 '18 at 9:05









    JMedinillaJMedinilla

    378312




    378312













    • Fair enough, I added some code. In this case, no heavy tasks, and a little more tabs are just fine. If I had more, I'd definitely use something else. Thanks again!

      – Siriann
      Nov 18 '18 at 9:26



















    • Fair enough, I added some code. In this case, no heavy tasks, and a little more tabs are just fine. If I had more, I'd definitely use something else. Thanks again!

      – Siriann
      Nov 18 '18 at 9:26

















    Fair enough, I added some code. In this case, no heavy tasks, and a little more tabs are just fine. If I had more, I'd definitely use something else. Thanks again!

    – Siriann
    Nov 18 '18 at 9:26





    Fair enough, I added some code. In this case, no heavy tasks, and a little more tabs are just fine. If I had more, I'd definitely use something else. Thanks again!

    – Siriann
    Nov 18 '18 at 9:26













    1














    If you transfer data from Fragment A to B, then do as below.



    1.Fragment A -> Base Activity -> Fragment B (Not recommend)
    You can transfer the data by using parent activity.
    2.Using Bundle object.



    public static Fragment newInstance(String param1, String param2) {
    BlankFragment fragment = new BlankFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
    mParam1 = getArguments().getString(ARG_PARAM1);
    mParam2 = getArguments().getString(ARG_PARAM2);
    }
    }





    share|improve this answer




























      1














      If you transfer data from Fragment A to B, then do as below.



      1.Fragment A -> Base Activity -> Fragment B (Not recommend)
      You can transfer the data by using parent activity.
      2.Using Bundle object.



      public static Fragment newInstance(String param1, String param2) {
      BlankFragment fragment = new BlankFragment();
      Bundle args = new Bundle();
      args.putString(ARG_PARAM1, param1);
      args.putString(ARG_PARAM2, param2);
      fragment.setArguments(args);
      return fragment;
      }

      @Override
      public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      if (getArguments() != null) {
      mParam1 = getArguments().getString(ARG_PARAM1);
      mParam2 = getArguments().getString(ARG_PARAM2);
      }
      }





      share|improve this answer


























        1












        1








        1







        If you transfer data from Fragment A to B, then do as below.



        1.Fragment A -> Base Activity -> Fragment B (Not recommend)
        You can transfer the data by using parent activity.
        2.Using Bundle object.



        public static Fragment newInstance(String param1, String param2) {
        BlankFragment fragment = new BlankFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
        }
        }





        share|improve this answer













        If you transfer data from Fragment A to B, then do as below.



        1.Fragment A -> Base Activity -> Fragment B (Not recommend)
        You can transfer the data by using parent activity.
        2.Using Bundle object.



        public static Fragment newInstance(String param1, String param2) {
        BlankFragment fragment = new BlankFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
        }
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 18 '18 at 9:04









        eltoryn7eltoryn7

        686




        686






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53359179%2fsend-data-between-fragments%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Tangent Lines Diagram Along Smooth Curve

            Yusuf al-Mu'taman ibn Hud

            Zucchini