How to create Fragment's elements when app starts without recreating them

83 Views Asked by At

I use four fragment in mainactivity and each has it's class with mainactivity class.

I have elements in fragment1 class, when I create them inside onCreateView method they are creating each time when I open the fragment.

I tried to create elements in onStart method in fragment class, nothing changes. I tried to create elements in onCreate method in fragment class, it stops the app.

When I create the elements in onCreate, onStart method in MainActivity, it stops the app.

So, basically I want to create element only once, and when app start they has to be created.

How can I solve this problem? Thanks for help.

2

There are 2 best solutions below

1
On

The easiest way would be to add a simple check for if they’re null or not before creating them:

private String test;

if (test == null) 
    test = new String();

For this method you would make sure the variables are in the scope of your entire class:

class test {
    private String test;

    public void update() {
        if(test == null) test = new String();
            textView.setText(test);
    }
}

Otherwise you could rewrite the code to use static variables.

0
On

I recommend you persist the state of your app using onSavedInstanceState() upon configuration changes because when you start your app, onCreate() is called once until there is configuration change: and each fragment's lifecycle depends on the activity that starts them, hence, you need to check for nullability of savedInstanceState in the appropriate activities and fragments such that logics inside onCreate() for activity and onCreateView() for fragment be defined for both when savedInstanceState is null and not null. By so doing, if your app should trigger onCreate() and onCreateView() after once, the nullability of the saved state will determine the logic to run