0

I'm still new to Kotlin and Android and developing a project that uses shared preferences.

I have multiple Activities and a user must be logged in to use all functions of the Main Activity.

The Main Acitivity has a menu drawer with few menu items. The first one is redirecting user to Login Activity. The rest of the menu items are hidden until user is logged in.

The process is as follows: Start with Main Activity -> The application checks if the user is logged in -> If not you must log in -> Go to Login Activity -> Logging in -> Then go back to Main Activity.

However, the main activity does not refresh at all. I mean, I don't even know how to do it. I want my main activity to refresh when I return from login activity.

So far, it only works when I close the app and reopen it. The session is likely cached in Shared preferences.

I tried to start and finish Activites by clicking certain buttons (eg After clicking login button when user passed all credentials) but it didn't work.

The following code checks that the user is logged in when the main activity starts

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        val menu: Menu = navView.menu
        val target2: MenuItem = menu.findItem(R.id.miItem2)
        val target3: MenuItem = menu.findItem(R.id.miItem3)
        
        //region user session
        try{
            if(!SharedPrefManager.getInstance(this)!!.isLoggedIn()){
                target2.isVisible = false
                target3.isVisible = false
                Toast.makeText(applicationContext, "nie zalogowany", Toast.LENGTH_LONG).show()
            }
            else{
                target2.isVisible = true
                target3.isVisible = true
                Toast.makeText(applicationContext, "zalogowany", Toast.LENGTH_LONG).show()
            }
        }catch (e: NullPointerException){

        }
//endregion

And there is function isLoggedIn():

    fun isLoggedIn(): Boolean{
        val sharedPreferences: SharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE)
        if(sharedPreferences.getString(KEY_USER_EMAIL, null) != null){
            return true

        }
            return false
    }

This code below takes me to the Login Activity

val btnLogInActivity : Button = findViewById(R.id.logButton)

        btnLogInActivity.setOnClickListener {
            val intent = Intent(this, LoginActivity::class.java)
            startActivity(intent)
        }

And this is the code in Login Activity (userLogin function is not important in this context):

buttonLogin.setOnClickListener {
            userLogin()
            newMainActivity()
        }


    private fun newMainActivity(){
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
    }

Ps. If you need more code to fix the problem, let me know

litseba
  • 7
  • 4
  • the code that takes your to log in activity and the code that takes you to MainActivity please. – MehranB Jan 24 '21 at 22:08
  • @MehranB I updated post with new code lines. I thought about adding pause and resume to the Main Activity while moving to Login Activity instead of startActivity() – litseba Jan 24 '21 at 22:50
  • `startActivityForResult(intent)` might be what you're looking for. – Martin Zeitler Jan 25 '21 at 03:57
  • It’s not a good practice to refresh an activity either via finish() or recreate() just for making some changes via sharedPreferences. I agree with @MartinZeitler & you should using startActivityForResult or the newer api if you are on AndroidX as startActivityForResult is deprecated now. – Darshan Jan 25 '21 at 05:34
  • @DarShan That's not true; [`startActivityForResult()`](https://developer.android.com/reference/android/app/Activity#startActivityForResult(android.content.Intent,%20int)) is not deprecated... only `startActivityFromChild()` had recently been deprecated. It's rather that with AndroidX navigation component, these have no use. – Martin Zeitler Jan 25 '21 at 05:47
  • @MartinZeitler “AndroidX” - https://stackoverflow.com/questions/62671106/onactivityresult-method-is-deprecated-what-is-the-alternative – Darshan Jan 25 '21 at 05:51
  • @DarShan Only on `Fragment` - not on `Activity`... while this is probably just another one of these questionable design-changes, which are recently being pushed (not all of them make much sense). I mean, while the `Fragment` `isAdded()`, one can still use the `Activity`. – Martin Zeitler Jan 25 '21 at 05:53
  • @MartinZeitler I guess I just missed that part – Darshan Jan 25 '21 at 05:55
  • There's also [`SharedPreferences.OnSharedPreferenceChangeListener`](https://developer.android.com/reference/android/content/SharedPreferences.OnSharedPreferenceChangeListener#onSharedPreferenceChanged(android.content.SharedPreferences,%20java.lang.String))... which appears to invalidate the whole concept of needing to mess around alike that. – Martin Zeitler Jan 25 '21 at 06:08
  • @MartinZeitler I used `onResume()` function and it worked as I wanted because I don't want Main Activity to finish. But you gave me a hint for another problem I have with my project – litseba Jan 25 '21 at 11:06

1 Answers1

0

You just have to add finish() in your code. Update your methods with the code below:

        btnLogInActivity.setOnClickListener {
            val intent = Intent(this, LoginActivity::class.java)
            startActivity(intent)
            finish()
        }

And after login:

    private fun newMainActivity(){
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        finish()
    }
  • I've tried it before creating this post but it didn't work. Also I don't want MainActivity to finish when I go to Login Activity so I used `onResume()` function. And it worked. – litseba Jan 25 '21 at 11:08