I am not able to validate my new activity - android

I created a new empty activity for my project but I am getting an error. The activity file as well as the layout file is shown in red color. I tried creating an intent object from MainActivity, in order to start this activity but received the following error
Classifier 'Details' does not have a companion object, and thus must
be initialized here
I've attached a screenshot of my android studio.
Code for new activity
package com.example.safetyapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class Details : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_details)
}
}
package com.example.safetyapp
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.firebase.ui.auth.AuthUI
import com.google.firebase.auth.FirebaseAuth
class MainActivity : AppCompatActivity() {
final val AUTH_REQUEST_CODE = 7192
lateinit var firebaseAuth:FirebaseAuth
lateinit var listener: FirebaseAuth.AuthStateListener
lateinit var providers: List<AuthUI.IdpConfig>
override fun onStart(){
super.onStart()
firebaseAuth.addAuthStateListener(listener)
}
override fun onStop(){
super.onStop()
if(listener!=null){
firebaseAuth.removeAuthStateListener(listener)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button2 = findViewById<Button>(R.id.button2)
val defence = findViewById<Button>(R.id.Defence)
button2.setOnClickListener{
val myintent = Intent(this, Details::class.java)
}
init()
}
private fun init() {
providers = arrayListOf(AuthUI.IdpConfig.PhoneBuilder().build(),
AuthUI.IdpConfig.EmailBuilder().build())
firebaseAuth = FirebaseAuth.getInstance()
listener = object:FirebaseAuth.AuthStateListener{
override fun onAuthStateChanged(p0: FirebaseAuth) {
val user = p0.currentUser
if(user!= null){
// Do something
}
else{
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.setLogo(R.drawable.logo)
.build(),AUTH_REQUEST_CODE)
}
}
}
}
}

You didn't import the Details class, add this line between your MainActivity class imports
import com.example.safetyapp.Details

Related

None of the following functions can be called with the arguments supplied: public suspend fun delay(timeMillis: Long):

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.*
class SplashScreen : AppCompatActivity() {
private lateinit var progressBar: ProgressBar
private val SPLASH_DISPLAY_LENGTH = 5000
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.splash_screen)
progressBar = findViewById(R.id.progressBar)
GlobalScope.launch(Dispatchers.Main) {
delay(SPLASH_DISPLAY_LENGTH)
progressBar.visibility = View.VISIBLE
loadWebView()
}
}
private suspend fun loadWebView() {
withContext(Dispatchers.IO) {
delay(SPLASH_DISPLAY_LENGTH)
}
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}
This is a Splash Screen. I got this error - None of the following functions can be called with the arguments supplied:public suspend fun delay(timeMillis: Long): Unit defined in kotlinx.coroutinespublic suspend fun delay(duration: Duration): Unit defined in kotlinx.coroutines. Can anybody help me please. Thanks in Advance.
I got it. I removed SPLASH_DISPLAY_LENGTH and added the duration directly like this- delay(5000). It worked --
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.*
#OptIn(DelicateCoroutinesApi::class)
#SuppressLint("CustomSplashScreen")
class SplashScreen1 : AppCompatActivity() {
private lateinit var progressBar: ProgressBar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.splash_screen)
progressBar = findViewById(R.id.progrssBar2)
GlobalScope.launch(Dispatchers.Main) {
delay(3000)
progressBar.visibility = View.VISIBLE
loadWebView()
}
}
private suspend fun loadWebView() {
withContext(Dispatchers.IO) {
delay(3000)
}
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}
It is another answer thanks to #Tenfour04. Comment
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.*
class SplashScreen1 : AppCompatActivity() {
private lateinit var progressBar: ProgressBar
//Define the constant as long instead of int
private val SPLASH_DISPLAY_LENGTH = 5000L
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.splash_screen)
progressBar = findViewById(R.id.progress_circular)
GlobalScope.launch(Dispatchers.Main) {
delay(SPLASH_DISPLAY_LENGTH)
progressBar.visibility = View.VISIBLE
loadWebView()
}
}
private suspend fun loadWebView() {
withContext(Dispatchers.IO) {
delay(SPLASH_DISPLAY_LENGTH)
}
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}

Firebase authentication issues, Kotlin

