共有設定を使用したFirebase認証へのログイン登録

SHUBHAM SHEDGE

Firebaseを使用してログイン/登録認証を作成し、DashboardActivityのフルネームやメールアドレスなどの共有設定を使用してデータを入力しました。しかし、問題は、User1が新しいアカウントを作成してログインし、データが正常に入力されたとき...そしてuser2が別の新しいアカウントを作成して再度ログインしたときにデータが正常に入力された...しかし問題は、User1が再度ログインしてダッシュボードアクティビティに移動すると、user2の詳細が表示されることです。

これが私の問題です

これは私のコードです

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/register"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Register"/>
    <Button
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login"/>

</LinearLayout>

MainActivity.java

package com.example.firebaseemailpasswordexample;

import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button registerBtn, loginBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initializeViews();

        registerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
                startActivity(intent);
            }
        });
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });
    }

    private void initializeViews() {
        registerBtn = findViewById(R.id.register);
        loginBtn = findViewById(R.id.login);
    }
}

activity_registration.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".RegistrationActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Register new account" />

    <EditText
        android:id="@+id/fname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Full name" />

    <EditText
        android:id="@+id/email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Email" />

    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Password"
        android:inputType="textPassword" />

    <EditText
        android:id="@+id/mob"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Mobile Number" />

    <Button
        android:id="@+id/register"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Register" />

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone" />

</LinearLayout>

RegistrationActivity.java

package com.example.firebaseemailpasswordexample;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class RegistrationActivity extends AppCompatActivity {

    private EditText emailTV, passwordTV,fname1,mobnumber;
    private Button regBtn;
    private ProgressBar progressBar;

    private FirebaseAuth mAuth;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration);

        mAuth = FirebaseAuth.getInstance();

        initializeUI();

        regBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                registerNewUser();
            }
        });
    }

    private void registerNewUser() {
        progressBar.setVisibility(View.VISIBLE);

        String email, password,firstname,mobnumber1;
        email = emailTV.getText().toString();
        password = passwordTV.getText().toString();
        firstname=fname1.getText().toString();
        mobnumber1=mobnumber.getText().toString();

        SharedPreferences sharedPref = getSharedPreferences("myKey", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString("email", email);
        editor.putString("firstname", firstname);
        editor.apply();

        if (TextUtils.isEmpty(email)) {
            Toast.makeText(getApplicationContext(), "Please enter email...", Toast.LENGTH_LONG).show();
            return;
        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(getApplicationContext(), "Please enter password!", Toast.LENGTH_LONG).show();
            return;
        }

        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            Toast.makeText(getApplicationContext(), "Registration successful!", Toast.LENGTH_LONG).show();
                            progressBar.setVisibility(View.GONE);

                            Intent intent = new Intent(RegistrationActivity.this, LoginActivity.class);
                            startActivity(intent);
                        }
                        else {
                            Toast.makeText(getApplicationContext(), "Registration failed! Please try again later", Toast.LENGTH_LONG).show();
                            progressBar.setVisibility(View.GONE);
                        }
                    }
                });
    }

    private void initializeUI() {
        emailTV = findViewById(R.id.email);
        passwordTV = findViewById(R.id.password);
        fname1=findViewById(R.id.fname);
        mobnumber=findViewById(R.id.mob);
        regBtn = findViewById(R.id.register);
        progressBar = findViewById(R.id.progressBar);
    }
}

activity_login.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".LoginActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Account login"/>
    <EditText
        android:id="@+id/email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Email" />

    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Password"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login" />

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone" />
</LinearLayout>

LoginActivity.java

