代码错误:java.lang.IllegalStateException:无法执行 android:onClick 的方法

Error in code: java.lang.IllegalStateException: Could not execute method for android:onClick

我做了一个 android 项目,它将启动一个加速度计传感器,并将传感器的 x、y、z 数据存储在一个文件中。我在方法 start 中添加了 start.setEnabled(false)stop.setEnabled(true) 行代码,此后我的代码在 start 处崩溃。错误如下: </p> <pre><code>E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.zhenga1.photojewel, PID: 27298 java.lang.IllegalStateException: Could not execute method for android:onClick at android.view.View$DeclaredOnClickListener.onClick(View.java:4507) at android.view.View.performClick(View.java:5267) at android.view.View$PerformClick.run(View.java:21540) at android.os.Handler.handleCallback(Handler.java:815) at android.os.Handler.dispatchMessage(Handler.java:104) at android.os.Looper.loop(Looper.java:207) at android.app.ActivityThread.main(ActivityThread.java:5710) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at android.view.View$DeclaredOnClickListener.onClick(View.java:4502) at android.view.View.performClick(View.java:5267)  at android.view.View$PerformClick.run(View.java:21540)  at android.os.Handler.handleCallback(Handler.java:815)  at android.os.Handler.dispatchMessage(Handler.java:104)  at android.os.Looper.loop(Looper.java:207)  at android.app.ActivityThread.main(ActivityThread.java:5710)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference at com.example.zhenga1.photojewel.Main3Activity.start(Main3Activity.java:120) at java.lang.reflect.Method.invoke(Native Method)  at android.view.View$DeclaredOnClickListener.onClick(View.java:4502)  at android.view.View.performClick(View.java:5267)  at android.view.View$PerformClick.run(View.java:21540)  at android.os.Handler.handleCallback(Handler.java:815)  at android.os.Handler.dispatchMessage(Handler.java:104)  at android.os.Looper.loop(Looper.java:207)  at android.app.ActivityThread.main(ActivityThread.java:5710)  at java.lang.reflect.Method.invoke(Native Method) 

更新:这是我的 .xml 主布局文件: </p> <pre><code><?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="16dp" android:paddingLeft="16dp" android:paddingRight="16dp" android:paddingTop="16dp" tools:context="com.example.zhenga1.photojewel.MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start Accelerometer" android:id="@+id/button" android:onClick="start" android:layout_marginTop="300dp" android:layout_marginStart="0dp" android:layout_marginLeft="0dp" android:textStyle="normal" android:textSize="6pt"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="End Accelerometer" android:onClick="end" android:id="@+id/button2" android:layout_alignParentRight="true" android:layout_marginTop="300dp" android:textStyle="normal" android:textSize="6pt"/> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView2" android:layout_marginTop="200dp" android:layout_marginLeft="150dp" android:src="@mipmap/vibrator_pic"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="Medium Text" android:id="@+id/textView" android:layout_alignParentBottom="true" android:layout_marginTop="600dp" android:layout_marginLeft="0dp" android:layout_marginStart="0dp"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="Medium Text" android:id="@+id/textView2" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="Medium Text" android:id="@+id/textView3" android:layout_alignParentBottom="true" android:layout_marginTop="600dp" android:layout_alignParentRight="true"/> <ImageButton android:layout_width="30dp" android:layout_height="30dp" android:id="@+id/imageButton2" android:layout_alignParentLeft="true" android:onClick="back" android:layout_alignParentTop="true" android:src="@mipmap/back_button"/> </RelativeLayout>

