Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/186.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 按钮onClickListener会导致运行时错误,而不按它_Java_Android_Button_Runtime Error_Onclicklistener - Fatal编程技术网

Java 按钮onClickListener会导致运行时错误,而不按它

Java 按钮onClickListener会导致运行时错误,而不按它,java,android,button,runtime-error,onclicklistener,Java,Android,Button,Runtime Error,Onclicklistener,我正在尝试制作一个应用程序,其中循环生成算术表达式,并将它们列为线性布局中的单个文本视图。点击其中一个表达式后,弹出窗口将显示该表达式和一个输入字段,供用户输入解决方案。下面有一个提交解决方案的按钮。我用XML定位了按钮。问题是,当我使用onClickListener时,当我点击表达式使窗口弹出时,应用程序崩溃。如果我移除整个onClickListener,窗口就会出现,但按钮是没有功能的。 这会导致错误: 这是函数的其余部分: klosinski.kamil.arithmeticprobl

我正在尝试制作一个应用程序,其中循环生成算术表达式,并将它们列为线性布局中的单个文本视图。点击其中一个表达式后,弹出窗口将显示该表达式和一个输入字段,供用户输入解决方案。下面有一个提交解决方案的按钮。我用XML定位了按钮。问题是,当我使用onClickListener时,当我点击表达式使窗口弹出时,应用程序崩溃。如果我移除整个onClickListener,窗口就会出现,但按钮是没有功能的。 这会导致错误:

这是函数的其余部分:


klosinski.kamil.arithmeticproblems.QuizGenerate$1.onClick(QuizGenerate.java:110)的这一行
告诉您崩溃发生在QuizGenerate.java文件的第110行

错误
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void android.widget.Button.setOnClickListener(android.view.view$OnClickListener)”
表明btnDone为空

只有当您正在查找的视图属于范围中的当前上下文时,findViewById才会起作用。i、 e.如果在活动中调用findViewById,则视图应属于该活动,否则将返回null。如果在片段内调用findViewById,则视图应属于该片段,否则将返回null。你明白了


因此,确保您正在调用
Button btnDone=(Button)findViewById(R.id.buttonDone)从正确的位置

您不应该使用setContentView();这样地。仅在onCreate()中调用它一次。如果要更改内容,请使用片段或启动其他活动。如果更改内容,您将无法再通过findViewById找到您的视图。

@ADM谢谢。我添加了日志,这不是坠机痕迹。在
LogCat
中选择
Error
,并且仅post Error log.btnDone为空。显示完整的XML,并显示展开布局的部分。或者在哪里执行setContentView()谢谢大家的更正。我已经添加了完整的代码和XML@卡伦德谢谢你。事实上,我删除了
this.setContentView(scrollView)这一行并且它对输出没有影响。也许它在那里毫无意义。我现在正在阅读有关片段的文档,因为我以前从未接触过它,我认为它比弹出窗口工作得更好。我能征求你的意见吗?再次感谢如果我正确理解了你的应用程序想法,那么使用一个包含算术表达式列表的活动并点击打开一个对话框是完全可以的。这里不一定需要片段,我只是指出了切换内容的必要性。我认为你应该更深入地研究这两个主题:1。使用RecyclerView和2实现列表。显示自定义对话框。您可以通过以下链接进一步阅读:和(尤其是自定义laoyut部分)。
Button btnDone = (Button) findViewById(R.id.buttonDone);
        btnDone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                answerWindow.dismiss();
            }
        });
    package klosinski.kamil.arithmeticproblems;

import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import java.util.Random;

public class QuizGenerate extends AppCompatActivity {



   boolean usePlus, useMinus, useMult, useDivide;
   int count, maxValue;
   Equation equation[] = new Equation[20];

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

        SharedPreferences quizSettings = getSharedPreferences("QuizSettings", MODE_PRIVATE);

