-1

i'm getting this error each time the button Medir is pressed, everything works with the rest

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference

this is the MainActivity code:

    package com.example.kotlincalcinsu

    import android.content.Intent
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.widget.Button
    import android.widget.TextView

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

            val admin = AdminSQLiteOpenHelper(this, "AppDB", null, 1)
            val bd = admin.readableDatabase

            val name = bd.rawQuery("SELECT nombre FROM usuario", null).toString()
            val weight = bd.rawQuery("SELECT peso FROM usuario", null).toString()
            bd.close()

            //declarando TextView
            val nombre = findViewById<TextView>(R.id.Nombre)
            val peso = findViewById<TextView>(R.id.Peso)
            //declarando botones
            val medir = findViewById<Button>(R.id.medir)
            val historial = findViewById<Button>(R.id.historial)
            val registro = findViewById<Button>(R.id.registro)

            if (name.isNotEmpty() && weight.isNotEmpty()){
                nombre.text = name
                peso.text = weight
            }

            medir.setOnClickListener {
                val intent = Intent(this, Medir::class.java)
                startActivity(intent)
            }
            historial.setOnClickListener {
                val intent = Intent(this, Historial::class.java)
                startActivity(intent)
            }
            registro.setOnClickListener {
                val intent = Intent(this, Registro::class.java)
                startActivity(intent)
            }
        }
     }

And this is the Activity i'm trying to start




package com.example.kotlincalcinsu

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.ListView
import android.widget.Toast
import androidx.core.app.ActivityCompat

class Medir : AppCompatActivity() {

    private val REQUEST_CODE_ENABLE_BT:Int = 1
    private var bluetoothAdapter: BluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
    private lateinit var pairedDevices: Set<BluetoothDevice>

    val selectDeviceList = findViewById<ListView>(R.id.selectorLV)

    companion object{
        val EXTRA_ADDRESS: String = "Device_address"
    }

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



        val refresh = findViewById<Button>(R.id.refresh)
        val conectar = findViewById<Button>(R.id.conectar)

        //inicializar BluetoothAdapter
        //bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        //revisar si esta encendido el Bluetooth
        if (bluetoothAdapter == null){
            Toast.makeText(this, "This device doesn't support Bluetooth", Toast.LENGTH_LONG).show()
            return
        } else{
            Toast.makeText(this, "Bluetooth available", Toast.LENGTH_LONG).show()
        }

        if (!bluetoothAdapter!!.isEnabled){
            val enableBluetoothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) return
            startActivityForResult(enableBluetoothIntent, REQUEST_CODE_ENABLE_BT)
        }

        refresh.setOnClickListener { pairedDeviceList() }


    }
    private fun pairedDeviceList(){
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { }
        pairedDevices = bluetoothAdapter!!.bondedDevices
        val list : ArrayList<BluetoothDevice> = ArrayList()

        if (pairedDevices.isNotEmpty()){
            for (device: BluetoothDevice in pairedDevices){
                list.add(device)
                Log.i("device", ""+device)
            }
        } else{
            Toast.makeText(this, "No paired Bluetooth devices", Toast.LENGTH_LONG).show()
        }

        val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, list)
            selectDeviceList.adapter = adapter
            selectDeviceList.onItemClickListener = AdapterView.OnItemClickListener{ _, _, position, _ ->
            val device: BluetoothDevice = list[position]
            val address: String = device.address

            val intent = Intent(this, ControlActivity::class.java)
            intent.putExtra(EXTRA_ADDRESS, address)
            startActivity(intent)
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == REQUEST_CODE_ENABLE_BT){
        if (resultCode == RESULT_OK){
            if (bluetoothAdapter!!.isEnabled){
                Toast.makeText(this, "Bluetooth has been enabled", Toast.LENGTH_LONG).show()
            } else{
                Toast.makeText(this, "Bluetooth has been disabled", Toast.LENGTH_LONG).show()
            }
        } else if (resultCode == RESULT_CANCELED){
            Toast.makeText(this, "Bluetooth enableing has been canceled", Toast.LENGTH_LONG).show()
        }
    }
}

}

and the AndroidManifest:

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

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
    <uses-feature
        android:name="android.hardware.bluetooth_le"
        android:required="true">
    </uses-feature>
    <uses-feature
        android:name="android.hardware.bluetooth"
        android:required="true">
    </uses-feature>

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.KotlinCalcInsu"
        tools:targetApi="31">
        <activity
            android:name=".Historial"
            android:exported="false">
            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
        <activity
            android:name=".Medir"
            android:exported="false">
            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
        <activity
            android:name=".Registro"
            android:exported="false">
            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

</manifest>

everything appears to be right according to teachers and other people that have take a look at it, but it just keeps throwing that error and crashing the app. Any help is welcome and thanks beforehand

i have already tried different computers Mac and Windows, tried with different versions of Android and Android Studio. I rewrite the code to check if there was some typing error or just something wrong with the files, but nothing worked.

  • You have a pointer that is null. So your call resembles `null.getApplicationInfo()`. Which will not do. Check for null before use. – blackapps Nov 03 '22 at 17:57

1 Answers1

1

Anything like these lines:

private var bluetoothAdapter: BluetoothAdapter = BluetoothAdapter.getDefaultAdapter()

val selectDeviceList = findViewById<ListView>(R.id.selectorLV)

in an Activity will cause a crash. You cannot call Activity functions safely in property initializers, because the Activity hasn't been set up until onCreate() is called. Property initializers are called before onCreate.

You either need to change these to lateinit and initialize them in onCreate, or you can turn them into Lazy properties -- replace = /*...*/ with by lazy { /*...*/ }.

For future reference, the stack trace gives you the exact line of code that causes the problem. If you have issues in the future that you cannot solve, you need to post the stack trace and the code that is referenced by the stack trace.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154
  • thanks, gonna try to add lateinit to those. this is the logcat results when the app crashes, i didn't add the code cause it doesn't show where is the error as far as i understand it. i think there's something wrong in the intent as the app can't even start the Medir activity, just can't figure out what is it. – Angel Estrada Nov 03 '22 at 20:09
  • this is part of the logcat result i got E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.kotlincalcinsu, PID: 8835 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.kotlincalcinsu/com.example.kotlincalcinsu.Medir}: 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:3914) – Angel Estrada Nov 03 '22 at 20:11
  • I think one of your lines of code above is the source of the problem, but it causes a misdirection, so the exception is thrown in code further up the stack, deep in Android's classes. If you read further down the stack trace, you'll probably find a line beginning with "at" that describes one of the two lines above in your own file. – Tenfour04 Nov 03 '22 at 20:14