Search code examples
javaandroid-studiooncreateonstart

onCreate() method is not calling method A but onStart() calls method A


I have an onCreate() method that looks something like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);        
    
    if (blah) {
        blahblah;
    } else {
        method1();
    }

    MethodA();

}

An onActivityResult method that looks something like this:

@Override
protected void onActivityResult(int a, int b, Intent c) {
    super.onActivityResult(b, a, c);
    if (b == blah) {
        if (a == blah) {
            Method1();
        }
    }
}

Method1():

public void Method1() {
    blah
}

I have a methodA() which is supposed to appear first time (at the moment it doesnt appear, unless I put methodA() in onStart() - then only it appears on its second attempt at opening the app

public void MethodA() {
   sets text on screen
   
}









 

Solution

  • From my knowledge in Android it should have been called. From the information you have given there is limited debugging and searching for mistakes I can do, but I'd like to know how you are checking whether your function is or is not being called.

    • From what I read, you are only trusting on visual feedback to verify whether your function is being called.

    I would not want that, especially since in a specific case of yours, you tell it does appear after two launches.

    Try using Logcat (integrated by default in Android Studio, not a plugin) to check whether the function is or isn't being called. Start by verifying whether onCreate is called on launch (which should be the case in my experience).

    On top of your class write the static member variable (if you write "logt" and press tab, it creates itself automatically):

    private static final String TAG = "ActivityName";
    

    In the OnCreate method write (if you write "logd" and press tab, it creates itself automatically):

    log.d(TAG, "I am printing from the OnCreate method");
    

    In Logcat you will be able to filter on your debugTagName.

    https://developer.android.com/studio/debug/am-logcat

    If this is not the issue, verify if you are working with fragments or activity. In containers the OnCreate method might be called earlier for fragments (when they are not on the screen). This should not cause any issues, but it might when items are programatically moved or removed from another fragment.