简体   繁体   中英

MainActivity onCreate running twice

I am trying to debug my application, which seems to be running the onCreate method for MainActivity, twice.

I put in a Log.i() command and sure enough, it appears twice in Logcat.

What could be the cause of this?

Here is my onCreate code:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Log.i(TAG, "Starting..."); // this appear twice in logcat

    // Set activity view
    setContentView(R.layout.activity_main);

    // Initialise buttons
    Button loginBtn = (Button) findViewById(R.id.login);

    // Initialise text inputs
    screen = (EditText)findViewById(R.id.screen);
    pw = (EditText)findViewById(R.id.pw);

    final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    String storedScreenCode = sharedPreferences.getString("storedScreenCode", null);
    String storedScreenPassword = sharedPreferences.getString("storedScreenPassword", null);

    domain = sharedPreferences.getString("apiUrl", null);

    final String lastUpdated = sharedPreferences.getString("lastUpdated", null);

    if(storedScreenCode != null) {
        String url = domain + getResources().getString(R.string.api_login_url) + storedScreenCode + "/" + storedScreenPassword;

        try {
            status = new NetworkChecker(getApplicationContext()).execute().get(4, TimeUnit.SECONDS);
            Log.i(TAG, status.toString());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        }

        if(status) {
            try {
                String loginResult = new ReadJSONFeedTask().execute(url).get(4, TimeUnit.SECONDS);
                JSONObject loginJson = new JSONObject(loginResult);

                if(loginJson.getInt("success") == 1) {

                        Intent i = new Intent(getApplicationContext(), NextActivity.class);
                        startActivity(i);

                } else {

                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }
    }

    loginBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View view) {

            if (isEmpty(screen) && isEmpty(pw)) {
                screen.setError("Screen Code is required!");
                pw.setError("Password is required!");
            } else {
                WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

                ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

                if(!wifi.isWifiEnabled()) {
                    Toast.makeText(getBaseContext(), "Wifi is not enabled.", Toast.LENGTH_LONG).show();
                    startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                } else if(!mWifi.isConnected()) {
                    Toast.makeText(getBaseContext(), "Wifi is not connected.", Toast.LENGTH_LONG).show();
                    startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                } else {

                    //String domain = sharedPreferences.getString("apiUrl", null);

                    String url = domain + getResources().getString(R.string.api_login_url) + screen.getText().toString() + "/" + pw.getText().toString();
                    Log.i(TAG, "API Login URL: " + url);

                    try {
                        status = new NetworkChecker(getApplicationContext()).execute().get();
                        Log.i(TAG, "Status: " + status);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }

                    if(status) {
                        try {
                            String loginResult = new ReadJSONFeedTask().execute(url).get();
                            JSONObject loginJson = new JSONObject(loginResult);

                            // check success boolean
                            if(loginJson.getInt("success") == 1) { // if success equals 1, carry on with activity

                                    Intent i = new Intent(getApplicationContext(), NextActivity.class);
                                    startActivity(i);
                            } else {
                                // if success equals 0, show toast
                                Toast.makeText(getBaseContext(), loginJson.getString("message") , Toast.LENGTH_LONG).show();
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Toast.makeText(getBaseContext(), "No Connectivity", Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
    });
  }

I split this up a bit, putting the main chunk of it into onStart(). I then put a log message in onCreate and onStart, put break points on and ran as debug. Android Studio picked up the breakpoints, first the log message in onCreate, then the one in onStart, THEN it went back to onCreate and again to onStart.

So something is definitely calling onCreate twice (or the whole activity?)

You use getApplicationContext() and getBaseContext() a couple of times in cases where you should use this or YourActivity.this instead. This might cause memory leaks under certain circumstances. This should have been a comment but I don't have enough rep. So sorry...

It usually happens when you change orientation in your activity such as:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

instead of this set orientation in manifest:

<activity android:name=".YourActivity" android:screenOrientation="landscape"/>

good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM