Could not find a method sendMessage(View) in the activity class

好久不见. 提交于 2019-11-29 12:59:16

I was struggling with a similar error following the android tutorial

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.myfirstapp, PID: 18300
              java.lang.IllegalStateException: Could not find method sendMessage (MainActivity)(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button'
                  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
                  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
                  at android.view.View.performClick(View.java:5197)
                  at android.view.View$PerformClick.run(View.java:20909)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:145)
                  at android.app.ActivityThread.main(ActivityThread.java:5944)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:372)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

but in my case the WYSIWYG editor (IntelliJ w/Android Studio plugin) ended up populating the onClick property in activity_main.xml with some extra junk about MainActivity:

android:onClick="sendMessage (MainActivity)"

So I deleted " (MainActivity)" and it stopped crashing. I see this is different from your problem as your xml file already seems correct with android:onClick="sendMessage". But wanted to add it here for any others struggling with what I saw. This was the closest post to the issue I was seeing. I'm just getting started and this was killing me, so hope it helps someone else.

The problem is the onClick property in one of your Button tags:

    android:onClick="sendMessage" />

Just make sure you have a method sendMessage(View) in your Activity.

It is because you need to implement implements android.view.View.OnClickListener in your class, therefore add the correct imports i.e. import android.view.View.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!