"L'application s'est arrêté" dès que je cliques sur un bouton

guineeguinee Messages postés 184 Date d'inscription   Statut Membre Dernière intervention   -  
BunoCS Messages postés 436 Date d'inscription   Statut Modérateur Dernière intervention   -
Bonjour,
Je développe une application Android de Quizz avec Android Studio, j'ai utilisé un textview pour la question, trois boutons pour les choix de réponse, quand j'installe mon app sur mon appareil physique ou je l'ouvre avec l'AVD, j'ai la première question qui s'affiche si je cliques sur n'importe lequel des boutons, l'application s'arrête.
Merci d'avance pour votre aide!

4 réponses

  1. BunoCS Messages postés 436 Date d'inscription   Statut Modérateur Dernière intervention   3 931
     
    Hello (ça faisait longtemps, tiens ;) ),

    Qu'as-tu dans les logs? Tu dois sûrement avoir un problème dans le onClickListener...

    @+ 
    Buno, Modo CS-CCM 
    L'urgent est fait, l'impossible est en cours. Pour les miracles, prévoir un délai... 
    The urgent is done, the impossible is underway. For miracles, provide for a delay...
    1
    1. guineeguinee Messages postés 184 Date d'inscription   Statut Membre Dernière intervention   38
       
      Ah oui ça faisait longtemps :)
      En tout cas voici mon MainActivity.java

      package com.quizzfouta.gn;

      import android.support.v7.app.AppCompatActivity;
      import android.os.Bundle;
      import android.view.View;
      import android.widget.Button;
      import android.widget.TextView;
      import android.widget.Toast;

      import java.util.Random;

      public class Main2Activity extends AppCompatActivity {



      private Questions mQuestions = new Questions();
      private TextView mScoreView;
      private TextView mQuestionView;
      private Button mButtonChoice1;
      private Button mButtonChoice2;
      private Button mButtonChoice3;
      private Button btnquit;

      private String mAnswer;
      private int mScore = 0;
      private int mQuestionNumber = 0;


      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main2);

      mButtonChoice1= (Button) findViewById(R.id.btn1);
      mButtonChoice2= (Button) findViewById(R.id.btn2);
      mButtonChoice3= (Button) findViewById(R.id.btn3);
      btnquit= (Button) findViewById(R.id.btnquit);
      mScoreView= (TextView) findViewById(R.id.score);
      mQuestionView= (TextView) findViewById(R.id.tvq);

      updateQuestion();

      // Debut des boutons Ecouteurs

      //Ecouteurs bouton 1
      mButtonChoice1.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
      if (mButtonChoice1.getText()== mAnswer){
      mScore = mScore + 1;
      updateScore(mScore);
      updateQuestion();
      //On ajoute un toast
      Toast.makeText(Main2Activity.this, "C'est correct", Toast.LENGTH_SHORT).show();
      } else {
      Toast.makeText(Main2Activity.this, "C'est faux", Toast.LENGTH_SHORT).show();
      updateQuestion();

      }
      }
      });
      //Ecouteurs Bouton 2
      mButtonChoice2.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
      if (mButtonChoice2.getText()== mAnswer){
      mScore = mScore + 1;
      updateScore(mScore);
      updateQuestion();
      //On ajoute un toast
      Toast.makeText(Main2Activity.this, "C'est correct", Toast.LENGTH_SHORT).show();
      } else {
      Toast.makeText(Main2Activity.this, "C'est faux", Toast.LENGTH_SHORT).show();
      updateQuestion();

      }
      }
      });

      //Ecouteurs bouton 3
      mButtonChoice3.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
      if (mButtonChoice3.getText()== mAnswer){
      mScore = mScore + 1;
      updateScore(mScore);
      updateQuestion();
      //On ajoute un toast
      Toast.makeText(Main2Activity.this, "C'est correct", Toast.LENGTH_SHORT).show();
      } else {
      Toast.makeText(Main2Activity.this, "C'est faux", Toast.LENGTH_SHORT).show();
      updateQuestion();

      }
      }
      });
      //Fin des écouteurs

      }

      private void updateQuestion() {

      mQuestionView.setText(mQuestions.getQuestions(mQuestionNumber));
      mButtonChoice1.setText(mQuestions.getChoice1(mQuestionNumber));
      mButtonChoice2.setText(mQuestions.getChoice2(mQuestionNumber));
      mButtonChoice3.setText(mQuestions.getChoice3(mQuestionNumber));

      mAnswer = mQuestions.getCorrectAnswer(mQuestionNumber);
      mQuestionNumber++;
      }

      private void updateScore(int point){
      mScoreView.setText("" + mScore);
      }
      }

      0
      1. BunoCS Messages postés 436 Date d'inscription   Statut Modérateur Dernière intervention   3 931 > guineeguinee Messages postés 184 Date d'inscription   Statut Membre Dernière intervention  
         
        1. je ne comprends pas comment cela fonctionne: dans le
        onCreate()
        , tu appelle
        updateQuestions()
        mais ton tableau de questions est a priori vide -> crash
        2. on ne compare pas des chaînes de caractères avec "==". Regarde
        string.equals()
        .
        3. tes 3 callback onClickListener sont identiques -> il faut factoriser pour minimiser les sources d'erreur
        0
      2. guineeguinee Messages postés 184 Date d'inscription   Statut Membre Dernière intervention   38 > BunoCS Messages postés 436 Date d'inscription   Statut Modérateur Dernière intervention  
         
        Le tableau de question n'est pas vide, j'ai quelques questions dedans

        package com.quizzfouta.gn;

        public class Questions {
        private String mQuestions[] = {
        "Qui est le premier Almamy du Fouta ?",
        "Qui est l'auteur de Oogirde Malal ?",
        "Parmis ces trois livres, lequel parle d'héritage?",
        };

        private String mChoices[][] = {
        {
        "Almamy Bocar Biro", "Alpha Ibrahima Sambegou", "Almamy Ibrahima Sory Maoudho",
        "Thierno Sadou Dalein", "Thierno Ibrahima Dama", "Thierno Samba Mombeya",
        "Oogirde Malal", "Shukrul Ilaahi", "Nushu Ruaati",

        }
        };

        private String mCorrectAnswer[] = {"Alpha Ibrahima Sambegou", "Thierno Samba Mombeya", "Shukrul Ilaahi", };

        public String getQuestions(int a){
        String question = mQuestions[a];
        return question;
        }
        public String getChoice1(int a){
        String choice0 = mChoices[a][0];
        return choice0;
        }
        public String getChoice2(int a){
        String choice1 = mChoices[a][1];
        return choice1;
        }
        public String getChoice3(int a){
        String choice2 = mChoices[a][2];
        return choice2;
        }
        public String getCorrectAnswer(int a){
        String answer = mCorrectAnswer[a];
        return answer;
        }
        }
        0
  2. guineeguinee Messages postés 184 Date d'inscription   Statut Membre Dernière intervention   38
     
    Voici le message du Gradle Consle
    Executing tasks: [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies]

    Configuration on demand is an incubating feature.
    NDK is missing a "platforms" directory.
    If you are using NDK, verify the ndk.dir is set to a valid NDK directory. It is currently set to C:\Users\USER\AppData\Local\Android\Sdk\ndk-bundle.
    If you are not using NDK, unset the NDK variable from ANDROID_NDK_HOME or local.properties to remove this warning.

    Incremental java compilation is an incubating feature.
    :app:preBuild UP-TO-DATE
    :app:preDebugBuild UP-TO-DATE
    :app:checkDebugManifest
    :app:preReleaseBuild UP-TO-DATE
    :app:prepareComAndroidSupportAnimatedVectorDrawable2600Alpha1Library
    :app:prepareComAndroidSupportAppcompatV72600Alpha1Library
    :app:prepareComAndroidSupportConstraintConstraintLayout100Alpha7Library
    :app:prepareComAndroidSupportSupportCompat2600Alpha1Library
    :app:prepareComAndroidSupportSupportCoreUi2600Alpha1Library
    :app:prepareComAndroidSupportSupportCoreUtils2600Alpha1Library
    :app:prepareComAndroidSupportSupportFragment2600Alpha1Library
    :app:prepareComAndroidSupportSupportMediaCompat2600Alpha1Library
    :app:prepareComAndroidSupportSupportV42600Alpha1Library
    :app:prepareComAndroidSupportSupportVectorDrawable2600Alpha1Library
    :app:prepareComGoogleAndroidGmsPlayServicesAds1026Library
    :app:prepareComGoogleAndroidGmsPlayServicesAdsLite1026Library
    :app:prepareComGoogleAndroidGmsPlayServicesBase1026Library
    :app:prepareComGoogleAndroidGmsPlayServicesBasement1026Library
    :app:prepareComGoogleAndroidGmsPlayServicesClearcut1026Library
    :app:prepareComGoogleAndroidGmsPlayServicesGass1026Library
    :app:prepareComGoogleAndroidGmsPlayServicesTasks1026Library
    :app:prepareDebugDependencies
    :app:compileDebugAidl UP-TO-DATE
    :app:compileDebugRenderscript UP-TO-DATE
    :app:generateDebugBuildConfig UP-TO-DATE
    :app:generateDebugResValues UP-TO-DATE
    :app:generateDebugResources UP-TO-DATE
    :app:mergeDebugResources UP-TO-DATE
    :app:processDebugManifest UP-TO-DATE
    :app:processDebugResources UP-TO-DATE
    :app:generateDebugSources UP-TO-DATE
    :app:preDebugAndroidTestBuild UP-TO-DATE
    :app:prepareComAndroidSupportTestEspressoEspressoCore222Library
    :app:prepareComAndroidSupportTestEspressoEspressoIdlingResource222Library
    :app:prepareComAndroidSupportTestExposedInstrumentationApiPublish05Library
    :app:prepareComAndroidSupportTestRules05Library
    :app:prepareComAndroidSupportTestRunner05Library
    :app:prepareDebugAndroidTestDependencies
    :app:compileDebugAndroidTestAidl UP-TO-DATE
    :app:processDebugAndroidTestManifest UP-TO-DATE
    :app:compileDebugAndroidTestRenderscript UP-TO-DATE
    :app:generateDebugAndroidTestBuildConfig UP-TO-DATE
    :app:generateDebugAndroidTestResValues UP-TO-DATE
    :app:generateDebugAndroidTestResources UP-TO-DATE
    :app:mergeDebugAndroidTestResources UP-TO-DATE
    :app:processDebugAndroidTestResources UP-TO-DATE
    :app:generateDebugAndroidTestSources UP-TO-DATE
    :app:mockableAndroidJar UP-TO-DATE
    :app:preDebugUnitTestBuild UP-TO-DATE
    :app:prepareDebugUnitTestDependencies

    BUILD SUCCESSFUL

    Total time: 18.58 secs
    0
    1. BunoCS Messages postés 436 Date d'inscription   Statut Modérateur Dernière intervention   3 931
       
      Il ne faut pas regarder la console Gradle mais la console "Android Monitor", filtrée sur le package name de ton app.
      Tu n'as toujours pas appris à t'en servir?
      0
  3. guineeguinee Messages postés 184 Date d'inscription   Statut Membre Dernière intervention   38
     
    Le voici

    --------- beginning of crash
    10-23 14:52:44.513 5445-5445/com.quizzfouta.gn E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.quizzfouta.gn, PID: 5445
    java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
    at com.quizzfouta.gn.Questions.getChoice1(Questions.java:26)
    at com.quizzfouta.gn.Main2Activity.updateQuestion(Main2Activity.java:104)
    at com.quizzfouta.gn.Main2Activity.access$400(Main2Activity.java:12)
    at com.quizzfouta.gn.Main2Activity$1.onClick(Main2Activity.java:57)
    at android.view.View.performClick(View.java:5637)
    at android.view.View$PerformClick.run(View.java:22429)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
    0
    1. BunoCS Messages postés 436 Date d'inscription   Statut Modérateur Dernière intervention   3 931
       
      Tu n'as pas besoin de tout copier! Il faut que tu apprennes à lire les logs!
      Avec l'extrait suivant, tu as toutes les billes pour corriger:
      --------- beginning of crash 
      10-23 14:52:44.513 5445-5445/com.quizzfouta.gn E/AndroidRuntime: FATAL EXCEPTION: main
      Process: com.quizzfouta.gn, PID: 5445
      java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
      at com.quizzfouta.gn.Questions.getChoice1(Questions.java:26)
      at com.quizzfouta.gn.Main2Activity.updateQuestion(Main2Activity.java:104)
      at com.quizzfouta.gn.Main2Activity.access$400(Main2Activity.java:12)
      at com.quizzfouta.gn.Main2Activity$1.onClick(Main2Activity.java:57)
      at android.view.View.performClick(View.java:5637)
      at android.view.View$PerformClick.run(View.java:22429)
      at android.os.Handler.handleCallback(Handler.java:751)
      at android.os.Handler.dispatchMessage(Handler.java:95)
      at android.os.Looper.loop(Looper.java:154)
      at android.app.ActivityThread.main(ActivityThread.java:6119)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
      0
  4. guineeguinee Messages postés 184 Date d'inscription   Statut Membre Dernière intervention   38
     
    J'ai bien regardé ces references dans le code, je ne comprends pas ce quoi le problème.
    0