为什么我的应用程序抛出空指针异常?

时间:2019-10-24 22:57:47

标签: java android xml

我的Android应用包含一个主要活动,该活动可以在各种细分之间进行切换。当我尝试通过id从布局文件中找到9个按钮以将它们添加到Button数组中,然后再为它们提供onClickEventListener时,我得到了一个例外,即使我定义了这些id,发现的按钮也为空

//主要活动的Java代码

public class MainActivity extends AppCompatActivity implements Welcome.OnFragmentInteractionListener {

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

        Welcome welcomeFragment = Welcome.newInstance("", "");

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.parent_layout, welcomeFragment);
        fragmentTransaction.commit();
    }

    @Override
    public void onChangeToMode() {
        replaceFragment(Mode.newInstance("", ""), "MODE");
    }

    public void onPvpButtonClicked(View view) {
        replaceFragment(Pvp.newInstance("", ""), "PVP");
    }

    public void onPvcButtonClicked(View view) {
        replaceFragment(Welcome.newInstance("", ""), "WELCOME");
    }

    public void onPvc2ButtonClicked(View view) {
        replaceFragment(Welcome.newInstance("", ""), "WELCOME");
    }

    private void replaceFragment(Fragment fragment, String tag) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.parent_layout, fragment);
        fragmentTransaction.addToBackStack(tag);
        fragmentTransaction.commit();
    }
}

// Layout of the Tic Tac Toe fragment
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <Button
            android:id="@+id/button_00"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="60sp"/>

        <Button
            android:id="@+id/button_01"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="60sp"/>

        <Button
            android:id="@+id/button_02"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="60sp"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <Button
            android:id="@+id/button_10"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="60sp"/>

        <Button
            android:id="@+id/button_11"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="60sp"/>

        <Button
            android:id="@+id/button_12"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="60sp"/>
    </LinearLayout>

    //etc.
    </LinearLayout>

</LinearLayout>

// Java Code of the Tic Tac Toe fragment
public class Pvp extends Fragment implements View.OnClickListener {

    // UI deklarieren
    private Button[][] buttons = new Button[3][3];
    private boolean player1Turn = true;
    private int roundCount;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public Pvp() {
        // Required empty public constructor
    }

    // TODO: Rename and change types and number of parameters
    public static Pvp newInstance(String param1, String param2) {
        Pvp fragment = new Pvp();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                String buttonID = "button_" + i + j;
                int resID = getActivity().getResources().getIdentifier(buttonID, "id", getActivity().getPackageName());
                buttons[i][j] = getActivity().findViewById(resID);
                buttons[i][j].setOnClickListener(this);
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.map3x3, container, false);
        return view;
    }

This is the error message I get

2019-10-25 00:29:31.898 23036-23036/? E/ample.tictacto: Unknown bits set in runtime_flags: 0x8000
2019-10-25 00:29:32.991 23036-23069/com.example.tictactoe E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
2019-10-25 00:29:32.991 23036-23069/com.example.tictactoe E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
2019-10-25 00:29:38.063 23036-23036/com.example.tictactoe E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.tictactoe, PID: 23036
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at com.example.tictactoe.Pvp.onCreate(Pvp.java:61)
        at androidx.fragment.app.Fragment.performCreate(Fragment.java:2414)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1418)
        at androidx.fragment.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1195)
        at androidx.fragment.app.FragmentTransition.calculateFragments(FragmentTransition.java:1078)
        at androidx.fragment.app.FragmentTransition.startTransitions(FragmentTransition.java:117)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2408)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
        at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
        at androidx.fragment.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

1 个答案:

答案 0 :(得分:0)

布局具有2x3的按钮矩阵,而您初始化了3x3的矩阵