I am having some issues with Firebase auth. I'm building an app using using Kotlin but keep retrieving the error 'W/System: Ignoring header X-Firebase-Locale because its value was null.'
I had this working previously, when I had set up the application using activities. I've now moved towards MVP architecture, but this seems to have broken my firebase authentication. I have also ensured that Email/Password sign in method has been enabled in the Firebase console.
If anyone could please take a look and hopefully you can see where I am going wrong. Many thanks.
SignInView
package org.wit.hikingtrails.views.signIn
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import org.wit.hikingtrails.databinding.ActivitySignInBinding
import com.google.firebase.auth.FirebaseAuth
import org.wit.hikingtrails.activities.SignUpActivity
import org.wit.hikingtrails.views.hikeList.HikeListView
import org.wit.hikingtrails.views.signUp.SignUpView
class SignInView : AppCompatActivity() {
lateinit var presenter: SignInPresenter
private lateinit var binding: ActivitySignInBinding
private lateinit var firebaseAuth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
presenter = SignInPresenter( this)
super.onCreate(savedInstanceState)
binding = ActivitySignInBinding.inflate(layoutInflater)
setContentView(binding.root)
firebaseAuth = FirebaseAuth.getInstance()
binding.textView.setOnClickListener {
val intent = Intent(this, SignUpView::class.java)
startActivity(intent)
}
binding.button.setOnClickListener {
val email = binding.emailEt.text.toString()
val pass = binding.passET.text.toString()
if (email.isNotEmpty() && pass.isNotEmpty()) {
presenter.doLogin(email, pass)
} else {
Toast.makeText(this, "Empty Fields Are not Allowed !!", Toast.LENGTH_SHORT).show()
}
}
}
override fun onStart() {
super.onStart()
if(firebaseAuth.currentUser != null){
val intent = Intent(this, HikeListView::class.java)
startActivity(intent)
}
}
}
SignInPresenter:
package org.wit.hikingtrails.views.signIn
import android.content.ContentValues.TAG
import android.content.Intent
import android.util.Log
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.google.firebase.auth.FirebaseAuth
import org.wit.hikingtrails.views.hikeList.HikeListView
import timber.log.Timber
import timber.log.Timber.i
class SignInPresenter (val view: SignInView) {
private lateinit var loginIntentLauncher : ActivityResultLauncher<Intent>
init{
registerLoginCallback()
}
var auth: FirebaseAuth = FirebaseAuth.getInstance()
fun doLogin(email: String, pass: String) {
// view.showProgress()
auth.signInWithEmailAndPassword(email, pass).addOnCompleteListener(view) { task ->
if (task.isSuccessful) {
val launcherIntent = Intent(view, HikeListView::class.java)
loginIntentLauncher.launch(launcherIntent)
} else {
i("Login failed:")
// val launcherIntent = Intent(view, HikeListView::class.java)
// loginIntentLauncher.launch(launcherIntent)
}
// view.hideProgress()
}
}
private fun registerLoginCallback(){
loginIntentLauncher =
view.registerForActivityResult(ActivityResultContracts.StartActivityForResult())
{ }
}
}
For anyone that was having the same issue: The issue was with my API key. In kotlin, to debug, I used Timber.i( "signInWithCredential:failure ${task.exception?.message}") within the else statement of doLogin() in the presenter

Getting FATAL EXCEPTION while running the applications second screen

