3

I'm trying to call addAuthStateListener but it's not working in kotlin. and also AuthUI not working properly. Every time I try to run this code I'm getting a runtime error. And the application force closed. I tried to get some help in firebase documentation but I'm not found anything that helps me.

import android.app.Activity
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.firebase.ui.auth.AuthUI
import com.google.firebase.auth.FirebaseAuth

class MainActivity : AppCompatActivity() {
    private var mFirebaseAuth:FirebaseAuth? = null
    private var mFirebaseAuthLis:FirebaseAuth.AuthStateListener?=null
    private val RC_SIGN_IN = 1258
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mFirebaseAuth = FirebaseAuth.getInstance()

        //val user = FirebaseAuth.getInstance().currentUser != null

        mFirebaseAuthLis=FirebaseAuth.AuthStateListener { firebaseAuth ->
            var user = firebaseAuth.currentUser
            if (user!=null){
                Toast.makeText(applicationContext,"Welcome",Toast.LENGTH_SHORT).show()
            }else{
                val providers = arrayListOf(
                    AuthUI.IdpConfig.EmailBuilder().build(),
                    AuthUI.IdpConfig.PhoneBuilder().build(),
                    AuthUI.IdpConfig.GoogleBuilder().build(),
                    AuthUI.IdpConfig.FacebookBuilder().build(),
                    AuthUI.IdpConfig.TwitterBuilder().build())


                startActivityForResult(
                    AuthUI.getInstance()
                        .createSignInIntentBuilder()
                        .setAvailableProviders(providers)
                        .build(),
                    RC_SIGN_IN)
            }

        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode==RC_SIGN_IN){
            if (resultCode== Activity.RESULT_OK){
                Toast.makeText(applicationContext,"Hi user",Toast.LENGTH_SHORT).show()
            }else{
                finish()
            }
        }
    }

    override fun onStart() {
        super.onStart()
       mFirebaseAuth!!.addAuthStateListener { mFirebaseAuthLis }
    }

    override fun onPause() {
        super.onPause()
       mFirebaseAuth!!.removeAuthStateListener { mFirebaseAuthLis }
    }
}

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.roni.familychatting">

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

build.gradle(Module: app)

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.roni.familychatting"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    //implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.google.firebase:firebase-core:16.0.4'
    implementation 'com.google.firebase:firebase-auth:16.0.4'
    implementation 'com.android.support:appcompat-v7:24.2.0'
    implementation 'com.firebaseui:firebase-ui-auth:4.2.0'

    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'

    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
apply plugin: 'com.google.gms.google-services'

project level gradle

buildscript {
    ext.kotlin_version = '1.2.71'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.0.1'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
Debashis Nandy
  • 545
  • 1
  • 7
  • 17

2 Answers2

1

You need to register the listener:

FirebaseAuth.getInstance().addAuthStateListener(listener)

In your case:

mFirebaseAuth!!.addAuthStateListener(mFirebaseAuthLis)
Sriram
  • 167
  • 2
  • 11
0

You need to save FirebaseAuth.AuthStateListener in mFirebaseAuthLis

mFirebaseAuthLis = FirebaseAuth.AuthStateListener { firebaseAuth ->
        var user = firebaseAuth.currentUser
        if (user!=null){
            Toast.makeText(applicationContext,"Welcome",Toast.LENGTH_SHORT).show()
        } else{
            val providers = arrayListOf(
                AuthUI.IdpConfig.EmailBuilder().build(),
                AuthUI.IdpConfig.PhoneBuilder().build(),
                AuthUI.IdpConfig.GoogleBuilder().build(),
                AuthUI.IdpConfig.FacebookBuilder().build(),
                AuthUI.IdpConfig.TwitterBuilder().build())


            startActivityForResult(
                AuthUI.getInstance()
                    .createSignInIntentBuilder()
                    .setAvailableProviders(providers)
                    .build(),
                RC_SIGN_IN)
        }

    }

After that all should work as expected.

ConstOrVar
  • 2,025
  • 1
  • 11
  • 14
  • now it shows me this error " E/FirebaseInstanceId: Failed to resolve target intent service, skipping classname enforcement E/FirebaseInstanceId: Error while delivering the message: ServiceIntent not found." – Debashis Nandy Oct 25 '18 at 12:12
  • @DebashisNandy, steps to solve that problem can be found in https://stackoverflow.com/questions/39962566/error-while-delivering-the-message-serviceintent-not-found – ConstOrVar Oct 25 '18 at 13:45
  • I tried this solution but again the problem is occurring. I don't understand why it's happening? – Debashis Nandy Oct 25 '18 at 16:11
  • @DebashisNandy, I suggest you create new question with more detailed information about manifest, service code that used firebase and other helpful stuff to solve problem. That question is no longer mirror the problem you have now (problem described in that question has been already solved) – ConstOrVar Oct 25 '18 at 18:11
  • I updated my post. I searched and try many things that are available but still i have same error. – Debashis Nandy Oct 26 '18 at 06:14
  • @DebashisNandy, as described in official docs https://firebase.google.com/docs/reference/android/com/google/firebase/iid/FirebaseInstanceIdService, you can extend `FirebaseInstanceIdService` and register it in manifest manually. Detailed guide how to do it described in https://medium.com/android-school/firebaseinstanceidservice-is-deprecated-50651f17a148 – ConstOrVar Oct 26 '18 at 06:30