I developed an application to get NFC adapter using NfcAdapter.getDefaultAdapter(this) function. But it gives NullPointerException - NfcAdapter.getDefaultAdapter(this) must not be null.
class TappingActivity : BaseActivity() {
private lateinit var mNfcAdapter: NfcAdapter
private lateinit var mFusedLocationClient: FusedLocationProviderClient
private lateinit var mBroadcastReceiver: BroadcastReceiver
private lateinit var mAdapter: RecyclerViewAdapter<SecurityPoint, ViewHolder>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tapping)
ButterKnife.bind(this)
setSupportActionBar(toolbar)
savedInstanceState?.let {
lastLoggedPremisesID = it.getInt("lastLoggedPremisesID")
}
mNfcAdapter = NfcAdapter.getDefaultAdapter(this)
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
if (!mNfcAdapter.isEnabled) {
snack(getString(R.string.str_nfc_disabled), Snackbar.LENGTH_INDEFINITE, R.color.error)
}
}
override fun onResume() {
super.onResume()
setupForegroundDispatch()
}
override fun onPause() {
super.onPause()
stopForegroundDispatch()
}
override fun onDestroy() {
super.onDestroy()
LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver)
}
private fun setupForegroundDispatch() {
val intent = Intent(this, TagDetection::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
val intentFilter = IntentFilter()
intentFilter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED)
intentFilter.addCategory(Intent.CATEGORY_DEFAULT)
val techList = arrayOf<Array<String>>()
mNfcAdapter.enableForegroundDispatch(this, pendingIntent, arrayOf(intentFilter), techList)
}
private fun stopForegroundDispatch() {
mNfcAdapter.disableForegroundDispatch(this)
}
}
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.antlergroup.patrolsystem, PID: 11333
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.antlergroup.patrolsystem/com.antlergroup.patrolsystem.ui.SecurityPointRegistrationActivity}: java.lang.NullPointerException: NfcAdapter.getDefaultAdapter(this) must not be null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3897)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4076)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2473)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:219)
at android.app.ActivityThread.main(ActivityThread.java:8349)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1055)
Caused by: java.lang.NullPointerException: NfcAdapter.getDefaultAdapter(this) must not be null
at com.antlergroup.patrolsystem.ui.SecurityPointRegistrationActivity.onCreate(SecurityPointRegistrationActivity.kt:72)
at android.app.Activity.performCreate(Activity.java:8085)
at android.app.Activity.performCreate(Activity.java:8073)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1320)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3870)
You need to define NfcManager first then you can call the getDefaultAdapter method. Please refer to the code snippet.
private var mNfcAdapter: NfcAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tapping)
NfcManager manager = (NfcManager) context.getSystemService(Context.NFC_SERVICE);
mNfcAdapter = manager.getDefaultAdapter();
}
For more information, you can refer to this link
Related
My app crashes on starting it (basically any activity with firebase code) after adding firebase authentication
This is the logcat
2022-07-14 20:17:21.538 15482-15482/com.example.flimer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.flimer, PID: 15482
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.flimer/com.example.flimer.SignUp}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3086)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3318)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:113)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:71)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2044)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:226)
at android.app.ActivityThread.main(ActivityThread.java:7212)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:576)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:956)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:170)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
at android.content.Context.obtainStyledAttributes(Context.java:682)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:848)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:815)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:640)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:259)
at com.example.flimer.SignUp.<init>(SignUp.kt:15)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1215)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3074)
This is the code for the splashscreen
class Startscreen : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_startscreen)
auth = Firebase.auth
val user = auth.currentUser
if (Build.VERSION.SDK_INT < 16) {
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN)
}
if (user != null){
Handler().postDelayed({
val intent = Intent(this#Startscreen, MainActivity::class.java)
startActivity(intent)
finish()
}, 2000)
}else{
Handler().postDelayed({
val intent = Intent(this#Startscreen, SignUp::class.java)
startActivity(intent)
finish()
},2000)
}
}
This is the crash happening in my sign up screen on starting
class SignUp : AppCompatActivity() {
private lateinit var etEmail: String
private lateinit var etPass: String
private lateinit var etPass2: String
private lateinit var btn: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sign_up)
etEmail = findViewById<EditText>(R.id.et_email).text.toString().trim { it <= ' ' }
etPass = findViewById<EditText>(R.id.pass).text.toString().trim { it <= ' ' }
etPass2 = findViewById<EditText>(R.id.et_pass2).text.toString().trim { it <= ' ' }
btn = findViewById(R.id.btn_create)
btn.setOnClickListener {
dialog()
if (isValid(etEmail, etPass, etPass2)){
signUp(etEmail, etPass)
}
}
}
private fun isValid(email: String, pass: String,pass2: String ): Boolean{
return if (email.isEmpty() && pass.isEmpty()){
Toast.makeText(this#SignUp, "Fill in the blanks", Toast.LENGTH_SHORT).show()
false
}else if(pass != pass2){
Toast.makeText(this#SignUp, "Passwords do not match", Toast.LENGTH_SHORT).show()
false
}else{
true
}
}
private fun signUp(email: String, pass: String){
var auth: FirebaseAuth = Firebase.auth
auth.createUserWithEmailAndPassword(email,pass).addOnCompleteListener {
dismiss()
if (it.isSuccessful){
Toast.makeText(this#SignUp, "Success",Toast.LENGTH_SHORT ).show()
}else{
Toast.makeText(this#SignUp, it.exception!!.message, Toast.LENGTH_SHORT).show()
}
}
}
private fun dialog(){
val dialog = Dialog(this)
dialog.setContentView(R.layout.custom_dialog)
dialog.show()
}
private fun dismiss(){
Dialog(this).dismiss()
}
}
The auth variable is initialized as follows
auth = FirebaseAuth.getInstance()
And not how you are doing
auth = Firebase.auth
Please help, the program not work.
I want to change the variables a and b and put them in the names
Thanks..............................................................................................
class Asd(){
lateinit var a: String
lateinit var b: String
var database = FirebaseDatabase.getInstance().getReference("RedCars")
.child("20-8-2020 18:0")
.addValueEventListener(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(p0: DataSnapshot) {
var map = p0.value as Map<String, Any>
a = map["price"].toString()
b = map["pickup"].toString()
}
})
}
public class MyCustomAdapter(context: Context): BaseAdapter(){
private val mContext: Context
val d = Asd().a
val h = Asd().b
var names = arrayListOf<String>(
d, h
)
I try this:.............
public class MyCustomAdapter(context: Context): BaseAdapter(){
lateinit var a: String
lateinit var b: String
var database = FirebaseDatabase.getInstance().getReference("RedCars")
.child("20-8-2020 18:0")
.addValueEventListener(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(p0: DataSnapshot) {
var map = p0.value as Map<String, Any>
a = map["price"].toString()
b = map["pickup"].toString()
}
})
private val mContext: Context
var names = arrayListOf<String>(
a, b
)
Logcat error:....................................................
2020-08-05 22:03:16.024 9227-9227/com.example.redcars E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.redcars, PID: 9227
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.redcars/com.example.redcars.MainActivity}: kotlin.UninitializedPropertyAccessException: lateinit property a has not been initialized
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3895)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4074)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2473)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:219)
at android.app.ActivityThread.main(ActivityThread.java:8347)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1055)
Caused by: kotlin.UninitializedPropertyAccessException: lateinit property a has not been initialized
at com.example.redcars.MainActivity$MyCustomAdapter.<init>(MainActivity.kt:133)
at com.example.redcars.MainActivity.onCreate(MainActivity.kt:47)
at android.app.Activity.performCreate(Activity.java:8085)
at android.app.Activity.performCreate(Activity.java:8073)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1320)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3868)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4074)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2473)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:219)
at android.app.ActivityThread.main(ActivityThread.java:8347)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1055)
And this have in MainActivity:
listView.adapter = MyCustomAdapter(this)
You should use lateinit properties only after they are initialized. So I suggest to move initialization of names array to ValueEventListener:
public class MyCustomAdapter(context: Context): BaseAdapter(){
lateinit var a: String
lateinit var b: String
lateinit var names: ArrayList<String>
// or you can use MutableList
// var namesMutable: MutableList<String> = mutableListOf()
var database = FirebaseDatabase.getInstance().getReference("RedCars")
.child("20-8-2020 18:0")
.addValueEventListener(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(p0: DataSnapshot) {
var map = p0.value as Map<String, Any>
a = map["price"].toString()
b = map["pickup"].toString()
// INITIALIZE THE ARRAY HERE
names = arrayListOf<String>(a, b)
// namesMutable.add(a)
// namesMutable.add(b)
// notifyDatasetChanged()
}
})
// ...
}
I don't really understand why logFile(and loggingProcess) are not initialized. The logcat shows that the file exists and createLogFile() method had been called when Activity was created, but when I'm trying to uploadLogs() from the Activity(using SandboxApp().uploadLogs()) it throws an exception
class SandboxApp: Application(), MyCallbacks {
companion object {
#JvmField
val TAG = SandboxApp::class.java.simpleName
}
private lateinit var loggingProcess: Process
private lateinit var logFile: File
private lateinit var fileDirectory: File
private var isLogging = false
private val formatter = SimpleDateFormat("dd-MM-yyyy_HH-mm", Locale.getDefault())
private lateinit var workManager: WorkManager
override fun onCreate() {
super.onCreate()
workManager = WorkManager.getInstance(this)
registerActivityLifecycleCallbacks(this)
}
fun createLogFile() {
val currentTime = formatter.format(Calendar.getInstance().time)
val fileName = "logs-$currentTime.log"
fileDirectory = File(filesDir.absolutePath + File.separator + "sandboxLog")
fileDirectory.mkdirs()
Log.d(TAG, "FileDir exists? $fileDirectory, ${fileDirectory.exists()}")
logFile = File(fileDirectory, fileName)
logFile.createNewFile()
Log.d(TAG, "File exists? $logFile, ${logFile.exists()}")
}
fun startLogging() {
isLogging = true
loggingProcess = Runtime.getRuntime().exec("logcat -f $logFile")
}
private fun stopLogging() {
isLogging = false
loggingProcess.destroy()
}
fun uploadLogs() {
stopLogging()
val data = Data.Builder()
.putString("file path", logFile.absolutePath)
.build()
val request = OneTimeWorkRequest.Builder(LogsWorker::class.java)
.setInputData(data)
.build()
workManager.enqueue(request)
createLogFile()
startLogging()
}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
super.onActivityCreated(activity, savedInstanceState)
Log.d(TAG, "onActivityCreated method")
createLogFile()
startLogging()
}
}
This is the exception, tha same is for the loggingProcess variable
2020-08-04 15:55:51.338 8741-8741/com.example.sandboxlog E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sandboxlog, PID: 8741
kotlin.UninitializedPropertyAccessException: lateinit property logFile has not been initialized
at com.example.sandboxlog.SandboxApp.uploadLogs(SandboxApp.kt:66)
at com.example.sandboxlog.MainActivity$onCreate$2.onClick(MainActivity.kt:33)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
upd: onCreate method of MainActivity, where uploadLogs is being called
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d(TAG, "MainActivity created")
Thread.setDefaultUncaughtExceptionHandler(CrashHandler())
button.setOnClickListener {
// creating an exception
RequestBody.create(MultipartBody.FORM, exceptionFile!!)
}
buttonSend.setOnClickListener {
SandboxApp().uploadLogs()
}
buttonSecondActivity.setOnClickListener {
Log.d(TAG, "Starting second activity")
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
}
}
You shouldn't create an instance of your app class SandboxApp by yourself, it is done by the system. To have access to the instance of SandboxApp you can use ctx.applicationContext property:
val app = context.applicationContext as SandboxApp
app.uploadLogs()
So in the OnClickListener it will look like the following:
buttonSend.setOnClickListener {
val app = applicationContext as SandboxApp
app.uploadLogs()
}
I am developing news and I am getting following nullpointexception
java.lang.RuntimeException: Unable to start activity ComponentInfo{yodgorbek.komilov.musobaqayangiliklari/yodgorbek.komilov.musobaqayangiliklari.ui.WelcomeActivity}: kotlin.UninitializedPropertyAccessException: lateinit property manager has not been initialized
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2976)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3113)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:113)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:71)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1858)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6820)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:922)
Caused by: kotlin.UninitializedPropertyAccessException: lateinit property manager has not been initialized
at yodgorbek.komilov.musobaqayangiliklari.ui.WelcomeActivity.onCreate(WelcomeActivity.kt:26)
at android.app.Activity.performCreate(Activity.java:7224)
at android.app.Activity.performCreate(Activity.java:7213)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2956)
... 11 more
below my WelcomeActivity.kt class
class WelcomeActivity : AppIntro() {
private lateinit var manager: PreferencesManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Make sure you don't call setContentView!
if (manager.isFirstRun()) {
showIntroSlides()
} else {
goToMain()
}
}
// Call addSlide passing your Fragments.
// You can use AppIntroFragment to use a pre-built fragment
private fun showIntroSlides() {
manager.setFirstRun()
addSlide(
AppIntroFragment.newInstance(
title = "Welcome to the NewsApp",
description = "NewsApp give your information about life news around the world",
imageDrawable = R.drawable.news,
backgroundDrawable = R.drawable.news_slider,
titleColor = Color.YELLOW,
descriptionColor = Color.RED,
backgroundColor = Color.BLUE,
titleTypefaceFontRes = R.font.opensans_light,
descriptionTypefaceFontRes = R.font.opensans_regular
)
)
addSlide(
AppIntroFragment.newInstance(
title = "...Let's get started!",
description = "This is the last slide, I won't annoy you more :)"
)
)
}
private fun goToMain() {
startActivity(Intent(this, MainActivity::class.java))
}
override fun onSkipPressed(currentFragment: Fragment?) {
super.onSkipPressed(currentFragment)
goToMain()
}
override fun onDonePressed(currentFragment: Fragment?) {
super.onDonePressed(currentFragment)
goToMain()
}
override fun onSlideChanged(oldFragment: Fragment?, newFragment: Fragment?) {
super.onSlideChanged(oldFragment, newFragment)
Log.d("Hello", "Changed")
}
}
I don't understand what is the causing null pointer exception even I have tried initialize manager following way
private var manager: PreferencesManager? = null
but it did not solve my problem
I want to know where I am making mistake what I have to do avoid nullpointer exception
It's simple by looking into logs. Your manager is not initialized before using. Look at onCreate
private lateinit var manager: PreferencesManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Make sure you don't call setContentView!
// <<<<<<<<<<<<<<< INITIALISE manager HERE >>>>>>>>>>>>>>
if (manager.isFirstRun()) { <<<<<<<< HERE you are using an uninitilised manager
showIntroSlides()
} else {
goToMain()
}
}
Initialise manager before if (manager.isFirstRun()) { in onCreate()
Main activity:
val turminha : Turma = this.abrirArquivo()
recycler_view.layoutManager = LinearLayoutManager(this)
recycler_view.adapter = AlunoAdapter(this,turminha.alunos)
floatingActionButton.setOnClickListener({
val i = Intent(this, ActivityAddAluno::class.java)
i.putExtra("turma", turminha)
startActivity(i)
})
ActivityAddAluno
class ActivityAddAluno : AppCompatActivity() {
var i = getIntent()
private var turma = i.getSerializableExtra("turma") as Turma
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_aluno)
mBtnSalvarAluno.setOnClickListener{
var name = mEdtNomeAluno.text.toString()
var matricula = mEdtMatriculaAluno.text.toString()
toast("Nome: $name \n," +
"Matricula: $matricula")
turma.addAluno(Aluno(name, matricula))
}
}
Class Aluno
class Aluno : Serializable {
var disciplinas: ArrayList<Disciplina>? = null
private set
var nome: String? = null
var matricula: String? = null
constructor() {
disciplinas = ArrayList()
}
constructor(nome: String, matricula: String) {
this.nome = nome
this.matricula = matricula
disciplinas = ArrayList()
}
Class Turma
class Turma() : Serializable {
val alunos: ArrayList<Aluno>
init {
alunos = ArrayList()
}
fun addAluno(aluno: Aluno) {
alunos.add(aluno)
}
When I try to access the other activity passing my Turma object in floatbutton, the app stops working. Logcat says the problem is in the code part:
var i = getIntent()
private var turma = i.getSerializableExtra("turma") as Turma
logcat:
FATAL EXCEPTION: main
Process: com.example.thial.estudandokotlin, PID: 3428
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.thial.estudandokotlin/com.example.thial.estudandokotlin.ActivityAddAluno}:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
How can i resolve this?
Actually your problem is happening here as per your log cat messages.
var i = getIntent()
private var turma = i.getSerializableExtra("turma") as Turma
Here the Value "i" is null and on top of it your trying to take the getSerializableExtra() String.
Where exactly your calling this lines in ActivityAddAluno class ? It must be inside the onCreate function not in the constructor. (As per Joshua stated)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//...
var i = getIntent()
if(i!=null)
{
private var turma = i.getSerializableExtra("turma") as Turma
}
}
Here is one of the example Switching between Activities along with data using Kotlin