I am working on a android application that is NewsApp. I had made 2 activity. First is MainActivity and Second is HomeActivity. There is a button on MainActivity that is Register. If user press the button the MainActivity will be finish and HomeActivity appears but in my case when the user click register button the HomeActivity is not appearing and emulator show "App has stopped".
Since I am new to this I am not able to spot where the problem is and don't know how I can resolve it.
Thanks in advance.
The Error I am getting is:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.project.newsapp, PID: 8723
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at com.project.newsapp.HomeActivity.onResponse(HomeActivity.kt:108)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
I am also attaching my HomeActivity and MainActivity code so you can tell me where I am doing it wrong.
My HomeActivity Code:
package com.project.newsapp
import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.project.newsapp.contract.Request
import com.project.newsapp.contract.Response
import com.project.newsapp.network.IRequestContract
import com.project.newsapp.network.NetworkClient
import com.project.newsapp.utils.Constant
import com.project.newsapp.utils.DataProvider
import com.project.newsapp.utils.showToast
import kotlinx.android.synthetic.main.activity_home.*
import kotlinx.android.synthetic.main.activity_home.btnExit
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Call
import retrofit2.Callback
class HomeActivity : AppCompatActivity(), Callback<Response>, View.OnClickListener {
lateinit var userId:String
lateinit var userName:String
private val retrofitClient = NetworkClient.getNetworkClient()
private val requestContract = retrofitClient.create(IRequestContract::class.java)
private lateinit var sharedPreferences: SharedPreferences
private lateinit var progressDialog: ProgressDialog
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
progressDialog = ProgressDialog(this)
progressDialog.setMessage("Please wait...")
progressDialog.setCancelable(true)
sharedPreferences = getSharedPreferences(Constant.PREF_NAME, Context.MODE_PRIVATE)
title = "NewsApp"
userId = intent.getStringExtra(Constant.KEY_USER_ID).toString()
userName = intent.getStringExtra(Constant.KEY_USER_NAME).toString()
txtUserName.text = "Welcome $userName"
btnAllNews.setOnClickListener (this)
btnMyNews.setOnClickListener (this)
btnSignOut.setOnClickListener (this)
btnExit.setOnClickListener (this)
}
override fun onStart() {
super.onStart()
progressDialog.show()
val request = Request(
action = Constant.GET_NEWS,
userId = userId
)
val callResponse = requestContract.makeApiCall(request)
callResponse.enqueue(this)
}
override fun onClick(v: View?) {
when(v?.id){
R.id.btnAllNews -> {
if(DataProvider.response.allNews.size>0){
Intent(this,ViewAllNewsActivity::class.java).apply {
startActivity(this)
}
}else{
showToast("Blogs are not available")
}
}
R.id.btnMyNews -> {
}
R.id.btnSignOut -> {
signOut()
}
}
}
private fun signOut(){
val editor = sharedPreferences.edit()
editor.clear().commit()
Intent(this,MainActivity::class.java).apply{
startActivity(this)
finish()
}
}
override fun onResponse(call: Call<Response>, response: retrofit2.Response<Response>) {
if(progressDialog.isShowing)
progressDialog.dismiss()
if(response.body()!=null){
val serverResponse = response.body()
if(serverResponse!!.status){
DataProvider.response = serverResponse
}else{
showToast(serverResponse.message)
edUserName.setText("")
}
}
else{
showToast("Server is not responding. Please try again later.")
}
}
override fun onFailure(call: Call<Response>, t: Throwable) {
if(progressDialog.isShowing)
progressDialog.dismiss()
showToast("Server is not responding. Please try again later.")
}}
My MainActivity Code:
package com.project.newsapp
import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.project.newsapp.contract.Request
import com.project.newsapp.contract.Response
import com.project.newsapp.network.IRequestContract
import com.project.newsapp.network.NetworkClient
import com.project.newsapp.utils.Constant
import com.project.newsapp.utils.showToast
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Call
import retrofit2.Callback
class MainActivity : AppCompatActivity(), Callback<Response> {
private val retrofitClient = NetworkClient.getNetworkClient()
private val requestContract = retrofitClient.create(IRequestContract::class.java)
private lateinit var progressDialog:ProgressDialog
private lateinit var sharedPreferences:SharedPreferences
lateinit var userName:String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
progressDialog = ProgressDialog(this)
progressDialog.setMessage("Please wait...")
progressDialog.setCancelable(true)
sharedPreferences = getSharedPreferences(Constant.PREF_NAME, Context.MODE_PRIVATE)
checkIfUserAlreadyRegistered()
btnRegister.setOnClickListener {
userName = edUserName.text.toString().trim().uppercase()
if(userName.isNullOrEmpty()){
showToast("Please Enter your Name")
}else{
progressDialog.show()
val request = Request(
action = Constant.REGISTER_USER,
userName = userName
)
val callResponse = requestContract.makeApiCall(request)
callResponse.enqueue(this)
}
}
/*btnExit.setOnClickListener {
finish()
}*/
}
override fun onFailure(call: Call<Response>, t: Throwable) {
if(progressDialog.isShowing)
progressDialog.dismiss()
showToast("Server is not responding. Please try again later.")
edUserName.setText("")
}
override fun onResponse(call: Call<Response>, response: retrofit2.Response<Response>) {
if(progressDialog.isShowing)
progressDialog.dismiss()
if(response.body()!=null){
val serverResponse = response.body()
if(serverResponse!!.status){
saveUserToPref(serverResponse.userId,userName)
Intent(this, HomeActivity::class.java).apply {
putExtra(Constant.KEY_USER_ID, serverResponse.userId)
putExtra(Constant.KEY_USER_NAME, userName)
startActivity(this)
finish()
}
}else{
showToast(serverResponse.message)
edUserName.setText("")
}
}
else{
showToast("Server is not responding. Please try again later.")
edUserName.setText("")
}
}
private fun saveUserToPref(userId:String, userName:String){
val editor = sharedPreferences.edit()
editor.putString(Constant.KEY_USER_ID,userId)
editor.putString(Constant.KEY_USER_NAME,userName)
editor.commit()
}
private fun checkIfUserAlreadyRegistered(){
val userId = sharedPreferences.getString(Constant.KEY_USER_ID,"invalid user id")
val userName = sharedPreferences.getString(Constant.KEY_USER_NAME,"invalid user name")
if(!userId.contentEquals("invalid user id")
&& !userName.contentEquals("invalid user name")){
Intent(this, HomeActivity::class.java).apply {
putExtra(Constant.KEY_USER_ID, userId)
putExtra(Constant.KEY_USER_NAME, userName)
startActivity(this)
finish()
}
}
}}
Kotlin synthetic accessors are deprecated.
One of the reasons why they are deprecated is that they lead to the error that you are seeing. edUserName appears to be null, implying that R.layout.activity_home does not actually have a widget whose ID maps to edUserName.
The problem may come from:
import kotlinx.android.synthetic.main.activity_main.*
Most likely, that should not be in HomeActivity, since you are not using activity_main there.