        usePlus = quizSettings.getBoolean("usePlus", true);
        useMinus = quizSettings.getBoolean("useMinus", true);
        useMult = quizSettings.getBoolean("useMult", true);
        useDivide = quizSettings.getBoolean("useDivide", true);
        count = quizSettings.getInt("count",0);
        maxValue = quizSettings.getInt("maxValue",0);
        generateQuiz(); //Populate Equation class with generated equations
        displayQuiz(); //Display the equations to the screen
    }

    //Method to display the contents of Equation class to the screen
    public void displayQuiz(){
        ScrollView scrollView = (ScrollView) findViewById(R.id.scrollViewx);
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        scrollView.addView(linearLayout);
        for(int i = 0; i < count; i++){
            int value1 = equation[i].getValue1();
            int value2 = equation[i].getValue2();
            char operator = equation[i].getOperator();

            String value1Str = Integer.toString(value1);
            String value2Str = Integer.toString(value2);

            TextView textView = new TextView(this);
            textView.setTextSize(getResources().getDimension(R.dimen.equationSize));
            if(operator == '/'){
                operator = '\u00F7';
            }
            textView.setText(value1Str + " " + operator + " " + value2Str + "=");
            textView.setId(i);
            textView.setOnClickListener(displayAnswerForm);
            textView.setClickable(true);

            linearLayout.addView(textView);
        }
        this.setContentView(scrollView);
    }

    // OnClickListener runs after equation is pressed.
    // Displays a popup window with the pressed equation and editText for answer.
    public View.OnClickListener displayAnswerForm = new View.OnClickListener() {
        public void onClick(View v) {

            LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
            View popupView = inflater.inflate(R.layout.popup_window, null);

            // Create the popup window
            int width = LinearLayout.LayoutParams.MATCH_PARENT;  // Width of the popup window
            int height = LinearLayout.LayoutParams.MATCH_PARENT; // Height of the popup window
            final PopupWindow answerWindow = new PopupWindow(popupView, width, height, true);

            int equationTextViewId= v.getId(); // The ID of the text view that was pressed

            // Getting the values and operator to display as equation.
            String value1 = Integer.toString(equation[equationTextViewId].getValue1());
            String value2 = Integer.toString(equation[equationTextViewId].getValue2());
            char operator = equation[equationTextViewId].getOperator();
            // If operator is a '/' (divide) then display it as a divider symbol.
            if(operator == '/'){
                operator = '\u00F7';
            }
            String equationToDisplay = value1+" "+operator+" "+value2+"="; // Complete string with the equation.

            //Display our equation on the popup window.
            ((TextView)answerWindow.getContentView().findViewById(R.id.answerWindowTextView)).setText(equationToDisplay);


            // Display the popup window.
            answerWindow.showAtLocation(v, Gravity.CENTER, 0, 0);


            ////
            ////
            //// setOnClickListener or the function causes a crash.
            ////
            ////
            Button btnDone = (Button) findViewById(R.id.buttonDone);
            btnDone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    answerWindow.dismiss();
                }
            });


        }

    };


    //Method to populate Equation class with generated equations
    public void generateQuiz(){

        char operator = '+';

        for(int i = 0; i < count; i++){
            switch(getRandomNumber(1, 4)){
                case 1:
                    operator = '+';
                    break;
                case 2:
                    operator = '-';
                    break;
                case 3:
                    operator = '*';
                    break;
                case 4:
                    operator = '/';
                    break;
                default:
                    break;
            }

            equation[i] = new Equation(getRandomNumber(1, maxValue), getRandomNumber(1, maxValue), operator);
        }
    }

    private int getRandomNumber(int min,int max) {
        return (new Random()).nextInt((max - min) + 1) + min;
    }



}
08-02 15:50:18.731 12741-12741/klosinski.kamil.arithmeticproblems E/AndroidRuntime: FATAL EXCEPTION: main
    Process: klosinski.kamil.arithmeticproblems, PID: 12741
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at klosinski.kamil.arithmeticproblems.QuizGenerate$1.onClick(QuizGenerate.java:110)
        at android.view.View.performClick(View.java:5698)
        at android.widget.TextView.performClick(TextView.java:10846)
        at android.view.View$PerformClick.run(View.java:22565)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:158)
        at android.app.ActivityThread.main(ActivityThread.java:7230)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)