这是我的 java 代码: </p> <pre><code>package com.example.zhenga1.photojewel; import android.app.Activity; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import java.lang.Boolean; import java.io.File; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.os.SystemClock; import android.view.View; import android.widget.Toast; import android.widget.Button; import android.widget.TextView; import java.util.TimerTask; import java.util.Timer; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; public class Main3Activity extends Activity implements SensorEventListener{ private Sensor Accel; static private SensorManager Sensor; public float[] linear_acceleration; private float maxdeltax, maxdeltay, maxdeltaz; public float[] gravity; private Boolean bool = Boolean.TRUE; public float[] prevvalue; private float deltax, deltay, deltaz; private FileWriter prnt; private Timer timer; private TimerTask timerTask; private File fold, file; private Button start, stop; private TextView curx,cury,curz; private int count, curd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main3); count = 0; initializetimer(); System.out.println("This is the clock time in Mills"+SystemClock.uptimeMillis()); linear_acceleration = new float[3]; start = (Button)findViewById(R.id.button1); stop = (Button)findViewById(R.id.button2); maxdeltax = 0f; maxdeltay = 0f; maxdeltaz = 0f; gravity = new float[3]; fold = new File("sdcard/vibration"); if(!fold.exists()) { fold.mkdir(); } file = new File("sdcard/vibration/data.txt"); int v=0; if(!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } curd = 0; } else { while (file.exists()) { v++; file = new File("sdcard/vibration/data" + v + ".txt"); curd = v; } int d = v-1; file = new File("sdcard/vibration/data"+d+".txt"); if(file.length()>300) { file = new File("sdcard/vibration/data"+d+".txt"); curd = d; } try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } prevvalue = new float[3]; Arrays.fill(prevvalue,0); Sensor = (SensorManager) getSystemService(Context.SENSOR_SERVICE); Accel = Sensor.getDefaultSensor(android.hardware.Sensor.TYPE_ACCELEROMETER); curx = (TextView)findViewById(R.id.textView); cury = (TextView)findViewById(R.id.textView2); curz = (TextView)findViewById(R.id.textView3); displayCurrentValues(0,0,0); try { prnt = new FileWriter(file, Boolean.TRUE); } catch (IOException e) { e.printStackTrace(); } } private void initializetimer() { timerTask = new TimerTask() { @Override public void run() { saveCurVals(maxdeltax,maxdeltay,maxdeltaz); maxdeltax = 0f; maxdeltay = 0f; maxdeltaz = 0f; } }; } public void start(View view) { stop.setEnabled(true); Sensor.registerListener(this, Accel, SensorManager.SENSOR_DELAY_NORMAL); timer = new Timer(); timer.schedule(timerTask, 1000, 1000); start.setEnabled(false); } public void end(View view) { Sensor.unregisterListener(this); displayCurrentValues(0, 0, 0); try { prnt.close(); } catch (IOException e) { e.printStackTrace(); } timer.cancel(); stop.setEnabled(false); start.setEnabled(true); } @Override public void onSensorChanged(SensorEvent event) { deltax = Math.abs(event.values[0]-prevvalue[0]); deltay = Math.abs(event.values[1]-prevvalue[1]); deltaz = Math.abs(event.values[2]-prevvalue[2]); findMaxValues(deltax,deltay,deltax); if(Math.abs(deltax)<1) { deltax=0; } if(Math.abs(deltay)<1) { deltay=0; } if(Math.abs(deltaz)<1) { deltaz=0; } displayCurrentValues(deltax,deltay,deltaz); prevvalue[0] = event.values[0]; prevvalue[1] = event.values[1]; prevvalue[2] = event.values[2]; } private void findMaxValues(float x, float y, float z) { if(maxdeltax < x) { maxdeltax = x; } if(maxdeltay < y) { maxdeltay = y; } if(maxdeltaz < z) { maxdeltaz = z; } } private void displayCurrentValues(float x, float y, float z) { curx.setText("x:"+Float.toString(x)); cury.setText("y:"+Float.toString(y)); curz.setText("z:"+Float.toString(z)); } private void saveCurVals(float x, float y, float z) { count++; try { prnt.write(Float.toString(x) + " " + Float.toString(y) + " " + Float.toString(z) + "\n"); prnt.flush(); }catch (IOException e) { e.printStackTrace(); } if(file.length()>300) { redefineFile(); } } private void redefineFile() { int bigd = curd + 1; file = new File("sdcard/vibration/data"+bigd+".txt"); curd = bigd; try { file.createNewFile(); prnt = new FileWriter(file,Boolean.TRUE); } catch (IOException e) { e.printStackTrace(); } } public void back(View view) { finish(); try { prnt.close(); } catch (IOException e) { e.printStackTrace(); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { if(accuracy == SensorManager.SENSOR_STATUS_ACCURACY_HIGH) { Toast.makeText(getApplicationContext(),"GOOD QUALITY and ACCURACY SENSOR",Toast.LENGTH_LONG).show(); } } }

我研究了一些类似的错误,但它们都处理未正确初始化的按钮,这不是我的情况。 请帮我。 谢谢

即使您初始化了那些未指向您的 activity 布局按钮的按钮,在 Android Studio

中我也会遇到同样的情况

在您的布局文件中,您的开始按钮具有 ID R.id.button,而在您 activity class 中,您使用 ID R.id.button1 找到该视图。 您的布局:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Start Accelerometer"
    android:id="@+id/button"  <--- HERE
    android:onClick="start"
    android:layout_marginTop="300dp"
    android:layout_marginStart="0dp"
    android:layout_marginLeft="0dp"
    android:textStyle="normal"
    android:textSize="6pt"/>

Activity :

 start = (Button)findViewById(R.id.button1);

您需要在两个地方设置相同的 ID