my app keep crashing after tryed to connect it to firebase kotlin

I created a simple login and sup app and connect it to firebase.
so far the logging layout does not even show up it's just crushing while lanching which makes me so confused?
[![eroo message][1]][1]
this is my login/main activity
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
class MainActivity : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
val button: Button = findViewById(R.id.buGotosub)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
auth = FirebaseAuth.getInstance()
button.setOnClickListener {
startActivity(Intent(this,SubscribAcc::class.java))
finish()
}
}
public override fun onStart() {
super.onStart()
// Check if user is signed in (non-null) and update UI accordingly.
val currentUser = auth.currentUser
updarUI(currentUser)
}
fun updarUI(currentUser : FirebaseUser?){
}
} ```

Kotlin: Set variable in secondary activity conditional on OnClick in main activity

I have a main activity with four card views. I want each card view, when clicked, to go to a multiple choice quiz specific to that card. In my questions activity, I need to identify which of the card views was clicked in order to determine which set of questions should be called. I tried using boolean values in my main activity but am not able to reference them in my questions activity.
Main Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
c1.setOnClickListener {
val intent = Intent(this, QuestionsActivity::class.java)
intent.putExtra("boolean_a", true);
startActivity(intent)
finish()
}
c2.setOnClickListener {
val intent = Intent(this, QuestionsActivity::class.java)
intent.putExtra("boolean_b", true);
startActivity(intent)
finish()
}
c3.setOnClickListener {
val intent = Intent(this, QuestionsActivity::class.java)
intent.putExtra("boolean_c", true);
startActivity(intent)
finish()
}
c4.setOnClickListener {
val intent = Intent(this, QuestionsActivity::class.java)
intent.putExtra("boolean_d", true);
startActivity(intent)
finish()
}
}
}
The intent.putExtra("booleanA", true) in my main activity and if boolean statement and var booleanA = getIntent().getExtras()!!.getBoolean("booleanA") declaration in my secondary activity crash the app. If I remove intent.putExtra("booleanA", true) and var booleanA = getIntent().getExtras()!!.getBoolean("booleanA")and remove the if statement, leaving just mQuestionsList = Constants.getQuestions(), the app no longer crashes
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import kotlinx.android.synthetic.main.activity_questions.*
class QuestionsActivity : AppCompatActivity(), View.OnClickListener {
private var mCurrentPosition:Int = 1
private var mQuestionsList:ArrayList<Questions>? = null
private var mSelectedOptionPosition:Int = 0
private var mCorrectAnswers: Int = 0
var booleanA = getIntent().getExtras()!!.getBoolean("booleanA")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_questions)
if (booleanA){
mQuestionsList = Constants.getQuestions()
}
setQuestion()
radio_button1.setOnClickListener(this)
radio_button2.setOnClickListener(this)
radio_button3.setOnClickListener(this)
radio_button4.setOnClickListener(this)
}
You Should do like this
class QuestionsActivity : AppCompatActivity(), View.OnClickListener {
private var mCurrentPosition:Int = 1
private var mQuestionsList:ArrayList<Questions>? = null
private var mSelectedOptionPosition:Int = 0
private var mCorrectAnswers: Int = 0
//don't get the intent data here
var booleanA: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_questions)
//get the intent data here
booleanA = getIntent().getExtras()!!.getBoolean("booleanA")
if (booleanA){
mQuestionsList = Constants.getQuestions()
}
setQuestion()
radio_button1.setOnClickListener(this)
radio_button2.setOnClickListener(this)
radio_button3.setOnClickListener(this)
radio_button4.setOnClickListener(this)
}

Categories

Resources