2015-05-05 4 views
0

Я применил приложение для ответов на вопросы и ответы с помощью Android Studio, однако он продолжает сбой. На боковой панели нет ошибок (она загорается зеленым цветом), но после первого раза я пытаюсь отправить ответ. Я выяснил, что в методе onClick он выбрал исключение нулевого указателя. Я посмотрел и попробовал решения, которые мог найти, но до сих пор не смог исправить эту ошибку. Ниже приведен код на странице сбоя. Любая помощь будет оценена по достоинству.Сбой приложения для Android из-за NPE

package com.example.jeff.mygame; 

import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.Button; 
import android.widget.RadioButton; 
import android.widget.RadioGroup; 
import android.widget.TextView; 


public class QuestionActivity extends Activity { 
    Intent intent; 
    TextView tv; 
    Button submitButton; 
    RadioGroup radioGroup; 
    RadioButton choice1, choice2, choice3, givenAnswer; 
    String answersText; 
    String questions[] = {"Which studio developed Elder Scrolls V: Skyrim?", "Who is the main character in the Mass Effect series?", 
      "Which indie games company developed the Walking Dead series?"}; 
    String answers[] = {"Bethesda", "Commander Shepard", "TellTale Games"}; 
    String choices[] = {"Bioware", "Bethesda", "Ubisoft", "Commander Shepard", "Garrus Vakarian", "Illusive Man", "Team Meat", "Way Forward", "TellTale Games"}; 
    int flag = 0; 
    public static int results, correct, incorrect; 

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

     tv = (TextView)findViewById(R.id.tvQ1); 
     choice1 = (RadioButton)findViewById(R.id.rb1); 
     choice2 = (RadioButton)findViewById(R.id.rb2); 
     choice3 = (RadioButton)findViewById(R.id.rb3); 
     submitButton = (Button)findViewById(R.id.submit1); 

     tv.setText(questions[flag]); 
     choice1.setText(choices[0]); 
     choice2.setText(choices[1]); 
     choice3.setText(choices[2]); 
     submitButton.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       givenAnswer = (RadioButton)findViewById(radioGroup.getCheckedRadioButtonId()); 
       answersText = givenAnswer.getText().toString(); 

       if(answersText.equals(answers[flag])){ 
        correct++; 
       }else{ 
        incorrect++; 
       }flag++; 
       if(flag < questions.length){ 
        tv.setText(questions[flag]); 
        choice1.setText(choices[flag*3]); 
        choice2.setText(choices[flag*3]); 
        choice3.setText(choices[flag*3]); 
       }else{ 
        results = correct; 
        intent = new Intent(getApplicationContext(),FinishActivity.class); 
        startActivity(intent); 
       } 
      } 
     }); 
    } 


    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_question, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 
} 

Вот logcat, который я забыл добавить сначала.

05-05 17:34:49.744  652-658/com.example.jeff.mygame I/dalvikvm﹕ threadid=3: reacting to signal 3 
05-05 17:34:49.775  652-658/com.example.jeff.mygame I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt' 
05-05 17:34:51.595  652-652/com.example.jeff.mygame I/Process﹕ Sending signal. PID: 652 SIG: 9 
05-05 17:42:07.295  704-709/com.example.jeff.mygame I/dalvikvm﹕ threadid=3: reacting to signal 3 
05-05 17:42:07.465  704-709/com.example.jeff.mygame I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt' 
05-05 17:42:07.775  704-709/com.example.jeff.mygame I/dalvikvm﹕ threadid=3: reacting to signal 3 
05-05 17:42:07.885  704-709/com.example.jeff.mygame I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt' 
05-05 17:42:08.105  704-704/com.example.jeff.mygame D/gralloc_goldfish﹕ Emulator without GPU emulation detected. 
05-05 17:42:11.465  704-704/com.example.jeff.mygame D/AndroidRuntime﹕ Shutting down VM 
05-05 17:42:11.465  704-704/com.example.jeff.mygame W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x409c01f8) 
05-05 17:42:11.475  704-704/com.example.jeff.mygame E/AndroidRuntime﹕ FATAL EXCEPTION: main 
    java.lang.NullPointerException 
      at com.example.jeff.mygame.QuestionActivity$1.onClick(QuestionActivity.java:48) 
      at android.view.View.performClick(View.java:3511) 
      at android.view.View$PerformClick.run(View.java:14105) 
      at android.os.Handler.handleCallback(Handler.java:605) 
      at android.os.Handler.dispatchMessage(Handler.java:92) 
      at android.os.Looper.loop(Looper.java:137) 
      at android.app.ActivityThread.main(ActivityThread.java:4424) 
      at java.lang.reflect.Method.invokeNative(Native Method) 
      at java.lang.reflect.Method.invoke(Method.java:511) 
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 
      at dalvik.system.NativeStart.main(Native Method) 
05-05 17:42:12.015  704-709/com.example.jeff.mygame I/dalvikvm﹕ threadid=3: reacting to signal 3 
05-05 17:42:12.025  704-709/com.example.jeff.mygame I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt' 
05-05 17:42:15.525  704-704/com.example.jeff.mygame I/Process﹕ Sending signal. PID: 704 SIG: 9 
+3

Есть ли у вас трассировка стека (Logcat), чтобы определить, где она происходит? Кроме того, вы уверены, что 'givenAnswer.getText()' не является нулевым? – Makoto

+1

Crash log пожалуйста. – Iqbal

+0

Вы создаете радиогруппу? Если это значение равно null, то null.Method() вызовет NPE –

ответ

1

Вы не инициализировали radioGroup. Вы должны сделать как ниже

radioGroup = (RadioGroup) findViewById(R.id.myRadioGroup); 
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(RadioGroup group, int checkedId) { 
         // find which radio button is selected 
         if(checkedId == R.id.rb1) { 
         // do action 
         } 
      } 
}); 
button.setOnClickListener(new OnClickListener() { 
     @Override   
     public void onClick(View v) { 
         int selectedId = radioGroup.getCheckedRadioButtonId(); 
         // find which radioButton is checked by id 
         if(selectedId == R.id.rb1) { 
          // you have chosen so and so radio button 
         } 
         // similarly check other buttons 
     } 
}); 
Смежные вопросы