Skip to content

The specified child already has a parent (when dynamically creating Frame & Page) #6931

Open

Description

@webleaf

Environment

  • CLI: 5.2.0
  • Cross-platform modules: 5.2.1
  • Android Runtime: 5.2.1

Describe the bug
Related with #6312 #6201 #6339

System.err: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
System.err: 	at android.view.ViewGroup.addViewInner(ViewGroup.java:4658)
System.err: 	at android.view.ViewGroup.addView(ViewGroup.java:4499)
System.err: 	at android.view.ViewGroup.addView(ViewGroup.java:4439)
System.err: 	at android.view.ViewGroup.addView(ViewGroup.java:4412)
System.err: 	at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1466)
System.err: 	at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
System.err: 	at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
System.err: 	at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802)
System.err: 	at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
System.err: 	at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
System.err: 	at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
System.err: 	at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
System.err: 	at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
System.err: 	at android.os.Handler.handleCallback(Handler.java:751)
System.err: 	at android.os.Handler.dispatchMessage(Handler.java:95)
System.err: 	at android.os.Looper.loop(Looper.java:154)
System.err: 	at android.app.ActivityThread.main(ActivityThread.java:6776)
System.err: 	at java.lang.reflect.Method.invoke(Native Method)
System.err: 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
System.err: 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

To Reproduce
After app is opened press Back button to "close" app. Then run (resume) app again by pressing app icon.

Sample project

import * as app from "tns-core-modules/application";
import {parse} from "tns-core-modules/ui/builder";
import {StackLayout} from "tns-core-modules/ui/layouts/stack-layout";
import {Page} from "tns-core-modules/ui/page";
import {Frame} from "tns-core-modules/ui/frame";

const rootLayoutXml = `<StackLayout><Frame id="rootLayoutFrame"/></StackLayout>`;
const rootLayoutView = <StackLayout>parse(rootLayoutXml);

const pageXml = `<Page><StackLayout><Label text="Text"/></StackLayout></Page>`;
const pageView = <Page>parse(pageXml);

const rootLayoutFrame = <Frame>rootLayoutView.getViewById("rootLayoutFrame");

app.run({
    create: () => {

        rootLayoutFrame.navigate({
            create: () => pageView
        });

        return rootLayoutView;
    }
});

Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

