0

My Android App consists of a Main Activity which switches through various Fragements. When I try to find 9 buttons from the layout file by id in order to add them to an Button Array and later give them an onClickEventListener, I get an exception, that the found buttons are null even though I have defined those id's

// Java code of the Main Activity

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 Answers1

0

the layout has a 2x3 matrix of buttons, and you initialize a 3x3 matrix

Ignacio Tomas Crespo
  • 3,401
  • 1
  • 20
  • 13