LoginSignup
5
5

More than 3 years have passed since last update.

Androidアプリ(Kotlin)で、FirebaseAuthenticationを利用したログイン方法

Posted at

Androidアプリ(Kotlin)で、FirebaseAuthenticationを利用したログイン方法

FirebaseAuthenticationを利用したログイン画面を作成したので、その備忘録
メールアドレスによるログインを利用した。

※前提条件として、すでにFirebaseのライブラリーは入っているものとする。

画面構成

メールアドレスとパスワードの入力欄とログインと新規登録のボタンを設置した。
Screenshot_20190722-094612.png

画面構成ソース

activity_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".activity.MenuActivity">

    <LinearLayout
            android:orientation="vertical"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            android:layout_marginStart="8dp" android:layout_marginEnd="8dp" android:layout_marginTop="8dp"
            app:layout_constraintTop_toTopOf="parent">
        <Space
                android:layout_width="match_parent"
                android:layout_height="24dp"/>
        <Button
                android:text="主催者"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" android:id="@+id/ownbutton" android:textSize="24sp"
                android:background="@drawable/button_primary" android:textColor="@color/colorW"/>
        <Space
                android:layout_width="match_parent"
                android:layout_height="64dp"/>
        <Button
                android:text="参加者"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" android:id="@+id/userbutton" android:textSize="24sp"
                android:background="@drawable/button_primary" android:textColor="@color/colorW"/>
        <Space
                android:layout_width="match_parent"
                android:layout_height="24dp"/>
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

処理について

ログインボタンを押下すると、入力されたテキストからログインの処理をする仕組み。
ログインが成功すると別画面に遷移

ソース全文

MainActivity.kt

package jp.dip.hirotann.appointmentdesk.activity

import android.app.AlertDialog
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import com.google.firebase.auth.FirebaseAuth
import jp.dip.hirotann.appointmentdesk.R
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() ,View.OnClickListener {

    //FirebaseAuthの宣言
    private var auth: FirebaseAuth? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //Firebase Auth の初期化
        this.auth = FirebaseAuth.getInstance()

        //プログレシブバーの処理
        progressBar.visibility = View.INVISIBLE

        val button: Button = findViewById(R.id.registrationbutton) as Button
        button.setOnClickListener(this)

        var newbutton : Button = findViewById(R.id.newbutton) as Button
        newbutton.setOnClickListener {
            val intent = Intent(application, NewActivity::class.java)
            startActivity(intent)
        }
    }

    //ログインボタンを押下した時の処理
    override fun onClick(v: View?) {

        //プログレシブバーの処理
        progressBar.visibility = View.VISIBLE

        var email =  findViewById(R.id.emailText) as EditText
        var password = findViewById(R.id.passwordText) as EditText

        if( email.text.isEmpty() || password.text.isEmpty() ){
            AlertDialog.Builder(this)
                .setTitle("入力エラー")
                .setMessage("メールアドレスまたはパスワードを入力してください。")
                .setPositiveButton("ok"){ dialog, which ->
                    progressBar.visibility = View.INVISIBLE
                }.show()
            return
        }

        this.signIn(email.text.toString(),password.text.toString())
    }

    //ログイン処理
    private fun signIn(email: String, password: String) {

        //Firebaseを利用したログイン
        this.auth?.signInWithEmailAndPassword(email, password)
            ?.addOnCompleteListener(this) { task ->
                //ログインが成功したら次の画面へ
                if (task.isSuccessful) {
                    progressBar.visibility = View.INVISIBLE
                    val intent = Intent(application, MenuActivity::class.java)
                    startActivity(intent)
                } else {
                    //ログインに失敗したらメッセージ
                    AlertDialog.Builder(this)
                        .setTitle("ログインに失敗")
                        .setMessage("メールアドレスとパスワードを確認してください。")
                        .setPositiveButton("ok"){ dialog, which ->
                            //プログレシブバーの処理
                            progressBar.visibility = View.INVISIBLE
                        }.show()
                }
            }
    }

}

解説

FirebaseAuth を利用する為に、宣言を行う。
これがうまくいかない場合は、ライブラリーが入ってないかも

//FirebaseAuthの宣言
    private var auth: FirebaseAuth? = null

ログインの処理
this.auth?.signInWithEmailAndPassword(email, password)でログインの処理が出来て、
そのあとにaddOnCompleteListener(this)処理成功時にどうするかを書いている。

下記の場合は、成功したら次の画面へ失敗ならメッセージを表示している。

 //ログイン処理
    private fun signIn(email: String, password: String) {

        //Firebaseを利用したログイン
        this.auth?.signInWithEmailAndPassword(email, password)
            ?.addOnCompleteListener(this) { task ->
                //ログインが成功したら次の画面へ
                if (task.isSuccessful) {
                    progressBar.visibility = View.INVISIBLE
                    val intent = Intent(application, MenuActivity::class.java)
                    startActivity(intent)
                } else {
                    //ログインに失敗したらメッセージ
                    AlertDialog.Builder(this)
                        .setTitle("ログインに失敗")
                        .setMessage("メールアドレスとパスワードを確認してください。")
                        .setPositiveButton("ok"){ dialog, which ->
                            //プログレシブバーの処理
                            progressBar.visibility = View.INVISIBLE
                        }.show()
                }
            }
    }

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5