2017-02-11 1 views
-1

J'ai fait un projet android qui va démarrer un capteur accéléromètre, et stocker les données de capteur x, y, z dans un fichier. J'ai ajouté la ligne de code start.setEnabled(false) et stop.setEnabled(true) dans la méthode start, et mon code s'est écrasé à start depuis. L'erreur est comme suit: Erreur dans le code: java.lang.IllegalStateException: Impossible d'exécuter la méthode pour android: onClick

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)  

Mise à jour: Voici mon fichier de mise en page .xml:

<?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> 

Et voici mon code java:

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(); 
     } 
    } 

} 

J'ai fait des recherches au sujet des erreurs similaires, mais ils traitent tous les boutons non initialisé correctement, ce qui n'est pas mon cas. S'il vous plaît aidez-moi. Merci Vous

+1

Pouvez-vous poster votre fichier de disposition d'activité? –

+0

C'est le conflit d'id de contrôle là-bas. Vous devez passer le même bouton-id dans votre code java que vous avez dans le fichier xml pour trouver le contrôle correctement. Je veux dire dans votre fichier xml vous avez id "bouton" pour démarrer le bouton et vous le trouvez dans votre code java avec "R.id.button1" alors s'il vous plaît le réparer et essayer de courir. –

Répondre

1

Dans votre mise en page fichier votre bouton de démarrage a id R.id.button et vous classe d'activité vous trouvez cette vue à l'aide de l'ID R.id.button1. Votre mise en page:

<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"/> 

Activité:

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

Vous devez définir mêmes ids aux deux endroits.

0

Même si vous avez initialisé vos boutons ceux pointant pas à vos boutons de mise en page d'activité, il arrive pour moi même dans Android Studio