• 8
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

startActivity : Which is better method and Why?

Ok, Let's make this simple.

I've two ways to start an activity other than default startActivity

One : Using a static start method

class LogInActivity : BaseAppCompatActivity() {
    // other activity code goes here
    companion object {
        fun start(context: Context /*,extra params goes here*/) {
            val intent = Intent(context, LogInActivity::class.java)
            // intent.putExtra extra params
            context.startActivity(intent)
        }
    }

}

Two : Using a static getStartIntent() method to get the Intent needed to start the activity

class LogInActivity : BaseAppCompatActivity() {

    companion object {

        fun getStartIntent(context: Context /*,extra params goes here*/) : Intent {
            val intent = Intent(context, LogInActivity::class.java) 
            // intent.putExtra extra params
            return intent
        }
    }
}

Questions:

  1. Which is better method and Why ?

I've seen most resources suggest to use the second method. What could be the reason ?

  1. Is there going to be a memory leak in any of these methods ?
      • 2
    • I see no difference except the code if different in fact. Both methods will execute same commands. Choose whichever you like more
      • 1
    • The advantage of using a newIntent pattern is extensibility beyond what the default function provides. With the former method you can't do anything with the created Intent. With the latter you have more options to modify the Intent in the calling activity.
      • 1
    • IMHO, there is little advantage to user either of these methods compared to inlining the two lines (at least if it is that simple). Feels a bit over-engineered.
    • @Henry Yeah, that's right. This is only useful when we have 2 or more arguments as I mentioned in the code comments.

One is more of a command pattern, while Two is a kind of factory pattern. While both do the same (supposedly), there's one problem with One: it's actually missing the context of the caller. If you need to have a configuration on the Intent, which might depend on the current state or the origin of the call, you'll not be able to apply it. This can be excluding it from the recent activities or disable history or clear the task or anything else.

So better go with Two to be safe and consistent. In any case you're not storing a reference to context, therefore you won't leak it.

  • 1
Reply Report