API Call in Android Studio - android

Im new to using android studio and im trying to make a API call in Android Studio using volley. I have set a button to do the API call but when clicked the application crashes. The API im using also uses a key where in its documentation says: "All requests to the API must contain the X-AUTH-TOKEN HTTP header. This header must contain your auth token." I can't really figure out why the application crashes when button is clicked.
private RequestQueue queue;
private JSONArray getText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue = Volley.newRequestQueue(this);
}
private StringRequest searchNameStringRequest(String nameSearch) {
final String API = "&X-AUTH-TOKEN=<<rfrzsucnc7eo3m5hcmq6ljdzda1lz793>>";
final String NAME_SEARCH = "&getText=";
final String URL_PREFIX = "https://v1.motorapi.dk";
String url = URL_PREFIX + API + NAME_SEARCH + nameSearch;
final StringRequest stringRequest;
stringRequest = new StringRequest(Request.Method.GET, url,
response -> {
try {
JSONObject result = new JSONObject(response).getJSONObject("list");
int maxItems = result.getInt("end");
JSONArray resultList = result.getJSONArray("item");
} catch (JSONException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
},
error -> {
Toast.makeText(MainActivity.this, "Motorregister dosen’t answer.”, Toast.LENGTH_LONG).show();
});
return stringRequest;
}
public void button(View view) {
queue.cancelAll(this);
StringRequest stringRequest = searchNameStringRequest(getText.toString());
stringRequest.setTag(this);
queue.add(stringRequest);
}
EDIT here is the crash log:
12/08 18:08:32: Launching 'app' on Pixel C API 29.
Install successfully finished in 1 s 791 ms.
$ adb shell am start -n "com.example.myapplication/com.example.myapplication.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 5893 on device 'Pixel_C_API_29 [emulator-5554]'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
D/libEGL: Emulator has host GPU support, qemu.gles is set to 1.
W/libc: Unable to set property "qemu.gles" to "1": connection failed; errno=13 (Permission denied)
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/RenderThread: type=1400 audit(0.0:19): avc: denied { write } for name="property_service" dev="tmpfs" ino=7291 scontext=u:r:untrusted_app:s0:c147,c256,c512,c768 tcontext=u:object_r:property_socket:s0 tclass=sock_file permissive=0 app=com.example.myapplication
W/e.myapplicatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/e.myapplicatio: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/HostConnection: HostConnection::get() New Host Connection established 0xd5a9e040, tid 5931
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV_Cache ANDROID_EMU_sync_buffer_data GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_3_0
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0xe1113980: maj 3 min 0 rcv 3
D/EGL_emulation: eglMakeCurrent: 0xe1113980: ver 3 0 (tinfo 0xd5ace1d0)
W/Gralloc3: mapper 3.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0xd5a9f850, tid 5931
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV_Cache ANDROID_EMU_sync_buffer_data GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_3_0
D/eglCodecCommon: allocate: Ask for block of size 0x1000
D/eglCodecCommon: allocate: ioctl allocate returned offset 0x3ffff6000 size 0x2000
D/EGL_emulation: eglMakeCurrent: 0xe1113980: ver 3 0 (tinfo 0xd5ace1d0)
I/AssistStructure: Flattened final assist data: 1576 bytes, containing 1 windows, 9 views
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 5893
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:446)
at android.view.View.performClick(View.java:7125)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
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)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:441)
at android.view.View.performClick(View.java:7125) 
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119) 
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) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONArray.toString()' on a null object reference
at com.example.myapplication.MainActivity.button(MainActivity.java:84)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:441) 
at android.view.View.performClick(View.java:7125) 
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119) 
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) 
I/Process: Sending signal. PID: 5893 SIG: 9

Your crash has nothing to do with Volley. Your onclick tries to call getText.toString, but you never set the value of getText so it's a null. You then dereference it. You need to set the value of getText, and you probably need a null check there as well.

Related

When I define a value in my Android script, it gives me an Error

