Estoy creando una aplicación que genera un número aleatorio entre 1 y 50, pida que el usuario lo adivine e informe si ganó o si el número es mayor o menor al ingresado. Cuando acierte, quiero lanzar una segunda activity que informe que ha acertado pero en el intent la aplicación se cierra. Es decir, la aplicación funciona correctamente hasta que el usuario acierta el número, momento en el que la aplicación se cierra. ¿Qué estoy haciendo mal? Gracias.
MainActivity.kt:
class MainActivity : AppCompatActivity() {
private lateinit var tv2: TextView
private lateinit var tv3: TextView
private lateinit var et1 : EditText
private lateinit var boton1: Button
private var numero: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
tv2 = findViewById(R.id.tv2)
tv3 = findViewById(R.id.tv3)
et1 = findViewById(R.id.et1)
boton1 = findViewById(R.id.boton1)
val preferencias = getSharedPreferences("datos", Context.MODE_PRIVATE)
val v = preferencias.getInt("puntos", 0).toString()
tv2.setText(v)
numero = 1 + (Math.random() * 50).toInt()
val tg = ToneGenerator(AudioManager.STREAM_RING, ToneGenerator.MAX_VOLUME)
boton1.setOnClickListener {
val valor = et1.text.toString().toInt()
if (numero == valor) {
actualizapuntos()
val intent = Intent(this, ResultActivity::class.java)
startActivity(intent)
} else {
tg.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD)
if (valor > numero)
tv3.text = "Ingresó un número mayor al que penso la maquina."
else
tv3.text = "Ingresó un número menor al que penso la maquina."
}
}
}
private fun actualizapuntos() {
...
}
}
ResultActivity.kt
class ResultActivity : AppCompatActivity() {
var btnVolver: Button = findViewById(R.id.btnVolver)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_result)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
btnVolver.setOnClickListener {
onBackPressedDispatcher.onBackPressed()
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<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.PRUEBA"
tools:targetApi="31">
<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>
</activity>
<activity
android:name=".ResultActivity"
android:exported="false" />
</application>
</manifest>
Todos los componentes necesarios están creados en sus correspondientes layouts.
Logcat:
E FATAL EXCEPTION: main (Ask Gemini) Process: com.example.prueba, PID: 21821 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.prueba/com.example.prueba.ResultActivity}: 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:3950) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4203) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:99) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2616) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loopOnce(Looper.java:222) at android.os.Looper.loop(Looper.java:314) at android.app.ActivityThread.main(ActivityThread.java:8716) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:565) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081) 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:217) at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174) at android.content.Context.obtainStyledAttributes(Context.java:1010) at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:898) at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:865) at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:667) at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:264) at com.example.prueba.ResultActivity.(ResultActivity.kt:13) at java.lang.Class.newInstance(Native Method) at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95) at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:44) at android.app.Instrumentation.newActivity(Instrumentation.java:1389) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3934) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4203) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:99) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2616) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loopOnce(Looper.java:222) at android.os.Looper.loop(Looper.java:314) at android.app.ActivityThread.main(ActivityThread.java:8716) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:565) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)