2017-01-06 3 views
0

Я делаю простое приложение и хочу, чтобы пользователь нажал кнопку «Пуск», чтобы перейти к следующему действию, но при реализации кнопки «Пуск» я продолжаю получать исключение NullPointerException, когда оно нажимается во время выполнения. Я смущен, потому что похоже, что FindViewByID возвращает null на идентификатор кнопки (startbutton), хотя он включен в файл XML. Застрял в этом часами и искал другие решения и пытался очистить и восстановить. Используя Android Studio 2.2.3, если это поможет. Благодарю.NullPointException на кнопке OnClickListener

XML файл activity_start_screen.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:gravity="top|center" 
android:weightSum="1"> 

<TextView 
    android:layout_width="match_parent" 
    android:layout_height="0dp" 
    android:text="Quiz App" 
    android:textSize="36dp" 
    android:gravity="center" 
    android:layout_weight="0.34" /> 

<Button 
    android:text="Start!" 
    android:layout_width="245dp" 
    android:layout_height="50dp" 
    android:id="@+id/startbutton" /> 

</LinearLayout> 

Основная деятельность Код StartScreen.java

import android.content.Intent; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.content.Intent; 
import android.app.Activity; 

public class StartScreen extends AppCompatActivity 
{ 
    private Button startbutton; 



@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_start_screen); 
    //set start button 
    startbutton = (Button) findViewById(R.id.startbutton); 
    startbutton.setOnClickListener(new View.OnClickListener() 
    { 
     @Override 
     public void onClick(View v) 
     { 
      //go to quiz screen 
      //change activity 
      Intent QuizScreen = new Intent(StartScreen.this, QuizScreen.class); 
      startActivity(QuizScreen); 

     } 
    }); 
} 
} 

Трассировка стека

E/AndroidRuntime: FATAL EXCEPTION: main 
       Process: com.paavan.quizappcoursework, PID: 2305 
       java.lang.RuntimeException: Unable to start activity ComponentInfo{com.paavan.quizappcoursework/com.paavan.quizappcoursework.QuizScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference 
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646) 
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
        at android.app.ActivityThread.-wrap12(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        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) 
       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference 
        at com.paavan.quizappcoursework.QuizScreen.onCreate(QuizScreen.java:63) 
        at android.app.Activity.performCreate(Activity.java:6662) 
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) 
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599) 
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)  
        at android.app.ActivityThread.-wrap12(ActivityThread.java)  
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)  
        at android.os.Handler.dispatchMessage(Handler.java:102)  
        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)  
Application terminated. 

QuizScreen.java

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


public class QuizScreen extends AppCompatActivity 
{ 
private Button mTrueButton; 
private Button mFalseButton; 
private Button mNextButton; 
private TextView mQuestionTextView; 

private Question[] mQuestionBank = new Question[] { 
     new Question(R.string.question_oceans, true), 
     new Question(R.string.question_mideast, false), 
     new Question(R.string.question_africa, false), 
     new Question(R.string.question_americas, true), 
     new Question(R.string.question_asia, true), 
     new Question(R.string.question_uk,false), 
     new Question(R.string.question_europe,true), 
     new Question(R.string.question_waterfall,false), 
     new Question(R.string.question_giraffes,false), 
     new Question(R.string.question_penguins,true), 
}; 

private int mCurrentIndex = 0; 

private void updateQuestion() 
{ 
    int question = mQuestionBank[mCurrentIndex].getTextResId(); 
    mQuestionTextView.setText(question); 
} 

private void checkAnswer(boolean userPressedTrue) 
{ 
    boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue(); 

    int messageResId = 0; 

    if (userPressedTrue == answerIsTrue) { 
     messageResId = R.string.correct_toast; 
    } else { 
     messageResId = R.string.incorrect_toast; 
    } 

    Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show(); 
} 



@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    mQuestionTextView = (TextView) this.findViewById(R.id.question_text_view); 


    mTrueButton = (Button) this.findViewById(R.id.true_button); 
    mTrueButton.setOnClickListener(new View.OnClickListener() 
    { 
     @Override 
     public void onClick(View v) 
     { 
      checkAnswer(true); 
     } 
    }); 
    mFalseButton = (Button) this.findViewById(R.id.false_button); 
    mFalseButton.setOnClickListener(new View.OnClickListener() 
    { 
     @Override 
     public void onClick(View v) 
     { 
      checkAnswer(false); 
     } 
    }); 

    mNextButton = (Button) this.findViewById(R.id.next_button); 
    mNextButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length; 
      updateQuestion(); 
     } 
    }); 

    updateQuestion(); 

} 



} 

quizscreen.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:gravity="center" 
android:orientation="vertical" > 



<TextView 
    android:id="@+id/question_text_view" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:padding="24dp" 
    /> 

<LinearLayout 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" > 

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

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

</LinearLayout> 


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

</LinearLayout> 
+1

опубликуйте свой журнал, пожалуйста, и вы уверены, что ваша кнопка находится в activity_start_screen.xml? –

+0

Включен ли файл XML в файл activity_start_screen.xml? – Isaac

+0

Какая строка вызывает ошибку? –

ответ

1

Необходимо добавить макет к активности.

Перед выполнением любой инициализации виджетов в OnCreate() добавить макет, используя setContentView (R.layout.your_layoutfile);

public class QuizScreen extends AppCompatActivity 
    { 
     @Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 

    setContentView(R.layout.quizscreenlayout); 

    //initialize your widgets 
} 
1

Попробуйте это:

LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View view = inflater.inflate(R.layout.activity_start_screen, null); 

Button startbutton = (Button) view.findViewById(R.id.startbutton); 
+0

Что? Это не имеет никакого смысла. Почему код в вопросе не работает как есть? –

+0

Спасибо, похоже, избавились от этой ошибки! Вы не возражаете, объясняя это, потому что это меня смутило. –

+0

Этот ответ не имеет никакого смысла, что вы пытаетесь сделать здесь? – W4R10CK

-1
Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener) 
    on a null object reference at 
    com.paavan.quizappcoursework.QuizScreen.onCreate(QuizScreen.java:65) 

Это исключения нулевого указателя в 65-й строке в Quizscreen. Ява. Проверьте, есть ли все кнопки id в quizscreen.xml.

+0

проверено quizscreen.xml и похоже, что они все есть. опубликует код в главном вопросе. –

+0

setContentView (R.layout.quizscreen) отсутствует –

 Смежные вопросы

  • Нет связанных вопросов^_^