I'm new to Android and Kotlin and wanted to make an App where it ramdomly gives you Teams with random Teammates. I tried storing the names of the players with SharedPreferences and had to define some Values(I don't understand what Values are) but when i define them, it crashes the app.
I know to proplem has to do with the values because if I delete them the App runs fine.
The enterName script
import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
class enterName : AppCompatActivity() {
var namesButton = findViewById<Button>(R.id.button2)
var namesText = findViewById<TextView>(R.id.namesText)
var outputText = findViewById<TextView>(R.id.outputText)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_enter_name)
namesButton.setOnClickListener {
saveData()
}
}
private fun saveData() {
val insertedText = namesText.text.toString()
outputText.text = insertedText
val sharedPreferences = getSharedPreferences("namesPref", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.apply {
putString("namesPref", insertedText)
}.apply()
}
}
The Activity script
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".enterName">
<EditText
android:id="#+id/namesText"
android:layout_width="379dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:ems="10"
android:hint="Enter Player Names"
android:inputType="textPersonName"
android:maxLines="3"
android:minHeight="48dp"
android:singleLine="false"
android:textAlignment="center"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView"
android:layout_width="286dp"
android:layout_height="41dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="#string/separateNames"
android:textAlignment="center"
android:textColor="#5A5A5A"
android:textSize="14sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/namesText" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="NEXT"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
<TextView
android:id="#+id/outputText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="hi"
android:textColor="#000000"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button2" />
</androidx.constraintlayout.widget.ConstraintLayout>
The Error/Log
2022-04-04 19:55:37.994 6997-6997/? I/.teamrandomize: Late-enabling -Xcheck:jni
2022-04-04 19:55:38.000 6997-6997/at.thebuckey_.teamrandomizer E/.teamrandomize: Unknown bits set in runtime_flags: 0x8000
2022-04-04 19:55:37.994 6997-6997/? I/.teamrandomize: Late-enabling -Xcheck:jni
2022-04-04 19:55:38.000 6997-6997/at.thebuckey_.teamrandomizer E/.teamrandomize: Unknown bits set in runtime_flags: 0x8000
2022-04-04 19:55:37.994 6997-6997/? I/.teamrandomize: Late-enabling -Xcheck:jni
2022-04-04 19:55:38.000 6997-6997/at.thebuckey_.teamrandomizer E/.teamrandomize: Unknown bits set in runtime_flags: 0x8000
2022-04-04 19:55:38.122 6997-7031/at.thebuckey_.teamrandomizer D/libEGL: Emulator has host GPU support, qemu.gles is set to 1.
2022-04-04 19:55:38.122 6997-7031/at.thebuckey_.teamrandomizer W/libc: Unable to set property "qemu.gles" to "1": connection failed; errno=13 (Permission denied)
2022-04-04 19:55:38.118 6997-6997/at.thebuckey_.teamrandomizer W/RenderThread: type=1400 audit(0.0:42): avc: denied { write } for name="property_service" dev="tmpfs" ino=6596 scontext=u:r:untrusted_app:s0:c144,c256,c512,c768 tcontext=u:object_r:property_socket:s0 tclass=sock_file permissive=0 app=at.thebuckey_.teamrandomizer
2022-04-04 19:55:38.127 6997-7031/at.thebuckey_.teamrandomizer D/libEGL: loaded /vendor/lib64/egl/libEGL_emulation.so
2022-04-04 19:55:38.128 6997-7031/at.thebuckey_.teamrandomizer D/libEGL: loaded /vendor/lib64/egl/libGLESv1_CM_emulation.so
2022-04-04 19:55:38.129 6997-7031/at.thebuckey_.teamrandomizer D/libEGL: loaded /vendor/lib64/egl/libGLESv2_emulation.so
2022-04-04 19:55:38.153 6997-6997/at.thebuckey_.teamrandomizer W/.teamrandomize: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
2022-04-04 19:55:38.153 6997-6997/at.thebuckey_.teamrandomizer W/.teamrandomize: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
2022-04-04 19:55:38.191 6997-7029/at.thebuckey_.teamrandomizer D/HostConnection: HostConnection::get() New Host Connection established 0x7b23c96400, tid 7029
2022-04-04 19:55:38.193 6997-7029/at.thebuckey_.teamrandomizer D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_sync_buffer_data GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_3_0
2022-04-04 19:55:38.194 6997-7029/at.thebuckey_.teamrandomizer W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2022-04-04 19:55:38.195 6997-7029/at.thebuckey_.teamrandomizer D/EGL_emulation: eglCreateContext: 0x7b23c965e0: maj 3 min 0 rcv 3
2022-04-04 19:55:38.195 6997-7029/at.thebuckey_.teamrandomizer D/EGL_emulation: eglMakeCurrent: 0x7b23c965e0: ver 3 0 (tinfo 0x7b23c18f00)
2022-04-04 19:55:38.203 6997-7029/at.thebuckey_.teamrandomizer W/Gralloc3: mapper 3.x is not supported
2022-04-04 19:55:38.205 6997-7029/at.thebuckey_.teamrandomizer D/HostConnection: createUnique: call
2022-04-04 19:55:38.206 6997-7029/at.thebuckey_.teamrandomizer D/HostConnection: HostConnection::get() New Host Connection established 0x7b23c96720, tid 7029
2022-04-04 19:55:38.206 6997-7029/at.thebuckey_.teamrandomizer D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_sync_buffer_data GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_3_0
2022-04-04 19:55:38.206 6997-7029/at.thebuckey_.teamrandomizer D/eglCodecCommon: allocate: Ask for block of size 0x1000
2022-04-04 19:55:38.207 6997-7029/at.thebuckey_.teamrandomizer D/eglCodecCommon: allocate: ioctl allocate returned offset 0x1fef08000 size 0x8000
2022-04-04 19:55:38.210 6997-7029/at.thebuckey_.teamrandomizer D/EGL_emulation: eglMakeCurrent: 0x7b23c965e0: ver 3 0 (tinfo 0x7b23c18f00)
2022-04-04 19:55:39.253 6997-6997/at.thebuckey_.teamrandomizer I/AssistStructure: Flattened final assist data: 1472 bytes, containing 1 windows, 8 views
2022-04-04 19:55:40.804 6997-6997/at.thebuckey_.teamrandomizer W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy#2616b45
2022-04-04 19:55:40.808 6997-6997/at.thebuckey_.teamrandomizer D/AndroidRuntime: Shutting down VM
2022-04-04 19:55:40.809 6997-6997/at.thebuckey_.teamrandomizer E/AndroidRuntime: FATAL EXCEPTION: main
Process: at.thebuckey_.teamrandomizer, PID: 6997
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{at.thebuckey_.teamrandomizer/at.thebuckey_.teamrandomizer.enterName}: 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:3194)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
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)
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:163)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174)
at android.content.Context.obtainStyledAttributes(Context.java:738)
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 at.thebuckey_.teamrandomizer.enterName.<init>(enterName.kt:12)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1243)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3182)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
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) 
2022-04-04 19:55:40.819 6997-6997/at.thebuckey_.teamrandomizer I/Process: Sending signal. PID: 6997 SIG: 9
I don't know what "Values" you're talking about, but your app is crashing because of this error:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{at.thebuckey_.teamrandomizer/at.thebuckey_.teamrandomizer.enterName}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
which is saying you're trying to call getApplicationInfo() on a Context that's actually null. That's happening because of this:
class enterName : AppCompatActivity() {
var namesButton = findViewById<Button>(R.id.button2)
var namesText = findViewById<TextView>(R.id.namesText)
var outputText = findViewById<TextView>(R.id.outputText)
Calling findViewById in an Activity requires its View hierarchy (so you can find the View you're searching for inside it), and long story short, that call is what's trying to use the Activity's Context. And it doesn't have one at construction time, so the context is null.
You need to do all your view-finding in onCreate or later, at which point you do have a Context (for view lookups, specifically after the view has been created, e.g. with setContentView). Do this instead:
class enterName : AppCompatActivity() {
lateinit var namesButton: Button
lateinit var namesText: TextView
lateinit var outputText: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_enter_name)
namesButton = findViewById<Button>(R.id.button2)
namesText = findViewById<TextView>(R.id.namesText)
outputText = findViewById<TextView>(R.id.outputText)
namesButton.setOnClickListener {
saveData()
}
}
lateinit lets you declare those top-level variables, but init them later (i.e. when you have the Context you need)
With the "Values" thing, when you store data in shared prefs you need a key/value pair - the key is the identifier you use to store a piece of data, the value is the data itself, that's all. You're doing it here:
editor.apply {
putString("namesPref", insertedText)
}.apply()
That's storing insertedText (the value) using the lookup key "namesPref". So you can retrieve that value later with getString("namesPref"). Since that's also the name of your SharedPreferences store I'm guessing you wanted to use a different name for your lookup, but that's the basics of it

How to create intent in a class that inherits from AppCompatActivity class?

I receive InvocationTargetException and IllegalStateException on startActivity(intent).I have tried using getApplicationcontext() to get context but didn't work.I have also tried inheriting from Activity class and passing context using this in Intent constructor.
Following is the code:
package com.example.worldclocktest;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showMessage("Created");
}
private void showMessage(String message) {
Toast toast = Toast.makeText(this, message, Toast.LENGTH_LONG);
toast.show();
}
public void buttonClick(View v)
{
if (v.getId() == R.id.button_list) {
showMessage("buttonClicked");
list_cities();
}
}
public void list_cities()
{
showMessage("city_list");
Intent intent = new Intent(this,ListActivity.class);
startActivity(intent);
}
}
Here is the activity.main.xml code: I call buttonClick() through onClick() in xml file. My app gets stop when I click on the button.When I debug the app it throw exception after startActivity()
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id='#+id/button_list'
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="buttonClick"
android:text="+"
/>
</LinearLayout>
Stack Trace from Logcat:
2021-04-13 19:56:44.365 10618-10618/? I/.worldclocktes: Not late-enabling -Xcheck:jni (already on)
2021-04-13 19:56:44.508 10618-10618/? I/.worldclocktes: Unquickening 12 vdex files!
2021-04-13 19:56:44.510 10618-10618/? W/.worldclocktes: Unexpected CPU variant for X86 using defaults: x86
2021-04-13 19:56:44.671 10618-10618/? D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2021-04-13 19:56:44.672 10618-10618/? D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2021-04-13 19:56:44.691 10618-10642/? D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
2021-04-13 19:56:44.700 10618-10642/? D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
2021-04-13 19:56:44.709 10618-10642/? D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
2021-04-13 19:56:44.963 10618-10618/? W/.worldclocktes: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
2021-04-13 19:56:44.964 10618-10618/? W/.worldclocktes: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
2021-04-13 19:56:45.051 10618-10618/? D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10153; state: ENABLED
2021-04-13 19:56:45.248 10618-10640/com.example.worldclocktest D/HostConnection: HostConnection::get() New Host Connection established 0xe842a630, tid 10640
2021-04-13 19:56:45.269 10618-10640/com.example.worldclocktest D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_2
2021-04-13 19:56:45.359 10618-10640/com.example.worldclocktest W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2021-04-13 19:56:47.508 10618-10640/com.example.worldclocktest D/EGL_emulation: eglCreateContext: 0xe84203e0: maj 2 min 0 rcv 2
2021-04-13 19:56:47.722 10618-10640/com.example.worldclocktest D/EGL_emulation: eglMakeCurrent: 0xe84203e0: ver 2 0 (tinfo 0xe8773730) (first time)
2021-04-13 19:56:47.925 10618-10640/com.example.worldclocktest I/Gralloc4: mapper 4.x is not supported
2021-04-13 19:56:47.932 10618-10640/com.example.worldclocktest D/HostConnection: createUnique: call
2021-04-13 19:56:47.934 10618-10640/com.example.worldclocktest D/HostConnection: HostConnection::get() New Host Connection established 0xe841ff80, tid 10640
2021-04-13 19:56:47.964 10618-10640/com.example.worldclocktest D/goldfish-address-space: allocate: Ask for block of size 0x100
2021-04-13 19:56:47.965 10618-10640/com.example.worldclocktest D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3fbdda000 size 0x2000
2021-04-13 19:56:48.076 10618-10640/com.example.worldclocktest D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_2
2021-04-13 19:56:49.818 10618-10640/com.example.worldclocktest I/OpenGLRenderer: Davey! duration=4717ms; Flags=1, IntendedVsync=11898143064735, Vsync=11898159731401, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=11898171912500, AnimationStart=11898171972000, PerformTraversalsStart=11898172054300, DrawStart=11901127754600, SyncQueued=11901181126200, SyncStart=11901185368400, IssueDrawCommandsStart=11901185452800, SwapBuffers=11902594254400, FrameCompleted=11902864771600, DequeueBufferDuration=1138100, QueueBufferDuration=2256600, GpuCompleted=-2920196950870201425,
2021-04-13 19:56:49.935 10618-10618/com.example.worldclocktest I/Choreographer: Skipped 288 frames! The application may be doing too much work on its main thread.
2021-04-13 19:56:50.017 10618-10640/com.example.worldclocktest I/OpenGLRenderer: Davey! duration=4884ms; Flags=0, IntendedVsync=11898176389049, Vsync=11902976388857, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=11902982657800, AnimationStart=11902982726600, PerformTraversalsStart=11902983338700, DrawStart=11902987117600, SyncQueued=11902988811400, SyncStart=11902991070000, IssueDrawCommandsStart=11902991143600, SwapBuffers=11902993756900, FrameCompleted=11903063537000, DequeueBufferDuration=700400, QueueBufferDuration=3259300, GpuCompleted=-7596402803422855178,
2021-04-13 19:59:19.661 10618-10618/com.example.worldclocktest D/AndroidRuntime: Shutting down VM
2021-04-13 19:59:19.684 10618-10618/com.example.worldclocktest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.worldclocktest, PID: 10618
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
at android.view.View.performClick(View.java:7448)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:7448) 
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119) 
at android.view.View.performClickInternal(View.java:7425) 
at android.view.View.access$3600(View.java:810) 
at android.view.View$PerformClick.run(View.java:28305) 
at android.os.Handler.handleCallback(Handler.java:938) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.worldclocktest/android.app.ListActivity}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2065)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1727)
at android.app.Activity.startActivityForResult(Activity.java:5320)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
at android.app.Activity.startActivityForResult(Activity.java:5278)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
at android.app.Activity.startActivity(Activity.java:5664)
at android.app.Activity.startActivity(Activity.java:5617)
at com.example.worldclocktest.MainActivity.list_cities(MainActivity.java:39)
at com.example.worldclocktest.MainActivity.buttonClick(MainActivity.java:30)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409) 
at android.view.View.performClick(View.java:7448) 
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119) 
at android.view.View.performClickInternal(View.java:7425) 
at android.view.View.access$3600(View.java:810) 
at android.view.View$PerformClick.run(View.java:28305) 
at android.os.Handler.handleCallback(Handler.java:938) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
2021-04-13 19:59:20.632 10618-10618/? I/Process: Sending signal. PID: 10618 SIG: 9
Your issue is:
Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.worldclocktest/android.app.ListActivity}; have you declared this activity in your AndroidManifest.xml?
Just add in your AndroidManifest.xml:
<application>
<activity
android:name=".ListActivity"
android:label="#string/..."
android:theme="#style/..."></activity>
</application>

