首页 > 解决方案 > Android Studio:尝试在空对象上调用虚拟方法“void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)”

问题描述

请任何帮助???

确实存在与我要问的问题类似的问题,但是我确实尝试了您提出的所有解决方案,但对我不起作用。

我在控制台中遇到的错误。

E/AndroidRuntime: 致命异常: main

              Process: ems.develop.megagame3, PID: 9574
              java.lang.RuntimeException: Unable to start activity ComponentInfo{ems.develop.megagame3/ems.develop.megagame3.MainActivity}: 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:2778)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                  at android.app.ActivityThread.-wrap11(Unknown Source:0)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                  at android.os.Handler.dispatchMessage(Handler.java:106)
                  at android.os.Looper.loop(Looper.java:164)
                  at android.app.ActivityThread.main(ActivityThread.java:6494)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
               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 ems.develop.megagame3.MainActivity.onCreate(MainActivity.java:41)
                  at android.app.Activity.performCreate(Activity.java:7009)
                  at android.app.Activity.performCreate(Activity.java:7000)

#

这里是 mainActivity.java

public class MainActivity extends AppCompatActivity {

private EditText TxtNumber=null ;
private Button lblCompare;
private TextView TxtResult;
private ProgressBar pgbScole;
private TextView TxtHistory;

private int searchedValue;
private int score;

public MainActivity() {
}


@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    /* TxtNumber =(EditText) findViewById(R.id.TxtNumber); */
    TxtNumber =(EditText) findViewById(R.id.TxtNumber);
    lblCompare =(Button) findViewById(R.id.lblCompare);
    TxtResult =(TextView) findViewById(R.id.TxtResult);
    pgbScole =(ProgressBar) findViewById(R.id.pgbScole);
    TxtHistory= (TextView) findViewById(R.id.TxtHistory);
    lblCompare.setOnClickListener(btnCompareListner);

    init();

}

private void init() {

    score= 0;
    searchedValue = 1+ (int)(Math.random() *100);
    Log.i("DEBUG", " Valeur cherché "+searchedValue);
    // réinitialisation des fields
    TxtNumber.setText("");
    pgbScole.setProgress(score);
    TxtResult.setText("");
    TxtHistory.setText("");
// Mettre le focus au field TxtNumber;
    TxtNumber.requestFocus();

}

private View.OnClickListener btnCompareListner;

{
    btnCompareListner = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.i("Debug", "Bouton cliqué ");
            String txtNumber = TxtNumber.getText().toString();
            if (txtNumber.equals("")) return;

            TxtHistory.append(TxtNumber +"\r\n");
            pgbScole.incrementProgressBy(1);
            score++;

            int enteredValue = Integer.parseInt(txtNumber);
            if (enteredValue == searchedValue) {
                congratulations();

            } else if (enteredValue < searchedValue) {
                TxtResult.setText(R.string.strGreater);
            }else{
                TxtResult.setText(R.string.strLower);
            }
            TxtNumber.setText("");
            TxtNumber.requestFocus();
        }
    };
}

private void congratulations() {
    TxtResult.setText(R.string.congra);

    AlertDialog retryAlert= new AlertDialog.Builder(this).create();
    retryAlert.setTitle(R.string.app_name);
    retryAlert.setMessage(getString( R.string.strMessage,score));
    retryAlert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.strYes), new AlertDialog.OnClickListener(){
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            init();
        }
    });
    retryAlert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.strNo), new AlertDialog.OnClickListener(){
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            finish();
        }
    });
    retryAlert.show();
}

这是“activity_main.xml”

   <?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<android.support.constraint.Guideline
    android:id="@+id/guideline3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="281dp"
    android:orientation="vertical"
    app:layout_constraintBottom_toTopOf="@+id/pgbScole"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintGuide_end="-44dp"
    app:layout_constraintTop_toTopOf="parent">

    <ProgressBar
        android:id="@+id/pgbScole"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="448dp"
        android:layout_height="14dp"
        android:layout_marginTop="180dp"
        android:max="10"
        android:progress="5"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.68"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/lbltitre"
        style="@android:style/Animation"
        android:layout_width="0dp"
        android:layout_height="42dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="29dp"
        android:layout_marginLeft="29dp"
        android:layout_marginRight="29dp"
        android:layout_marginStart="29dp"
        android:text="@string/lblTitle"
        android:textAppearance="@android:style/TextAppearance.Large"
        android:textColor="@android:color/background_dark"
        android:textColorHighlight="@android:color/background_dark"
        android:textColorHint="@android:color/background_dark"
        android:textColorLink="@android:color/holo_purple"
        app:layout_constraintBottom_toTopOf="@+id/TxtNumber"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0"
        tools:height="?android:attr/lightRadius"
        tools:textCursorDrawable="@android:color/holo_blue_dark"
        tools:textSize="18sp" />

    <EditText
        android:id="@+id/TxtNumber"
        android:layout_width="0dp"
        android:layout_height="43dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="28dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="28dp"
        android:layout_marginTop="56dp"
        android:ems="10"
        android:inputType="numberSigned"
        app:layout_constraintBottom_toTopOf="@+id/TxtResult"
        app:layout_constraintEnd_toStartOf="@+id/lblCompare"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="UnknownId" />

    <Button
        android:id="@+id/lblCompare"
        android:layout_width="159dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="28dp"
        android:layout_marginRight="28dp"
        android:layout_marginTop="64dp"
        android:text="@string/lblComapre"
        app:layout_constraintBottom_toBottomOf="@+id/TxtResult"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.036" />

    <TextView
        android:id="@+id/TxtHistory"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="24dp"
        android:layout_marginEnd="12dp"
        android:layout_marginLeft="12dp"
        android:layout_marginRight="12dp"
        android:layout_marginStart="12dp"
        android:layout_marginTop="8dp"
        android:background="@color/colorAccent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/pgbScole" />


    <EditText
        android:id="@+id/TxtResult"
        android:layout_width="299dp"
        android:layout_height="47dp"
        android:layout_marginBottom="4dp"
        android:layout_marginEnd="56dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="56dp"
        android:layout_marginStart="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/pgbScole"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/guideline3" />
</android.support.constraint.Guideline>

标签: android

解决方案


确保您没有其他xml同名的,并且您正在使用这个 another xml

一个非常相似的场景是,当您有两种不同配置的布局时,例如,landscape一个portraitviews而另一个没有


推荐阅读