Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
native Android login, in Kotlin
package com.example.ozturkse.awesomelogin
import android.content.Context
import android.support.v7.app.AppCompatActivity
class LoginUtil {
private val EMAIL = "email_shared_pref"
private val PASSWORD = "password_shared_pref"
private val LOGIN_PREFS_FILENAME = "Login"
fun isLoginInfoCorrect(context: Context, email: String, password: String): Boolean {
val (savedEmail, savedPassword) = getSavedLoginInfo(context)
if (email == savedEmail && password == savedPassword) {
return true
}
return false
}
fun saveLoginInfo(context: Context, email: String, password: String) {
val sharedPrefs = context.getSharedPreferences(LOGIN_PREFS_FILENAME, Context.MODE_PRIVATE)
val editor = sharedPrefs.edit()
editor.putString(EMAIL, email)
editor.putString(PASSWORD, password)
editor.apply()
}
data class LoginInfo(val email: String?, val password: String?)
fun getSavedLoginInfo(context: Context): LoginInfo {
val sharedPrefs = context.getSharedPreferences(LOGIN_PREFS_FILENAME, Context.MODE_PRIVATE)
val savedEmail = sharedPrefs.getString(EMAIL, null)
val savedPassword = sharedPrefs.getString(PASSWORD, null)
return LoginInfo(savedEmail, savedPassword)
}
fun clearLoginInfo(context: Context) {
val sharedPrefs = context.getSharedPreferences(LOGIN_PREFS_FILENAME, Context.MODE_PRIVATE)
val editor = sharedPrefs.edit()
editor.clear()
editor.apply()
}
}
package com.example.ozturkse.awesomelogin
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.content.Intent
import android.support.v4.content.ContextCompat
import android.view.View
import android.widget.TextView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val email = intent.getStringExtra(EMAIL_INTENT_KEY)
val password = intent.getStringExtra(PASSWORD_INTENT_KEY)
main_textview_email.text = email
main_textview_password.text = password
// notify login
val toast = Toast.makeText(this@MainActivity, R.string.login_successful, Toast.LENGTH_SHORT)
toast.show()
}
fun logout(view: View) {
val loginUtil = LoginUtil()
loginUtil.clearLoginInfo(this@MainActivity)
startActivity(SignInActivity.newIntent(this))
}
companion object {
private val EMAIL_INTENT_KEY = "email_intent"
private val PASSWORD_INTENT_KEY = "password_intent"
fun newIntent(context: Context, email: String, password: String): Intent {
val intent = Intent(context, MainActivity::class.java)
intent.putExtra(EMAIL_INTENT_KEY, email)
intent.putExtra(PASSWORD_INTENT_KEY, password)
return intent
}
}
}
package com.example.ozturkse.awesomelogin
import android.app.Application
import android.content.Context
import android.content.Intent
import android.os.AsyncTask
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_sign_in.*
/**
* A login screen that offers login via email/password.
*/
class SignInActivity : AppCompatActivity() {
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private var authTask: UserLoginTask? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sign_in)
val loginUtil = LoginUtil()
val (savedEmail, savedPassword) = loginUtil.getSavedLoginInfo(this@SignInActivity)
// log in if username and password matches
if (savedPassword != null && savedEmail != null) {
startActivity(MainActivity.newIntent(this@SignInActivity, savedEmail, savedPassword))
}
signin_edittext_password.setOnEditorActionListener(TextView.OnEditorActionListener { _, id, _ ->
if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
attemptLogin()
return@OnEditorActionListener true
}
false
})
sign_in_button.setOnClickListener { attemptLogin() }
sign_in_create_account_button.setOnClickListener { startActivity(SignUpActivity.newIntent(this)) }
}
// cancel login on stop
override fun onStop() {
super.onStop()
authTask?.cancel(true)
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private fun attemptLogin() {
if (authTask != null) {
return
}
// Reset errors.
signin_edittext_email.error = null
signin_edittext_password.error = null
val email = signin_edittext_email.text.toString()
val password = signin_edittext_password.text.toString()
var cancel = false
var focusView: View? = null
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
signin_edittext_email.error = getString(R.string.error_field_required)
focusView = signin_edittext_email
cancel = true
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView?.requestFocus()
} else {
authTask = UserLoginTask(email, password)
authTask!!.execute(null as Void?)
}
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
inner class UserLoginTask internal constructor(private val email: String, private val password: String) : AsyncTask<Void, Void, Boolean>() {
override fun doInBackground(vararg params: Void): Boolean? {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(1000)
val loginUtil = LoginUtil()
return loginUtil.isLoginInfoCorrect(this@SignInActivity, email, password)
} catch (e: InterruptedException) {
return false
}
}
override fun onPostExecute(success: Boolean?) {
authTask = null
if (success!!) {
finish()
startActivity(MainActivity.newIntent(this@SignInActivity, email, password))
} else {
signin_edittext_password.error = getString(R.string.error_login)
}
}
override fun onCancelled() {
authTask = null
}
}
companion object {
fun newIntent(context: Context): Intent {
val intent = Intent(context, SignInActivity::class.java)
return intent
}
}
}
package com.example.ozturkse.awesomelogin
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_sign_up.*
import android.content.Context
import android.content.Intent
class SignUpActivity : AppCompatActivity() {
private val minPasswordLength = 4
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sign_up)
signup_edittext_confirm_password.setOnEditorActionListener(TextView.OnEditorActionListener { _, id, _ ->
if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
attemptLogin()
return@OnEditorActionListener true
}
false
})
sign_up_button.setOnClickListener { attemptLogin() }
signup_login_button.setOnClickListener{startActivity(SignInActivity.newIntent(this))}
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private fun attemptLogin() {
// Reset errors.
signup_edittext_email.error = null
signup_edittext_password.error = null
signup_edittext_confirm_password.error = null
// Store values at the time of the login attempt.
val email = signup_edittext_email.text.toString()
val password = signup_edittext_password.text.toString()
val confirmPassword = signup_edittext_confirm_password.text.toString()
var cancel = false
var focusView: View? = null
if (password != confirmPassword) {
signup_edittext_password.error = getString(R.string.error_password_unmatch)
focusView = signup_edittext_password
cancel = true
}
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
signup_edittext_password.error = getString(R.string.error_invalid_password)
focusView = signup_edittext_password
cancel = true
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
signup_edittext_email.error = getString(R.string.error_field_required)
focusView = signup_edittext_email
cancel = true
} else if (!isEmailValid(email)) {
signup_edittext_email.error = getString(R.string.error_invalid_email)
focusView = signup_edittext_email
cancel = true
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView?.requestFocus()
} else {
// login successful
val loginUtil = LoginUtil()
loginUtil.saveLoginInfo(this@SignUpActivity,email,password)
startActivity(MainActivity.newIntent(this, email, password))
}
}
private fun isEmailValid(email: String): Boolean {
return email.contains("@")
}
private fun isPasswordValid(password: String): Boolean {
return password.length > minPasswordLength
}
companion object {
fun newIntent(context: Context): Intent {
val intent = Intent(context, SignUpActivity::class.java)
return intent
}
}
}
package com.example.ozturkse.awesomelogin
import android.app.Application
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
class SplashActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Start home activity
startActivity(Intent(this@SplashActivity, SignInActivity::class.java))
// close splash activity
finish()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.