package com.example.firebaseemailpasswordexample;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class LoginActivity extends AppCompatActivity {

    private EditText emailTV, passwordTV;
    private Button loginBtn;
    private ProgressBar progressBar;

    private FirebaseAuth mAuth;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        mAuth = FirebaseAuth.getInstance();

        initializeUI();

        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginUserAccount();
            }
        });
    }

    private void loginUserAccount() {
        progressBar.setVisibility(View.VISIBLE);

        String email, password;
        email = emailTV.getText().toString();
        password = passwordTV.getText().toString();

        if (TextUtils.isEmpty(email)) {
            Toast.makeText(getApplicationContext(), "Please enter email...", Toast.LENGTH_LONG).show();
            return;
        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(getApplicationContext(), "Please enter password!", Toast.LENGTH_LONG).show();
            return;
        }

        mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            Toast.makeText(getApplicationContext(), "Login successful!", Toast.LENGTH_LONG).show();
                            progressBar.setVisibility(View.GONE);

                            Intent intent = new Intent(LoginActivity.this, DashboardActivity.class);
                            startActivity(intent);
                        }
                        else {
                            Toast.makeText(getApplicationContext(), "Login failed! Please try again later", Toast.LENGTH_LONG).show();
                            progressBar.setVisibility(View.GONE);
                        }
                    }
                });
    }

    private void initializeUI() {
        emailTV = findViewById(R.id.email);
        passwordTV = findViewById(R.id.password);

        loginBtn = findViewById(R.id.login);
        progressBar = findViewById(R.id.progressBar);
    }
}

activity_dashboard.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DashboardActivity">


    <TextView
        android:id="@+id/textView4"
        android:layout_width="370dp"
        android:layout_height="71dp"
        android:layout_marginBottom="43dp"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/textView5"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        tools:ignore="MissingConstraints" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="371dp"
        android:layout_height="80dp"
        android:layout_marginBottom="158dp"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        tools:ignore="MissingConstraints" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="369dp"
        android:layout_height="70dp"
        android:layout_marginTop="65dp"
        android:layout_marginBottom="49dp"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/textView4"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="MissingConstraints" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="147dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

DashboardActivity.java

package com.example.firebaseemailpasswordexample;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class DashboardActivity extends AppCompatActivity {
    public static final String  Tag="DashboardActivity";



    private TextView textView41,textView51,textView21;
    private Button button1;
    private FirebaseAuth.AuthStateListener authListener;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);
        setupFirebaseListener();

        textView41=findViewById(R.id.textView4);
        textView51=findViewById(R.id.textView5);
        textView21=findViewById(R.id.textView2);
        button1=findViewById(R.id.button);

        SharedPreferences sharedPref = getSharedPreferences("myKey", MODE_PRIVATE);



        String email = sharedPref.getString("email","");
        String firstname = sharedPref.getString("firstname","");


        textView41.setText(email);
        textView51.setText(firstname);


        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(Tag,"onClick: attempting to sign out user.");
                FirebaseAuth.getInstance().signOut();
            }
        });


    }


    public void setupFirebaseListener(){
        Log.d(Tag,"setupFirebaseListener: Settingup the auth state listener");
        authListener=new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user=firebaseAuth.getCurrentUser();
                if (user!=null){
                    Log.d(Tag,"onAuthStateChanged: Signin" +user.getUid());
                }else {
                    Log.d(Tag,"onAuthStateChanged: Sign out");
                    Intent intent=new Intent(DashboardActivity.this,LoginActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                }
            }
        };
    }
}
Md。Asaduzzaman

複数のユーザーが同じアプリにログインするのをサポートするユースケースによると、ユーザー情報を保存するのではなく、SharedPreferencesFirebaseを使用できます。

ステップ-1:登録が成功した後updateProfile、ユーザー情報を更新するために使用します

mAuth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if(task.isSuccessful()) {

                    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

                    UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                            .setDisplayName(firstname)
                            .build();

                    user.updateProfile(profileUpdates)
                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if (task.isSuccessful()) {
                                        Log.d(TAG, "User profile updated.");
                                    }
                                }
                            });

                }
            }
        });

ステップ-2:ログインに成功FirebaseUserしたら、ユーザー情報を取得するために使用しますDashboardActivity

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

if (user != null) {
    // Name, email address
    String name = user.getDisplayName();
    String email = user.getEmail();

    textView41.setText(email);
    textView51.setText(name);
}

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

FireBase認証のログイン/登録の例外

C#を使用したデータベースへのログイン認証

