Home > Software engineering >  How to make the initial settings screen, which will appear only when the application is first launch
How to make the initial settings screen, which will appear only when the application is first launch

Time:02-18

I want that when the user has installed the application, he can accept the terms and conditions by clicking on the accept button. But this should only happen once when the user first starts the application. I use kotlin

I try this, but not work

class tutorial: AppCompatActivity() {
    private var pref: SharedPreferences = getSharedPreferences("mypref", MODE_PRIVATE)
    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
        setContentView(R.layout.tutorial_main)
        if (pref.getBoolean("firstTime", false)) {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
        }
    }
}

CodePudding user response:

  1. You are defaulting to false when the preference value has never been set, so it will always be false. You want it to be considered true when the app is opened the first time.

  2. You are failing to ever change the value of the preference, so even after you fix the default to be true, it will never change to false.

  3. You should show your terms and conditions when it's the first time, and directly open the main activity when it's not the first time. You have the logic flipped.

You need to set a default of true, and you need to persist a value of false:

class tutorial: AppCompatActivity() {

    private var pref: SharedPreferences = getSharedPreferences("mypref", MODE_PRIVATE)

    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
        setContentView(R.layout.tutorial_main)
        if (pref.getBoolean("firstTime", true)) { // use default of true
            pref.edit { putBoolean("firstTime", false) } // persist value of false
            // show T&C dialog that calls goToMain() when accepted
        } else {
            goToMain()
        }
    }

    private fun goToMain() {
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        finish() // close this activity since we don't want it in back stack
    }
}

By the way, class names by convention should always begin with a capital letter. It will make your code easier to read and understand.

  • Related