Search code examples
androidandroid-fragmentstabsandroid-tabhost

TextView forgets its value after tab switching


I've setup a tabhHost in my program with 3 tabs each with a fragment in its content that contains a textView. I've set a button in app that is supposed to update the content of every tab. However the problem i am now facing is that if i change a tab its content gets forgotten and new tab has no value aswell unless i click the button again. Each tab content has a different class but in each of them the class just returns the view with textview in it. I assumed that the values reset on each view inflate however i cannot find a reasonable way to make it work as i intend to it.

Here is the part of the code with the method ran by my button:

 public void getNum(View view) {

    proteinNeeded = weightNum.getValue() * FirstActivity.weightMultiplier;
    carbohydrateNeeded = weightNum.getValue() * 5;

    switch (weightMultiplier) {
        case 2: {
            resultTxt = String.format("Zapotrzebowanie:%nBiałko - %dg.%nWęglowodany - %dg.%n",
                    FirstActivity.proteinNeeded, FirstActivity.carbohydrateNeeded);
            FragmentTab.tv.setText(resultTxt);

            FragmentTab2.dietTxt = String.format("text1");
            FragmentTab2.tv.setText(FragmentTab2.dietTxt);

            FragmentTab3.foodTxt = String.format("text2");
            FragmentTab3.tv.setText(FragmentTab3.foodTxt);....

And here is the code from FragmentTab.java, each tab has more or less same code so i'll post only this one for now:

public class FragmentTab extends Fragment {

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


public static View v;
public static TextView tv;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.fragment_layout, container, false);
    tv = (TextView) v.findViewById(R.id.textResult);

    if (tv != null) {
        tv.setText("nothing has been input yet");
    }


    return v;
}

}

TL;DR - How do I save my values in textView in such a way that if my text gets updated it won't revert to default values after the view gets refreshed?


Solution

  • An option to solve your problem is to use SQLite Database to save your data, and fetch it from database whenever you return to that tab.

    You can refer to this link. Saving Data in SQL Databases.

    For other android storage options, refer to this series of videos. Android Data Storage Options.