I tried creating a simple room database in kotlin. The code seems to work just fine but i can't manage to show the list of the items i added in the recycler view.
Here is my main fragment :
package com.ebookfrenzy.roomdemo.ui.main
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import com.ebookfrenzy.roomdemo.ProductRepository
import com.ebookfrenzy.roomdemo.MainActivity
import com.ebookfrenzy.roomdemo.ProductDao
import com.ebookfrenzy.roomdemo.ui.main.ProductListAdapter
import android.view.ViewGroup
import com.ebookfrenzy.roomdemo.R
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.ebookfrenzy.roomdemo.Product
import androidx.fragment.app.viewModels
import java.util.*
import com.ebookfrenzy.roomdemo.databinding.FragmentMainBinding
//preparation du main fragment
class MainFragment : Fragment() {
private var adapter: ProductListAdapter? = null
companion object {
fun newInstance() = MainFragment()
}
val viewModel: MainViewModel by viewModels()
private var _binding: FragmentMainBinding? = null
private val binding get() = _binding!!
// si ya une erreur c'est ici
private fun recyclerSetup(){
adapter = ProductListAdapter(R.layout.product_list_item)
binding.recyclerView.layoutManager = LinearLayoutManager(context)
binding.recyclerView.adapter = adapter
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMainBinding.inflate(inflater, container, false)
return binding.root
}
#Deprecated("Deprecated in Java")
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
listenerSetup()
observerSetup()
recyclerSetup()
}
private fun clearFields() {
binding.productID.text = ""
binding.productName.setText("")
binding.productQuantity.setText("")
}
//ajout de bouton listeners
private fun listenerSetup() {
binding.addButton.setOnClickListener {
val name = binding.productName.text.toString()
val quantity = binding.productQuantity.text.toString()
if (name != "" && quantity != "") {
val product = Product(name, Integer.parseInt(quantity))
viewModel.insertProduct(product)
clearFields()
} else {
binding.productID.text = " Infos Incompletes "
}
}
binding.findButton.setOnClickListener {
viewModel.findProduct(binding.productName.text.toString())
}
binding.deleteButton.setOnClickListener {
viewModel.deleteProduct(
binding.productName.text.toString()
)
clearFields()
}
}
private fun observerSetup() {
viewModel.getAllProducts()
?.observe(viewLifecycleOwner, Observer { products -> products?.let { adapter?.setProductList(it) } })
viewModel.getSearchResults().observe(viewLifecycleOwner, Observer { products ->
products?.let {
if(it.isNotEmpty()){
binding.productID.text = String .format(Locale.US, "%d", it[0].id)
binding.productName.setText(it[0].productName)
binding.productQuantity.setText(String.format(Locale.US,"%d",it[0].quantity))
}
else {
binding.productID.text = "No Match"
}
}
})
}
}
Here is my adapter :
package com.ebookfrenzy.roomdemo.ui.main
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewParent
import android.widget.TextView
import androidx.appcompat.view.menu.MenuView.ItemView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.ebookfrenzy.roomdemo.Product
import com.ebookfrenzy.roomdemo.R
class ProductListAdapter(private val productItemLayout: Int): RecyclerView.Adapter<ProductListAdapter.ViewHolder>() {
private var productList : List<Product>? = null
override fun onBindViewHolder(holder: ViewHolder, listPosition:Int){
val item = holder.item
productList.let {
item.text = it!![listPosition].productName
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType:Int):ViewHolder{
val view = LayoutInflater.from(parent.context).inflate(productItemLayout, parent, false )
return ViewHolder(view)
}
fun setProductList(products : List<Product>){
productList = products
notifyDataSetChanged()
}
override fun getItemCount(): Int {
return if (productList==null) 0 else productList!!.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
var item : TextView = itemView.findViewById(R.id.product_row)
}
}
Here is the design of the main fragment xml :
vs what it shows in the emulator :
Finally, here is the logcat :
2023-02-06 13:33:13.886 5565-5565/? I/frenzy.roomdemo: Late-enabling -Xcheck:jni
2023-02-06 13:33:13.924 5565-5565/? W/frenzy.roomdemo: Unexpected CPU variant for x86: x86_64.
Known variants: atom, sandybridge, silvermont, kabylake, default
2023-02-06 13:33:14.005 5565-5565/? V/studio.deploy: Startup agent attached to VM
2023-02-06 13:33:13.992 5565-5565/? W/re-initialized>: type=1400 audit(0.0:27): avc: granted { execute } for path="/data/data/com.ebookfrenzy.roomdemo/code_cache/startup_agents/69880af5-agent.so" dev="dm-33" ino=148166 scontext=u:r:untrusted_app:s0:c161,c256,c512,c768 tcontext=u:object_r:app_data_file:s0:c161,c256,c512,c768 tclass=file app=com.ebookfrenzy.roomdemo
2023-02-06 13:33:14.006 5565-5565/? V/studio.deploy: No existing instrumentation found. Loading instrumentation from instruments-6b5afa68.jar
2023-02-06 13:33:14.014 5565-5565/? W/frenzy.roomdemo: DexFile /data/data/com.ebookfrenzy.roomdemo/code_cache/.studio/instruments-6b5afa68.jar is in boot class path but is not in a known location
2023-02-06 13:33:14.018 5565-5565/? V/studio.deploy: Applying transforms with cached classes
2023-02-06 13:33:14.040 5565-5565/com.ebookfrenzy.roomdemo W/frenzy.roomdemo: Redefining intrinsic method java.lang.Thread java.lang.Thread.currentThread(). This may cause the unexpected use of the original definition of java.lang.Thread java.lang.Thread.currentThread()in methods that have already been compiled.
2023-02-06 13:33:14.040 5565-5565/com.ebookfrenzy.roomdemo W/frenzy.roomdemo: Redefining intrinsic method boolean java.lang.Thread.interrupted(). This may cause the unexpected use of the original definition of boolean java.lang.Thread.interrupted()in methods that have already been compiled.
2023-02-06 13:33:14.045 5565-5565/com.ebookfrenzy.roomdemo D/CompatibilityChangeReporter: Compat change id reported: 171979766; UID 10161; state: ENABLED
2023-02-06 13:33:14.061 5565-5565/com.ebookfrenzy.roomdemo W/ziparchive: Unable to open '/data/app/~~KuAqymfHPelK0HgMzmVTcw==/com.ebookfrenzy.roomdemo-Bh69_2PWAZtOQ6sAIZ3H0g==/base.dm': No such file or directory
2023-02-06 13:33:14.061 5565-5565/com.ebookfrenzy.roomdemo W/ziparchive: Unable to open '/data/app/~~KuAqymfHPelK0HgMzmVTcw==/com.ebookfrenzy.roomdemo-Bh69_2PWAZtOQ6sAIZ3H0g==/base.dm': No such file or directory
2023-02-06 13:33:14.203 5565-5565/com.ebookfrenzy.roomdemo V/GraphicsEnvironment: ANGLE Developer option for 'com.ebookfrenzy.roomdemo' set to: 'default'
2023-02-06 13:33:14.204 5565-5565/com.ebookfrenzy.roomdemo V/GraphicsEnvironment: ANGLE GameManagerService for com.ebookfrenzy.roomdemo: false
2023-02-06 13:33:14.204 5565-5565/com.ebookfrenzy.roomdemo V/GraphicsEnvironment: Neither updatable production driver nor prerelease driver is supported.
2023-02-06 13:33:14.210 5565-5565/com.ebookfrenzy.roomdemo D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2023-02-06 13:33:14.210 5565-5565/com.ebookfrenzy.roomdemo D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2023-02-06 13:33:14.248 5565-5593/com.ebookfrenzy.roomdemo D/libEGL: loaded /vendor/lib64/egl/libEGL_emulation.so
2023-02-06 13:33:14.252 5565-5593/com.ebookfrenzy.roomdemo D/libEGL: loaded /vendor/lib64/egl/libGLESv1_CM_emulation.so
2023-02-06 13:33:14.258 5565-5593/com.ebookfrenzy.roomdemo D/libEGL: loaded /vendor/lib64/egl/libGLESv2_emulation.so
2023-02-06 13:33:14.444 5565-5565/com.ebookfrenzy.roomdemo W/frenzy.roomdemo: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (unsupported, reflection, allowed)
2023-02-06 13:33:14.445 5565-5565/com.ebookfrenzy.roomdemo W/frenzy.roomdemo: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (unsupported, reflection, allowed)
2023-02-06 13:33:14.449 5565-5565/com.ebookfrenzy.roomdemo D/CompatibilityChangeReporter: Compat change id reported: 210923482; UID 10161; state: DISABLED
2023-02-06 13:33:14.449 5565-5565/com.ebookfrenzy.roomdemo D/CompatibilityChangeReporter: Compat change id reported: 37756858; UID 10161; state: ENABLED
2023-02-06 13:33:14.777 5565-5591/com.ebookfrenzy.roomdemo D/HostConnection: createUnique: call
2023-02-06 13:33:14.778 5565-5591/com.ebookfrenzy.roomdemo D/HostConnection: HostConnection::get() New Host Connection established 0x750c54ed0e10, tid 5591
2023-02-06 13:33:14.782 5565-5591/com.ebookfrenzy.roomdemo 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_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma ANDROID_EMU_hwc_multi_configs GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_2
2023-02-06 13:33:14.786 5565-5591/com.ebookfrenzy.roomdemo W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2023-02-06 13:33:14.787 5565-5591/com.ebookfrenzy.roomdemo W/OpenGLRenderer: Failed to initialize 101010-2 format, error = EGL_SUCCESS
2023-02-06 13:33:14.793 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: eglCreateContext: 0x750c54ed1f50: maj 2 min 0 rcv 2
2023-02-06 13:33:14.817 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: eglMakeCurrent: 0x750c54ed1f50: ver 2 0 (tinfo 0x750e7ba74080) (first time)
2023-02-06 13:33:14.827 5565-5591/com.ebookfrenzy.roomdemo I/Gralloc4: mapper 4.x is not supported
2023-02-06 13:33:14.827 5565-5591/com.ebookfrenzy.roomdemo D/HostConnection: createUnique: call
2023-02-06 13:33:14.828 5565-5591/com.ebookfrenzy.roomdemo D/HostConnection: HostConnection::get() New Host Connection established 0x750c54ed2b50, tid 5591
2023-02-06 13:33:14.828 5565-5591/com.ebookfrenzy.roomdemo D/goldfish-address-space: allocate: Ask for block of size 0x100
2023-02-06 13:33:14.828 5565-5591/com.ebookfrenzy.roomdemo D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3f3ffe000 size 0x2000
2023-02-06 13:33:14.830 5565-5591/com.ebookfrenzy.roomdemo W/Gralloc4: allocator 4.x is not supported
2023-02-06 13:33:14.835 5565-5591/com.ebookfrenzy.roomdemo 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_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma ANDROID_EMU_hwc_multi_configs GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_2
2023-02-06 13:33:14.868 5565-5591/com.ebookfrenzy.roomdemo W/Parcel: Expecting binder but got null!
2023-02-06 13:33:24.302 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: app_time_stats: avg=1037.81ms min=1.98ms max=9269.97ms count=9
2023-02-06 13:33:24.456 5565-5565/com.ebookfrenzy.roomdemo D/CompatibilityChangeReporter: Compat change id reported: 163400105; UID 10161; state: ENABLED
2023-02-06 13:33:24.457 5565-5565/com.ebookfrenzy.roomdemo D/InputMethodManager: showSoftInput() view=androidx.appcompat.widget.AppCompatEditText{b0f2ed6 VFED..CL. .F.P..ID 373,0-953,124 #7f080153 app:id/productName aid=1073741824} flags=0 reason=SHOW_SOFT_INPUT
2023-02-06 13:33:24.472 5565-5565/com.ebookfrenzy.roomdemo I/AssistStructure: Flattened final assist data: 2804 bytes, containing 1 windows, 17 views
2023-02-06 13:33:24.505 5565-5565/com.ebookfrenzy.roomdemo W/OnBackInvokedCallback: OnBackInvokedCallback is not enabled for the application.
Set 'android:enableOnBackInvokedCallback="true"' in the application manifest.
2023-02-06 13:33:24.549 5565-5565/com.ebookfrenzy.roomdemo D/InsetsController: show(ime(), fromIme=true)
2023-02-06 13:33:25.358 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: app_time_stats: avg=211.10ms min=20.19ms max=410.23ms count=5
2023-02-06 13:33:26.385 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: app_time_stats: avg=171.04ms min=19.31ms max=492.61ms count=6
2023-02-06 13:33:27.180 5565-5565/com.ebookfrenzy.roomdemo D/InputMethodManager: showSoftInput() view=androidx.appcompat.widget.AppCompatEditText{eaf0844 VFED..CL. .F.P..ID 373,0-953,124 #7f080154 app:id/productQuantity aid=1073741825} flags=0 reason=SHOW_SOFT_INPUT
2023-02-06 13:33:27.203 5565-5565/com.ebookfrenzy.roomdemo W/OnBackInvokedCallback: OnBackInvokedCallback is not enabled for the application.
Set 'android:enableOnBackInvokedCallback="true"' in the application manifest.
2023-02-06 13:33:27.207 5565-5565/com.ebookfrenzy.roomdemo D/InsetsController: show(ime(), fromIme=true)
2023-02-06 13:33:27.207 5565-5565/com.ebookfrenzy.roomdemo D/InsetsController: show(ime(), fromIme=true)
2023-02-06 13:33:27.687 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: app_time_stats: avg=216.73ms min=17.56ms max=500.45ms count=6
2023-02-06 13:33:28.701 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: app_time_stats: avg=506.88ms min=499.29ms max=514.47ms count=2
2023-02-06 13:33:29.486 5565-5565/com.ebookfrenzy.roomdemo D/InsetsController: show(ime(), fromIme=true)
2023-02-06 13:33:29.706 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: app_time_stats: avg=43.48ms min=8.22ms max=500.77ms count=23
2023-02-06 13:33:30.970 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: app_time_stats: avg=38.23ms min=12.95ms max=500.55ms count=33
2023-02-06 13:33:32.321 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: app_time_stats: avg=450.48ms min=352.90ms max=500.27ms count=3
2023-02-06 13:33:32.347 5565-5565/com.ebookfrenzy.roomdemo W/OnBackInvokedCallback: OnBackInvokedCallback is not enabled for the application.
Set 'android:enableOnBackInvokedCallback="true"' in the application manifest.
2023-02-06 13:33:32.347 5565-5565/com.ebookfrenzy.roomdemo D/InsetsController: show(ime(), fromIme=true)
2023-02-06 13:33:35.122 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: app_time_stats: avg=1400.40ms min=34.21ms max=2766.59ms count=2
All my code is in kotlin, i saw that there was a topic of someone that had the same problem, but i couldn't manage to get it right.
EDIT : i followed a tutorial from a book, here is the part of the observerSetup() :
ps : instead of viewLifecycleOwner in the observer function, the book replaces it by "this" except that when i write "this", android studio reports it as an error and suggests to replace it by lifeCycleOwner
Thanks a lot for your time !
I think your issue is because you call observerSetup() before recyclerSetup(). recyclerSetup is where you set adapter, right? But in observerSetup you do this:
viewModel.getAllProducts()
?.observe(viewLifecycleOwner, Observer { products ->
// requires adapter to be set!
products?.let { adapter?.setProductList(it) }
})
If the LiveData that getAllProducts() returns already has a value, then it will immediately call adapter?.setProductList(it) - and since you haven't assigned adapter yet, nothing will happen because it's still null. And if that LiveData doesn't update again after you assign adapter, it will never refresh the display.
Without seeing the rest of your code I can't say for sure, but I'd check that first. The easiest thing to do is debug the app and set some breakpoints in recyclerSetup and your observer lambda, or just add some logging statements. Then you can see exactly what gets called first and if the order will cause you problems!
you need to assign your data to adapter so add
adapter.setProductList(products)
after getting your products
replace products with your array name
You need to call 'setProductList'. It is unused for now.
Related
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
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>
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.
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 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);