Httppostを使用してFlutterログイン認証と登録を実装する方法

登録済みのカードストライプを使用したCVC認証

共有設定を使用してAndroidStudioでログインし続けるには

Terraform:共有設定ファイルまたは静的変数を使用してAWSプロバイダーに対して認証できません

Dockerを使用したデプロイ中のTomcatの認証設定の問題

Dockerを使用したデプロイ中のTomcatの認証設定の問題

AndroidStudioで共有設定を使用してGoogleログインの詳細を保存する

共有設定を使用して、ユーザーのログイン状態を維持する方法

基本認証を使用したLaravelSocialitefacebookログインの統合

共有設定を使用してkotlinにログインするときのエラー

Androidを使用したFirebaseのメールとパスワードの認証-ユーザーの登録

jwt認証を使用したvueアプリケーションへの自動ログイン

RundeckWebhookプラグインの認証を設定します

共有設定を使用してAndroidに1回限りの登録画面を実装したいのですが、以前の共有設定を取得できません

JIRAプラグインでWindows認証を使用したSQLServerへのJDBCURL接続

異なるログイン資格情報を使用したUNC共有へのアクセス

ログインプラグイン登録フォームの送信をテーマにしながらポップアップを設定します

パスポートを使用して登録した後のユーザーのログイン

Googleログインボタンを使用して認証範囲を設定する方法

Javaで記述されたRESTFulapiを使用してログイン/登録する

オブジェクトと配列を使用したJSログイン/登録

春のセキュリティUsernamePasswordAuthenticationFilter JWT認証で設定したカスタムのログインURL

FlutterのFirestoreデータベースでユーザー(登録/サインアップ)を作成するためにFirebase電話番号OTP認証を使用できますか?はいの場合、どのように?(アンドロイド)

PHPバックエンドを使用したNotificationHubへの登録

共有設定を使用してログインデータからトークンを取得する方法

ドメインをホワイトリストに登録した後でも、firebase認証ドメインが承認されない

Firebaseエラー「Reference.pushが失敗しました:2番目の引数は有効な関数である必要があります」を使用したユーザー登録とログイン

TOP 一覧

  1. 1

    セレンのモデルダイアログからテキストを抽出するにはどうすればよいですか?

  2. 2

    どのように関係なく、それがどのように「悪い」、すべてのSSL証明書でのHttpClientを使用しないように

  3. 3

    Modbus Python Schneider PM5300

  4. 4

    Ansibleで複数行のシェルスクリプトを実行する方法

  5. 5

    tkinterウィンドウを閉じてもPythonプログラムが終了しない

  6. 6

    System.Data.OracleClient.OracleException:ORA-06550:行1、列7:

  7. 7

    インデックス作成時のドキュメントの順序は、Elasticsearchの検索パフォーマンスを向上させますか?

  8. 8

    scala.xmlノードを正しく比較する方法は?

  9. 9

    NGX-ブートストラップ:ドロップダウンに選択したアイテムが表示されない

  10. 10

    Elasticsearch - あいまい検索は、提案を与えていません

  11. 11

    mutate_allとifelseを組み合わせるにはどうすればよいですか

  12. 12

    Elasticsearchの場合、間隔を空けた単語を使用したワイルドカード検索

  13. 13

    Elasticsearchでサーバー操作を最適化:低いディスク透かしに対処する

  14. 14

    ラベルとエントリがpythontkinterに表示されないのはなぜですか?

  15. 15

    変数値を含むElasticSearch検索結果

  16. 16

    グラフ(.PNG)ファイルをエクスポートするZabbix

  17. 17

    STSでループプロセス「クラスパス通知の送信」のループを停止する方法

  18. 18

    Audacity:プロジェクトではなく、サウンドファイルのみを保存します

  19. 19

    Crashlytics:コンパイラー生成とはどういう意味ですか?

  20. 20

    Excelは、メモ帳データの複数の列を1つの列として解釈します

  21. 21

    ブラウザがHTMLテンプレートを解釈しない

ホットタグ

アーカイブ