Umar zzstu Syed
Umar zzstu Syed

Reputation: 13

How to switch and save between activities? (Kotlin)

I have 2 activities (activities 1 and 2 for clarity), 1 displays editTexts, and 2 transfers those editTexts into viewTexts. When the user first opens the app, I want them to see activity 1, but when they click the button that moves to activity 2, I want the app to be locked into that activity, and should they restart the app it should open on 2. However, if they click a button in activity 2, then it should move back to activity 1 and stay there. I've tried using a boolean statement for the checks, and then updating the sharedPreferences with an onClick listeners, but it keeps going to activity 2 or crashing.

How would I go about this? Thanks.

This is the code but it does not work.

 var firstTime : Boolean = appSettingPrefs.getBoolean("FirstInstall", false)

    if (firstTime){
        var i = Intent(this , ViewActivity::class.java)
        startActivity(i)
    }else {
        sharedPrefsEdit.putBoolean("FirstInstall", true)
        sharedPrefsEdit.apply()
    }

Upvotes: 0

Views: 1154

Answers (1)

GaneshHulyal
GaneshHulyal

Reputation: 126

Let's assume this as user needs to login first when he opens the app for the first time and for the second time he should see his profile, after clicking logout button login screen should be visible.

var isLoggedIn : Boolean = appSettingPrefs.getBoolean("isLoggedIn", false)
if(firstTime){
   var i = Intent(this , ProfileActivity::class.java)
   startActivity(i)
}
else{
    showLoginScreen()
   //in your case show edittext that your are trying to read values.
}

When the user clicks on LoginButton change SharedPrefs to true and move user to next activity(ViewActivity).

showLoginScreen(){
  //Read values from the EditText and save them to use in next screen.
  loginButton.setOnClickListener{
     sharedPrefsEdit.putBoolean("isLoggedIn", true)
     sharedPrefsEdit.apply()
     var i = Intent(this , ProfileActivity::class.java)
     startActivity(i)
  }
}

In profile activity when the user clicks on logout button login screen should be visible, this can be done like this.

logout.setOnClickListener {
   sharedPrefsEdit.putBoolean("isLoggedIn", false)
   sharedPrefsEdit.apply()
   var i = Intent(this , LoginActivity::class.java)
   startActivity(i)   
}

And flow goes this way,

When user opens the app, first check the value of isLoggedIn if it is true then directly take the user to next screen(ScreenTwo).

If isLoggedIn is false then show LoginScreen(ScreenOne) to the user, when the user click on login button then make isLoggedIn true and move him to ProfileActivity(SecondActivity).

If you have any doubts, let me know in the comments.

Upvotes: 1

Related Questions