When I run the code, a sign in dialog box pop up to ask for credentials again, as illustrated in attachment. The layer is added in even I ignore the dialog box by clicking at the "cancel" button.
Does anyone knows what is happening? and how to solve this problem (no dialog box pop up)?
p/s: The code runs well if I add feature layer, meaning that no dialog box pop up.
We would need more info about your code. The blog post you reference doesn't define any sign in dialog, so it's difficult to help you out about this sign in dialog which is likely defined in your code.