Cannot get packageManagers or Context to pass to classes on functions that worked fine in main. Kotlin

Listen I looked everywhere. Anything with remotely similiar keywords
on SO and other sites I looked read tried and failed. Ive tried stuff
written in java and Ive tried stuff slightly similiar. For some reason
I am not able to get context to transfer to Classes from main
activity. I read the android docs. I read the guides. The stuff works
when its a function of onCreate on my mainactivity. Anywhere else.
Nothing. Please help me. Im new to android studio but I programmed in
C, and C++ in college. This is much more difficult to me to pick up. I
just need some help
Actual Error Full log at bottom
Running Mininum api 21 AVD at API 30. Java SDK 14.0.2
2020-10-25 15:05:40.555 12534-12534/com.celadian.goodintents E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.celadian.goodintents, PID: 12534
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference
at android.content.ContextWrapper.getPackageManager(ContextWrapper.java:102)
at com.celadian.goodintents.CreateTimer.startTimer(CreateTimer.kt:19)
at com.celadian.goodintents.MainActivity$onCreate$1.onClick(MainActivity.kt:21)
at android.view.View.performClick(View.java:7448)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:967)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
MainActivity.kt
package com.celadian.goodintents
import android.content.Context
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button: Button = findViewById(R.id.home_button_one)
button.setOnClickListener {
println("Button Works")
val newTimer = CreateTimer()
newTimer.startTimer("Test", 3, this.applicationContext)
}
}
companion object {
private var instance: MainActivity? = null
fun applicationContext(): Context {
return instance!!.applicationContext
}
}
}
CreateTimer.kt
package com.celadian.goodintents
import android.app.Application
import android.content.Context
import android.content.Intent
import android.provider.AlarmClock
class CreateTimer: Application(){
fun startTimer(message: String, seconds: Int, context: Context) {
val intent = Intent(AlarmClock.ACTION_SET_TIMER).apply {
putExtra(AlarmClock.EXTRA_MESSAGE, message)
putExtra(AlarmClock.EXTRA_LENGTH, seconds)
putExtra(AlarmClock.EXTRA_SKIP_UI, true)
}
if (intent.resolveActivity(packageManager) != null) {
context.startActivity(intent)
}
}
}
'
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.celadian.goodintents">
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<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/Theme.GoodIntents">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.SET_TIMER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
build.gradle
plugins {
id 'com.android.application'
id 'kotlin-android'
}
android {
compileSdkVersion 29
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.celadian.goodintents"
minSdkVersion 21
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.google.android.material:material:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
LogCat
2020-10-25 15:05:34.639 12534-12534/? I/ian.goodintent: Not late-enabling -Xcheck:jni (already on)
2020-10-25 15:05:34.655 12534-12534/? I/ian.goodintent: Unquickening 12 vdex files!
2020-10-25 15:05:34.656 12534-12534/? W/ian.goodintent: Unexpected CPU variant for X86 using defaults: x86
2020-10-25 15:05:34.828 12534-12534/com.celadian.goodintents D/ApplicationLoaders: Returning zygote-cached class loader: /system/framework/android.test.base.jar
2020-10-25 15:05:35.073 12534-12534/com.celadian.goodintents D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2020-10-25 15:05:35.075 12534-12534/com.celadian.goodintents D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2020-10-25 15:05:35.104 12534-12559/com.celadian.goodintents D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
2020-10-25 15:05:35.105 12534-12559/com.celadian.goodintents D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
2020-10-25 15:05:35.121 12534-12559/com.celadian.goodintents D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
2020-10-25 15:05:35.673 12534-12534/com.celadian.goodintents W/ian.goodintent: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
2020-10-25 15:05:35.674 12534-12534/com.celadian.goodintents W/ian.goodintent: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
2020-10-25 15:05:36.061 12534-12557/com.celadian.goodintents D/HostConnection: HostConnection::get() New Host Connection established 0xd6145330, tid 12557
2020-10-25 15:05:36.080 12534-12557/com.celadian.goodintents D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0
2020-10-25 15:05:36.085 12534-12557/com.celadian.goodintents W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2020-10-25 15:05:36.134 12534-12557/com.celadian.goodintents D/EGL_emulation: eglCreateContext: 0xd6145e20: maj 3 min 0 rcv 3
2020-10-25 15:05:36.360 12534-12557/com.celadian.goodintents D/EGL_emulation: eglMakeCurrent: 0xd6145e20: ver 3 0 (tinfo 0xd5fc34b0) (first time)
2020-10-25 15:05:36.402 12534-12557/com.celadian.goodintents I/Gralloc4: mapper 4.x is not supported
2020-10-25 15:05:36.407 12534-12557/com.celadian.goodintents D/HostConnection: createUnique: call
2020-10-25 15:05:36.408 12534-12557/com.celadian.goodintents D/HostConnection: HostConnection::get() New Host Connection established 0xd6145800, tid 12557
2020-10-25 15:05:36.409 12534-12557/com.celadian.goodintents D/goldfish-address-space: allocate: Ask for block of size 0x100
2020-10-25 15:05:36.409 12534-12557/com.celadian.goodintents D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3f8d7f000 size 0x2000
2020-10-25 15:05:36.435 12534-12557/com.celadian.goodintents D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0
2020-10-25 15:05:36.609 12534-12534/com.celadian.goodintents I/Choreographer: Skipped 36 frames! The application may be doing too much work on its main thread.
2020-10-25 15:05:40.551 12534-12534/com.celadian.goodintents I/System.out: Button Works
2020-10-25 15:05:40.552 12534-12534/com.celadian.goodintents D/AndroidRuntime: Shutting down VM
2020-10-25 15:05:40.555 12534-12534/com.celadian.goodintents E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.celadian.goodintents, PID: 12534
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference
at android.content.ContextWrapper.getPackageManager(ContextWrapper.java:102)
at com.celadian.goodintents.CreateTimer.startTimer(CreateTimer.kt:19)
at com.celadian.goodintents.MainActivity$onCreate$1.onClick(MainActivity.kt:21)
at android.view.View.performClick(View.java:7448)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:967)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Try this:
CreateTimer.kt
package com.celadian.goodintents
import android.app.Application
import android.content.Context
import android.content.Intent
import android.provider.AlarmClock
class CreateTimer: Application() {
fun startTimer(message: String, seconds: Int, context: Context) {
val intent = Intent(AlarmClock.ACTION_SET_TIMER).apply {
putExtra(AlarmClock.EXTRA_MESSAGE, message)
putExtra(AlarmClock.EXTRA_LENGTH, seconds)
putExtra(AlarmClock.EXTRA_SKIP_UI, true)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
if (intent.resolveActivity(context.packageManager) != null) {
context.startActivity(intent)
}
}
}
I tested on my local machine and it triggers alarm without error.
Explanation
on startTimer, We got external context as parameter.
because of overseas startActivity invoking, all we have to do are add Intent.FLAG_ACTIVITY_NEW_TASK flag and using context's packageManager object.

Android App OKHTTP Websocket onFailure() connection close when Switch.setChecked(true) called

I am developing a websocket app in android studio emulator, and apparently everything works fine, until the program execute "Switch.setChecked(true)".
When program execute "Switch.setChecked(true)", the "public void onFailure(WebSocket webSocket, Throwable t, Response response)" method are called and connection close.
I thought it was some recursion problem in the listener, but if the "onCheckedChanged()" function inside listener doesn't have any code, the problem still persists.
NOTE:
I am using https/wss.
The secure websocket server it's being programmed by me in esp32.
Thank's for the help.
private Switch lampSwitch;
protected void onCreate(Bundle savedInstanceState)
{
...
lampSwitch = (Switch) findViewById(R.id.lampSwitch);
lampSwitch.setOnCheckedChangeListener(new lampSwitchListener());
...
}
private static final String TAG = "FragmentActivity";
private String sendValue;
private class lampSwitchListener implements CompoundButton.OnCheckedChangeListener
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
Log.d(TAG, "onCheckedChanged: test");
if (isChecked)
{
sendValue = "{\"lamp\":\"ON\"}";
}
else
{
sendValue = "{\"lamp\":\"OFF\"}";
}
send_Ws_Message(2, sendValue);
}
}
private void process_Message( ByteString input )
{
ByteString b = input.substring(1); // offset 1 position.
String message = b.utf8(); // convert from ByteString to String.
Log.d("MSG: ", message);
Log.d("length: ", String.valueOf(message.length() ) );
JSONObject jObject = null;
try
{
jObject = new JSONObject(message);
} catch (JSONException e) {
e.printStackTrace();
}
String lamp = null;
try
{
lamp = jObject.getString("lamp");
} catch (JSONException e) {
e.printStackTrace();
}
if ( lamp.equals("ON") )
{
Log.d("lamp: ", lamp);
Log.d("lamp.length: ", String.valueOf(lamp.length() ));
lampSwitch.setChecked(true); // this code line close client websocket connection
}
}
Logcat:
2020-10-03 00:37:44.898 6218-6218/? I/mple.myfirstap: Not late-enabling -Xcheck:jni (already on)
2020-10-03 00:37:44.914 6218-6218/? I/mple.myfirstap: Unquickening 12 vdex files!
2020-10-03 00:37:44.915 6218-6218/? W/mple.myfirstap: Unexpected CPU variant for X86 using defaults: x86
2020-10-03 00:37:45.070 6218-6218/com.example.myfirstapp D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
2020-10-03 00:37:45.072 6218-6218/com.example.myfirstapp D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
2020-10-03 00:37:45.082 6218-6243/com.example.myfirstapp D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
2020-10-03 00:37:45.088 6218-6243/com.example.myfirstapp D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
2020-10-03 00:37:45.092 6218-6243/com.example.myfirstapp D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
2020-10-03 00:37:45.201 6218-6218/com.example.myfirstapp W/mple.myfirstap: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
2020-10-03 00:37:45.201 6218-6218/com.example.myfirstapp W/mple.myfirstap: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
2020-10-03 00:37:45.295 6218-6241/com.example.myfirstapp D/HostConnection: HostConnection::get() New Host Connection established 0xee254710, tid 6241
2020-10-03 00:37:45.299 6218-6241/com.example.myfirstapp D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0
2020-10-03 00:37:45.301 6218-6241/com.example.myfirstapp W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2020-10-03 00:37:45.306 6218-6241/com.example.myfirstapp D/EGL_emulation: eglCreateContext: 0xee064eb0: maj 3 min 0 rcv 3
2020-10-03 00:37:45.323 6218-6241/com.example.myfirstapp D/EGL_emulation: eglMakeCurrent: 0xee064eb0: ver 3 0 (tinfo 0xee3b5630) (first time)
2020-10-03 00:37:45.343 6218-6241/com.example.myfirstapp I/Gralloc4: mapper 4.x is not supported
2020-10-03 00:37:45.344 6218-6241/com.example.myfirstapp D/HostConnection: createUnique: call
2020-10-03 00:37:45.344 6218-6241/com.example.myfirstapp D/HostConnection: HostConnection::get() New Host Connection established 0xee253ed0, tid 6241
2020-10-03 00:37:45.369 6218-6241/com.example.myfirstapp D/goldfish-address-space: allocate: Ask for block of size 0x100
2020-10-03 00:37:45.369 6218-6241/com.example.myfirstapp D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3fc7ba000 size 0x2000
2020-10-03 00:37:45.375 6218-6241/com.example.myfirstapp D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0
2020-10-03 00:37:47.795 6218-6218/com.example.myfirstapp W/mple.myfirstap: Accessing hidden method Landroid/graphics/FontFamily;-><init>()V (greylist-max-q, reflection, denied)
2020-10-03 00:37:47.797 6218-6218/com.example.myfirstapp E/TypefaceCompatApi26Impl: Unable to collect necessary methods for class java.lang.NoSuchMethodException
java.lang.NoSuchMethodException: android.graphics.FontFamily.<init> []
at java.lang.Class.getConstructor0(Class.java:2332)
at java.lang.Class.getConstructor(Class.java:1728)
at androidx.core.graphics.TypefaceCompatApi26Impl.obtainFontFamilyCtor(TypefaceCompatApi26Impl.java:321)
at androidx.core.graphics.TypefaceCompatApi26Impl.<init>(TypefaceCompatApi26Impl.java:84)
at androidx.core.graphics.TypefaceCompatApi28Impl.<init>(TypefaceCompatApi28Impl.java:36)
at androidx.core.graphics.TypefaceCompat.<clinit>(TypefaceCompat.java:47)
at androidx.core.graphics.TypefaceCompat.create(TypefaceCompat.java:190)
at androidx.appcompat.widget.AppCompatTextView.setTypeface(AppCompatTextView.java:705)
at android.widget.TextView.resolveStyleAndSetTypeface(TextView.java:2183)
at android.widget.TextView.setTypefaceFromAttrs(TextView.java:2154)
at android.widget.TextView.applyTextAppearance(TextView.java:4105)
at android.widget.TextView.<init>(TextView.java:1630)
at android.widget.TextView.<init>(TextView.java:990)
at androidx.appcompat.widget.AppCompatTextView.<init>(AppCompatTextView.java:99)
at androidx.appcompat.widget.AppCompatTextView.<init>(AppCompatTextView.java:95)
at androidx.appcompat.app.AppCompatViewInflater.createTextView(AppCompatViewInflater.java:182)
at androidx.appcompat.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:103)
at androidx.appcompat.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1407)
at androidx.appcompat.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1457)
at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1059)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:995)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1121)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:555)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:161)
at com.example.myfirstapp.DisplayMessageActivity.onCreate(DisplayMessageActivity.java:163)
at android.app.Activity.performCreate(Activity.java:7995)
at android.app.Activity.performCreate(Activity.java:7979)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2020-10-03 00:37:49.599 6218-6251/com.example.myfirstapp D/FragmentActivity: onFailure: caca
The problem was solved with:
runOnUiThread(new Runnable()
{
#Override
public void run()
{
lampSwitch.setOnCheckedChangeListener( null );
lampSwitch.setChecked(true);
lampSwitch.setOnCheckedChangeListener(new lampSwitchListener());
}
});
The strange thing is that only the Switch widget needs it, the SeekBar widget didn’t, but I used "runOnUiThread" anyway in SeekBar too.
By the tests i did, the problem is not related with the OkHttp lib.
I have a seekbBar on my app too and i tested with only the seekBar and worked.
slider = (SeekBar) findViewById(R.id.slider);
slider.setOnSeekBarChangeListener(new sliderListener());
I found that Switch in this way it works correctly, ie: change the Switch state on screen.
#Override
protected void onCreate(Bundle savedInstanceState)
{
...
lampSwitch = (Switch) findViewById(R.id.lampSwitch);
lampSwitch.setChecked(true);
lampSwitch.setOnCheckedChangeListener(new lampSwitchListener());
...
I found that Switch in this way crash the app, ie: app close.
#Override
protected void onCreate(Bundle savedInstanceState)
{
...
lampSwitch = (Switch) findViewById(R.id.lampSwitch);
lampSwitch.setOnCheckedChangeListener(new lampSwitchListener());
lampSwitch.setChecked(true);
...
I already tryied the code below but not worked too.
Here the websocket connection close and the Switch state on screen don't change.
I tested with another Switch in the app and the same behavior.
if ( lamp.equals("ON") )
{
Log.d("lamp: ", lamp);
Log.d("lamp.length: ", String.valueOf(lamp.length() ) );
lampSwitch.setOnCheckedChangeListener( null );
lampSwitch.setChecked(true);
lampSwitch.setOnCheckedChangeListener(new lampSwitchListener());
}
Any suggestion is very welcome.

Volley is not calling onResponse or onErrorResponse methods

Volley is not entering into onResponse or onErrorResponse methods in debug and normal run mode.
Last log is:
Request is: https://www.google.com/
This is my MainActivity.class:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String urlGoogle = "https://www.google.com/";
Log.println(Log.INFO, null, "Request is: " + urlGoogle);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, urlGoogle, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.println(Log.INFO, null, "Response is: " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.println(Log.INFO, null, "Error response is: " + error.toString());
}
});
}
});
}
}
Internet permission is set:
<uses-permission android:name="android.permission.INTERNET" />
Gradle implementation:
implementation group: 'com.android.volley', name: 'volley', version: '1.1.1'
Logs:
04/13 12:50:39: Launching 'app' on Nexus 5X API 29 x86.
$ adb shell am start -n "com.example.myapplication/com.example.myapplication.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 30116 on device 'Nexus_5X_API_29_x86 [emulator-5554]'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
D/libEGL: Emulator has host GPU support, qemu.gles is set to 1.
W/libc: Unable to set property "qemu.gles" to "1": connection failed; errno=13 (Permission denied)
W/RenderThread: type=1400 audit(0.0:380): avc: denied { write } for name="property_service" dev="tmpfs" ino=8370 scontext=u:r:untrusted_app:s0:c137,c256,c512,c768 tcontext=u:object_r:property_socket:s0 tclass=sock_file permissive=0 app=com.example.myapplication
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/e.myapplicatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/e.myapplicatio: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/HostConnection: HostConnection::get() New Host Connection established 0xe0e3cfa0, tid 30149
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_1
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0xec56ad20: maj 3 min 1 rcv 4
D/EGL_emulation: eglMakeCurrent: 0xec56ad20: ver 3 1 (tinfo 0xec609c20)
E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
glUtilsParamSize: unknow param 0x000082da
W/Gralloc3: mapper 3.x is not supported
D/HostConnection: createUnique: call
HostConnection::get() New Host Connection established 0xe0e3e710, tid 30149
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_1
D/eglCodecCommon: allocate: Ask for block of size 0x1000
allocate: ioctl allocate returned offset 0x3ff803000 size 0x2000
D/EGL_emulation: eglMakeCurrent: 0xec56ad20: ver 3 1 (tinfo 0xec609c20)
I/: Request is: https://www.google.com/
EDIT:
I tested with sites that returns jsons.
For example: http://ip.jsontest.com/
EDIT2:
I switched device with different network and it's the same.
EDIT3:
I downgraded volley for 1.0.0 version. No changes.
You are just creating an object of JsonObjectRequest but not executing it, to execute the request you need to add it to the request queue-
Add these two lines after initializing the JsonObjectRequest-
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jsonObjectRequest);

Categories

Resources