Activity

  1. changed the title [-]The specified child already has a parent. You must call removeView() on the child's parent first.[/-] [+]The specified child already has a parent (when dynamically creating Frame & Page)[/+] on Feb 20, 2019
  2. NickIliev commented on Feb 20, 2019

    @NickIliev
    Contributor

    @webleaf move the page creation inside the inner create

    const rootLayoutXml = `<Frame id="rootLayoutFrame"/>`;
    const rootLayoutView = parse(rootLayoutXml);
    
    const pageXml = `<Page><StackLayout><Label text="NAMEEEEEE"/></StackLayout></Page>`;
    const rootLayoutFrame = <Frame>rootLayoutView.getViewById("rootLayoutFrame");
    
    app.run({
        create: () => {
    
            rootLayoutFrame.navigate({
                create: () => { 
                    const pageView = <Page>parse(pageXml);
                    return pageView;
                }
            });
    
            return rootLayoutView;
        }
    });

    In that line of thoughts, you should probably also do the same for your Frame (not tested on my side but do it to avoid similar issue when navigating)

    const rootLayoutXml = `<Frame id="rootLayoutFrame"/>`;
    const pageXml = `<Page><StackLayout><Label text="NAMEEEEEE"/></StackLayout></Page>`;
    
    app.run({
        create: () => {
            const rootLayoutView = parse(rootLayoutXml);
            const rootLayoutFrame = <Frame>rootLayoutView.getViewById("rootLayoutFrame");
    
            rootLayoutFrame.navigate({
                create: () => { 
                    const pageView = <Page>parse(pageXml);
                    return pageView;
                }
            });
    
            return rootLayoutView;
        }
    });
  3. webleaf commented on Feb 20, 2019

    @webleaf
    Author

    @NickIliev I don't like idea to parse View on every navigate. That's why I use "singleton" (once) parsed Views. Also that's why I don't use xml view's. Looks like NS parse XML on every navigate. It's overhead and works slow.

    Sample project was done to reproduce the issue. Of course my project is more complex. And there was not such issue until 5.2.0
    And I can't rewrite all as you recommend, first of all because it was done to avoid parsing xml on every navigate.

  4. webleaf commented on Feb 20, 2019

    @webleaf
    Author

    @NickIliev I found some workaround, but I think it does not solve the issue. Workaround looks so:

    app.run({
        create: () => {
    
            if (!rootLayoutFrame.currentPage) { // <--- workaround
                rootLayoutFrame.navigate({
                    create: () => {
                        return page1View
                    }
                });
            }
    
            return rootLayoutView;
        }
    });
    

    Now we can suspend app via Back button and when we reopen it again error don't appear.
    But it produce other issue. After such app reopening topmost() call become return undefined, so such error could be produced:

    System.err: TypeError: Cannot read property 'navigate' of undefined
    

    Other question is Why after suspending app via Back button and reopening it again launchEvent raises before resumeEvent? On this launchEvent create: () => View (of app.run()) function is called and it is one of the reason of this issue. Only resumeEvent should raise in such case.
    To illustrate described problems I've created this snippet (just copy/past to your app.ts):

    import * as app from "tns-core-modules/application";
    import {parse} from "tns-core-modules/ui/builder";
    import {StackLayout} from "tns-core-modules/ui/layouts/stack-layout";
    import {Observable, Page} from "tns-core-modules/ui/page";
    import {Frame, topmost} from "tns-core-modules/ui/frame";
    
    const rootLayoutXml = `<StackLayout><Frame id="rootLayoutFrame"/></StackLayout>`;
    const rootLayoutView = <StackLayout>parse(rootLayoutXml);
    
    const page1Xml = `<Page><StackLayout><Button text="to Page2" tap="{{ onTap }}"/></StackLayout></Page>`;
    const page1View = <Page>parse(page1Xml);
    
    const page2Xml = `<Page><StackLayout><Label text="Page2"/></StackLayout></Page>`;
    const page2View = <Page>parse(page2Xml);
    
    const rootLayoutFrame = <Frame>rootLayoutView.getViewById("rootLayoutFrame");
    
    app.on(app.launchEvent, (args: app.LaunchEventData) => {
        console.log('Application onLaunchEvent...');
    });
    
    app.on(app.suspendEvent, (args) => {
        console.log('Application onSuspendEvent...');
    });
    
    app.on(app.resumeEvent, (args: app.ApplicationEventData) => {
        console.log('Application onResumeEvent...');
    });
    
    page1View.bindingContext = new class extends Observable {
        onTap() {
    
            // topmost() return undefined after suspending on Back button and reopening app
            // so using rootLayoutFrame directly could be workaround
            // but looks like it is not normal that topmost() return undefined
    
            topmost().navigate({
                create: () => page2View
            })
        }
    };
    
    app.run({
    
        // after suspending on Back button and reopening app launchEvent fires before resumeEvent
        // and create() function execute again
        // looks like it's not normal that launchEvent can be fired after suspendEvent and before resumeEvent
    
        create: () => {
    
            console.log("app.run create: () =>", rootLayoutView);
    
            if (!rootLayoutFrame.currentPage) {
                rootLayoutFrame.navigate({
                    create: () => {
                        return page1View
                    }
                });
            }
    
            return rootLayoutView;
        }
    });
    

    @manoldonev please, could you check this?

  5. NickIliev commented on Feb 22, 2019

    @NickIliev
    Contributor

    @webleaf regarding Why after suspending app via Back button and reopening it again launchEvent raises before `resumeEvent

    NativeScript is not chaning the way the activity lifecycles are working. You can test it with the native ActivityLifecycles and observe that again the 'onResume' event is triggered after onCreate and onStart - refer to the diagram in this documentation article. Here is a Playground app that demonstrates both the NativeScript lifecycle events and the native Android activity lifecycle events.

    Logs from the Playgrond app (downloaded locally so we could observe the initial start events)

    Hit the back button to exit the app
    JS: }}}}}}}} activityStopedEvent // onStop()
    JS: >>>>>>>>>>>>>>>>> NativeScript's EXIT EVENT >>>
    
    Return to the app
    JS: }}}}}}}} activityCreatedEvent // onCreate()
    JS: >>>>>>>>>>>>>>>>> NativeScript's LAUNCH EVENT >>>
    JS: }}}}}}}} activityStartedEvent // onStart()
    JS: }}}}}}}} activityResumedEvent // onResume()
    JS: >>>>>>>>>>>>>>>>> NativeScript's RESUME EVENT
    

    Hitting the hardware back (with no navigation stack in your current frame) will exit the app thus triggering the suspend event. then on returning to the app the launch event will be fired and finally the resume event.

    Regarding the workaround with 'currentPage' and the navigation error.

    You need to recreate the NativeScript entries (Page, Frame, etc) and this is the way NativeScript works.
    In your workaround you are guarding the first error but that won't do the job as the Frame (which you are using for the safety check) again needs to be recreated so it could have all the events, lifecycles, etc. to be reattached. The error Cannot read property 'navigate' of undefined shows that the frame reference is no longer valid as it was not recreated during the application start.

    Parsing the XML is not a big overhead - even in pretty complex UI we are talking about milliseconds and again this is the way NativeSript works when you have are creating XML files for your UI (with XML files or through XML strings and ui/builder).

  6. webleaf commented on Feb 22, 2019

    @webleaf
    Author

    In your workaround you are guarding the first error but that won't do the job as the Frame (which you are using for the safe check) again needs to be recreted so it could have all the events, lifecycles, etc. to be reattached.

    But it works. Since I already have a reference to the Frame created on the first app start (rootLayoutFrame). So if I do rootLayoutFrame.navigate() it works and I don't need recreate it.
    Just topmost() don't work in such case (it's not big problem, but maybe this indicates that topmost() don't work correctly).

    NavigationEntry create: () => {} function should return View. It happens (no matter when it was created). Everything else is a sign of NS architectural problems in this place. But you are trying to convince me that it should be so.

  7. NickIliev commented on Feb 22, 2019

    @NickIliev
    Contributor

    @webleaf Can you let me know if you are experiencing the same issue if you try to access the frame via getFrameById instead with topmost

  8. webleaf commented on Feb 22, 2019

    @webleaf
    Author

    @NickIliev getFrameById don't work too in such case.

  9. itsmerockingagain commented on Apr 26, 2021

    @itsmerockingagain

    I am also facing same issue, is there any workaround for this issue?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions