2016-08-27 4 views
0

Я создал короткую викторину в студии Android, которая состоит из 4 вопросов. Один вопрос имеет RadioButtons, второй имеет CheckBoxes, третий имеет обычные кнопки, а четвертый/пятый - EditText. Всякий раз, когда я нажимаю любую кнопку после ее запуска, приложение падает, и в журналах появляется большая ошибка.Приложение вылетает при нажатии кнопок

активность Main:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:tools="http://schemas.android.com/tools" 
     style="@style/Background" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" 
     android:paddingBottom="@dimen/activity_vertical_margin" 
     android:paddingLeft="@dimen/activity_horizontal_margin" 
     android:paddingRight="@dimen/activity_horizontal_margin" 
     android:paddingTop="@dimen/activity_vertical_margin" 
     tools:context="com.example.hende.germanquiz.MainActivity"> 


     <TextView 
      android:id="@+id/Header_text_view" 
      style="@style/Header" 
      android:text="@string/header_text" /> 

     <TextView 
      android:id="@+id/question_one" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:paddingTop="16dp" 
      android:text="@string/questionOne" /> 


     <RadioGroup 
      android:id="@+id/radio_group" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"> 

      <RadioButton 
       android:id="@+id/radio1" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:layout_marginTop="10dp" 
       android:checked="true" 
       android:onClick="Bitte schön" 
       android:text="@string/wrong1_answer" /> 

      <RadioButton 
       android:id="@+id/radio2" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:layout_marginTop="10dp" 
       android:onClick="Ich heiße" 
       android:text="@string/correct_answer" /> 

      <RadioButton 
       android:id="@+id/radio3" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:layout_marginTop="10dp" 
       android:onClick="Sprechen sie Deutsch?" 
       android:text="@string/wrong2_answer" /> 

      <TextView 
       android:id="@+id/question_two" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:paddingTop="16dp" 
       android:text="@string/questionTwo" 
       android:textColor="#B71C1C" /> 

      <CheckBox 
       android:id="@+id/checkbox1" 
       style="@style/Buttons" 
       android:onClick="rechnung1" 
       android:text="@string/correct2_answer" /> 

      <CheckBox 
       android:id="@+id/checkbox2" 
       style="@style/Buttons" 
       android:onClick="rechnung2" 
       android:text="@string/correct3_answer" /> 

      <CheckBox 
       android:id="@+id/checkbox3" 
       style="@style/Buttons" 
       android:onClick="Vogel" 
       android:text="Hast du einen Vogel?" /> 

      <TextView 
       android:id="@+id/question_three_text_view" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:paddingTop="16dp" 
       android:text="@string/question_three" /> 

      <TextView 
       android:id="@+id/question_threea_text_view" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="@string/question_threea" /> 


      <Button 
       android:id="@+id/button2" 
       style="@style/RegularButton" 
       android:text="@string/wrong4_answer" 
       android:onClick="button2"/> 

      <Button 
       android:id="@+id/button3" 
       style="@style/RegularButton" 
       android:text="@string/wrong5_answer" 
       android:onClick="button3"/> 
      <Button 
       android:id="@+id/button1" 
       style="@style/RegularButton" 
       android:text="@string/correct4_answer" 
       android:onClick="button1"/> 



      <TextView 
       android:id="@+id/aurora_text_view" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="@string/questionFour" 
       android:layout_marginTop="10dp" /> 

      <EditText 
       android:id="@+id/edit_text_view" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content"/> 
      <TextView 
       android:id="@+id/_text_view" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="@string/questionFive" 
       android:layout_marginTop="10dp"/> 

      <EditText 
       android:id="@+id/edit2_text_view" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" /> 

      <Button 
       android:id="@+id/submit_button" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="@string/submit_button" 
       android:onClick="calculateScore"/> 

      <TextView 
       android:id="@+id/score_text_view" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" /> 

     </RadioGroup> 
    </LinearLayout> 
</ScrollView> 

MainActivity:

public class MainActivity extends AppCompatActivity { 
    int score = 0; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
    } 
    public void questionOne(){ 
     RadioButton radio2 =(RadioButton)findViewById(R.id.radio2); 


     if (radio2.isSelected()) { 
      score = score + 1; 
    }} 

    public void questionTwo(){ 
     CheckBox checkbox1 =(CheckBox) findViewById(R.id.checkbox1); 
     CheckBox checkbox2=(CheckBox) findViewById(R.id.checkbox2); 

     if(checkbox1.isChecked() &&checkbox2 .isChecked()){ 
      score = score + 1; 
     } 

} 
    public void questionThree(){ 
     Button button1 = (Button)findViewById(R.id.button1); 
     Button button2 = (Button)findViewById(R.id.button2); 
     Button button3 = (Button)findViewById(R.id.button3); 
     if (button1.isSelected()) { 
      score= score + 1; 
     } 
} 



    public void questionFour(){ 
     EditText edit_text_view =(EditText) findViewById(R.id.edit_text_view); 
     if (edit_text_view.getText().toString().contains("Nordlicht") || edit_text_view.getText().toString().contains("Nordlicht")) { 
      score = score + 1; 

    } 
} 

public void questionFive(){ 
EditText edit2_text_view=(EditText)findViewById(R.id.edit2_text_view); 
    if (edit2_text_view.getText().toString().contains("On October 10th at 10:10, 10 tame goats pull 10 centners of sugar to the zoo")|| edit2_text_view.getText().toString().contains("On October 10th at 10:10, 10 tame goats pull 10 centners of sugar to the zoo")) { 
     score = score + 1; 

} 
}public void calculateScore(View view){ 
    display (score); 
    questionOne(); 
    questionTwo(); 
questionThree(); 
    questionFour(); 
    questionFive(); 




} 
    private void display(int number) { 
     TextView score_text_view = (TextView) findViewById(
       R.id.score_text_view); 
     score_text_view.setText("" + number); 
    }} 

Ошибка входа:

08-27 13:07:50.408 3344-3344/com.example.hende.germanquiz E/AndroidRuntime: FATAL EXCEPTION: main 
Process: com.example.hende.germanquiz, PID: 3344 
java.lang.IllegalStateException: Could not find method rechnung2(View) in a parent or ancestor Context for 
android:onClick attribute defined on view class android.support.v7.widget.AppCompatCheckBox with id 'checkbox2' 
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:5609) 
at android.widget.CompoundButton.performClick(CompoundButton.java:122) 
at android.view.View$PerformClick.run(View.java:22259) 
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:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
08-27 12:49:22.499 32531-416/com.example.hende.germanquiz E/InstantRun: 
Failed to update existing theme for activity [email protected] 
java.lang.NoSuchFieldException: No field mTheme in class Landroid/content/res/Resources$Theme; 
(declaration of 'android.content.res.Resources$Theme' appears in /system/framework/framework.jar) 
at java.lang.Class.getDeclaredField(Native Method) 
at com.android.tools.fd.runtime.MonkeyPatcher.monkeyPatchExistingResources(MonkeyPatcher.java:374) 
at com.android.tools.fd.runtime.Server.restart(Server.java:523) 
at com.android.tools.fd.runtime.Server.access$600(Server.java:61) 
at com.android.tools.fd.runtime.Server$SocketServerReplyThread.handle(Server.java:318) 
at com.android.tools.fd.runtime.Server$SocketServerReplyThread.run(Server.java:190) 
at com.android.tools.fd.runtime.Server$SocketServerThread.run(Server.java:158) 
at java.lang.Thread.run 
08-27 12:49:43.382 32531-32531/com.example.hende.germanquiz E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length 
08-27 12:49:43.590 32531-32531/com.example.hende.germanquiz E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length 
+0

Вы должны прочитать документацию по android: onClick, вы не используете ее надлежащим образом. – JoxTraex

+0

a/прочитайте свою ошибку. b/что вы думаете 'android: onClick =" rechnung2 "' делает? – njzk2

ответ

1

В вашем Activity нет метода с именем rechnung2

Ваш LogCat говорит это:

java.lang.IllegalStateException: Could not find method rechnung2(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatCheckBox with id 'checkbox2'

Предложение: Пожалуйста, проверьте свой xml и найдите все android:onclick элементов, затем проверьте свой Activity, в своем Activity у вас должен быть относительно метода.

Также Android Studio предупреждает вас, если у вас нет такого метода в Activity подобном:

enter image description here

2

В вашей XML вы определяете свойство OnClick. Это означает, что когда вы нажмете на эту кнопку, андроид вызовет метод, названный в свойстве onClick. Поскольку у вас нет этих методов, определенных в вас MainActivity, вы получаете ошибку времени выполнения

2

Здесь есть несколько проблем. Первое, кажется, связано с тем, что вы указали метод с именем «rechnung2» в свойстве onClick флажка, но вы его никогда не реализовывали. При появлении второй ошибки вы используете другую тему, чем по умолчанию, и может быть причиной конфликта где-то вдоль цепочки. Последняя ошибка в следе может быть потому, что вы прилагая счет на пустое место в вашем методе отображения

+0

Для событий onClick почему бы не setOnClickListeners в методе onCreate и не зарегистрировать их в глобальном обработчике. Вы можете использовать оператор switch для правильной обработки каждого из них. См .: http://blog.cubeactive.com/onclicklistener-android-tutorial/ – d199224

2

onClick атрибута XML вызывает метод, вы должны иметь этот метод в MainActivity. Кроме того, вы должны следовать следующим правилам:

The method you declare in the android:onClick attribute must have a 
specific signature. Specifically, the method must: 

Be public 
Return void 
Define a View as its only parameter (this will be the View that was clicked) 
Смежные вопросы