Свернуть эмулятор Android-студии после использования onDraw () - PullRequest
0 голосов
/ 01 декабря 2018

Я пытаюсь сделать игру на линкоре, и приведенные ниже классы - это только начало.

Я не знаю, что приводит к падению приложения после попытки нарисовать матрицу на экране.

Я попытался отладить его безуспешно, и я заранее извиняюсь за эти огромные примеры кода.

сначала появляется экран подключения, в основном экран основной активности, а затем вы нажимаете новую игру ивы предполагаете увидеть матрицу 11 * 11

BoardView

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;



public class BoardView extends AppCompatImageView {
    int border = 10;    // Width of the outer border
    int topBoardX = border;
    int topBoardY = 50;
    int fontSize = 30;
    Point[][] grid = new Point[11][11];
    String[] letters = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
    String[] numbers = {" 1", " 2", " 3", " 4", " 5", " 6", " 7", " 8", " 9", "10"};
    private static Paint paint;
    Point origin = new Point(this.getLeft(), this.getTop());

    public BoardView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        paint.setStrokeWidth(10);
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.STROKE);
        paint.setTextSize(fontSize);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        this.getLeft();
        int screenHeight = this.getMeasuredHeight();
        int screenWidth = this.getMeasuredWidth();
        int middle = screenHeight / 2;
        // Erase the view first
        paint.setColor(Color.BLACK);
        canvas.drawRect(topBoardX, topBoardY, screenWidth - border, middle - border, paint);

        paint.setColor(Color.BLUE);

        // Calculate cell width based on width
        int cellWidth = (screenWidth / 11) - 1;
        int cellHeight = (middle - border) / 12;   // 10 cells + 1 for letters and 1 for Attack/Defend Boards

        // Draw a border
        canvas.drawRect(topBoardX, topBoardY, screenWidth - border, middle - border, paint);
        paint.setColor(Color.GREEN);
        paint.setStrokeWidth(2);

     //   if (Game.gameStarted) {

            Game.gameGrid[0][0].setCellHeight(cellHeight);
            Game.gameGrid[0][0].setCellWidth(cellWidth);
            Game.gameGrid[0][0].setViewOrigin(origin);

            for (int y = 0; y < 11; y++) {
                for (int x = 0; x < 11; x++) { // TODO:  add the points to the gameGrid
                    Game.gameGrid[x][y].setTopleft(new Point(x * cellWidth + border, y * cellHeight + topBoardY));
                    Game.gameGrid[x][y].setBottomright(new Point((x + 1) * cellWidth + border, (y + 1) * cellHeight + topBoardX));
                }
            }
        // Draw the horizontal lines
        for( int i = 0; i < 11; i++ ) {
            canvas.drawLine( i * cellWidth + border, topBoardY, i * cellWidth + border, middle - border, paint );    // Vertical Lines
            canvas.drawLine( border, i * cellHeight + topBoardY, screenWidth - border, i * cellHeight + topBoardY, paint );  // Horizontal Lines
        }
       // }
    }
}

Game

package com.example.omer.battleship;

import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;


import java.util.*;


public class Game extends Activity {

    public static GameCell[][] gameGrid = new GameCell[11][11];
    View gameBoard = null;
    Activity customGrid = this;
    public static boolean gameStarted = false;
    Spinner shipSpinner;
    String[] shipsArray;
    Map<String, Integer> shipsMap = new HashMap<String, Integer>();
    ArrayAdapter<String> spinnerArrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initializeApp();
        setContentView(R.layout.gameboard);
        gameBoard = findViewById(R.id.boardView);

        gameStarted = false;
    }

    private void initializeApp() {
        // Initialize the gameGrid
        for (int y = 0; y < 11; y++) {
            for (int x = 0; x < 11; x++) {
                gameGrid[x][y] = new GameCell();
            }
        }
        gameGrid[1][1].setHas_ship(true);   // For debugging
        gameGrid[1][2].setHit(true);

    }

}

GameActivity

package com.example.omer.battleship;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;

import static com.example.omer.battleship.R.layout.activity_game;

public class gameActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(activity_game);
    }
}

GameCell

package com.example.omer.battleship;
import android.graphics.*;

public class GameCell {
    private Boolean has_ship;
    private Boolean miss;
    private Boolean hit;
    private Boolean waiting;
    private Point topLeft;
    private Point bottomRight;
    private Point viewOrigin;
    private int cellHeight, cellWidth;

    /**
     *
     */
    public GameCell() {
        has_ship = false;
        miss = false;
        hit = false;
        waiting = false;
        topLeft = null;
        bottomRight = null;
        cellHeight = 0;
        cellWidth = 0;
    }

    // GameCell Constructor

    /**
     * @param _has_ship
     * @param _miss
     * @param _hit
     * @param _waiting
     * @param _topLeft
     * @param _bottomRight
     */
    public GameCell( Boolean _has_ship, Boolean _miss, Boolean _hit, Boolean _waiting, Point _topLeft, Point _bottomRight ) {
        has_ship = _has_ship;
        miss = _miss;
        hit = _hit;
        waiting = _waiting;
        topLeft = _topLeft;
        bottomRight = _bottomRight;
    }

    /**
     * @param _origin
     */
    public void setViewOrigin( Point _origin ) {
        viewOrigin = _origin;
    }

    /**
     * @return viewOrigin
     */
    public Point getViewOrigin() {
        return viewOrigin;
    }

    /**
     * @param _cellHeight
     */
    public void setCellHeight( int _cellHeight ) {
        cellHeight = _cellHeight;
    }

    /**
     * @return cellHeight
     */
    public int getCellHeight() {
        return cellHeight;
    }

    /**
     * @param _cellWidth
     */
    public void setCellWidth( int _cellWidth ) {
        cellWidth = _cellWidth;
    }

    /**
     * @return cellWidth
     */
    public int getCellWidth() {
        return cellWidth;
    }


    /**
     * has_ship Getter
     *
     * @return has_ship
     */
    public Boolean getHas_ship() {
        return has_ship;
    }

    /**
     * Getter
     *
     * @param _has_ship
     */
    public void setHas_ship( Boolean _has_ship ) {
        has_ship = _has_ship;
    }

    /**
     * @return miss
     */
    public Boolean getMiss() {
        return miss;
    }

    /**
     * @param _miss
     */
    public void setMiss( Boolean _miss ) {
        miss = _miss;
    }

    /**
     * @return hit
     */
    public Boolean getHit() {
        return hit;
    }

    /**
     * @param _hit
     */
    public void setHit( Boolean _hit ) {
        hit = _hit;
    }

    /**
     * @return waiting
     */
    public Boolean getWaiting() {
        return waiting;
    }

    /**
     * @param _waiting
     */
    public void setWaiting( Boolean _waiting ) {
        waiting = _waiting;
    }

    /**
     * @return topLeft
     */
    public Point getTopleft() {
        return topLeft;
    }

    /**
     * @param _topLeft
     */
    public void setTopleft( Point _topLeft ) {
        topLeft = _topLeft;
    }

    /**
     * @return bottomRight
     */
    public Point getBottomright() {
        return bottomRight;
    }

    /**
     * @param _bottomRight
     */
    public void setBottomright( Point _bottomRight ) {
        bottomRight = _bottomRight;
    }

}

MainActivity

public class MainActivity extends AppCompatActivity {

    private Button btn;
    private RadioGroup radioLevelGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn=(Button)findViewById(R.id.newGameButton);
        radioLevelGroup=(RadioGroup)findViewById(R.id.radioLevelGroup);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int selectedId = radioLevelGroup.getCheckedRadioButtonId();
                if(selectedId!=-1) {
                    OpenNewGameActivity();
                }
                }
        });
    }
    public void OpenNewGameActivity()
    {
        Intent intent=new Intent(this,gameActivity.class);
        startActivity(intent);
    }
}

GameBoardXML

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Ship"

        android:layout_gravity="center_horizontal"
        android:onClick="onClickAddShip"
        android:layout_x="179dp"
        android:layout_y="106dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        />

    <view
        android:layout_width="fill_parent"
        android:layout_height="569dp"
        class="com.example.omer.battleship.BoardView"
        android:id="@+id/boardView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        />


</RelativeLayout>

Activity 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"
    android:background="@drawable/battlepic"
    tools:context=".MainActivity">

    <RadioGroup
        android:id="@+id/radioLevelGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.12"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"

        app:layout_constraintVertical_bias="0.26">

        <RadioButton
            android:id="@+id/option1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Easy"
            android:textColor="@android:color/white"
            tools:layout_editor_absoluteX="53dp"
            tools:layout_editor_absoluteY="139dp" />

        <RadioButton
            android:id="@+id/option2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Medium"
            android:textColor="@android:color/white"
            tools:layout_editor_absoluteX="53dp"
            tools:layout_editor_absoluteY="209dp" />

        <RadioButton
            android:id="@+id/option3"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Large"
            android:textColor="@android:color/white"
            tools:layout_editor_absoluteX="53dp"
            tools:layout_editor_absoluteY="263dp" />
    </RadioGroup>

    <Button
        android:id="@+id/newGameButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="NEW GAME"
        app:layout_constraintTop_toBottomOf="@+id/radioLevelGroup"
        tools:layout_editor_absoluteX="148dp" />

</android.support.constraint.ConstraintLayout>

activity_gameXML

<?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=".gameActivity">
    <view
        android:layout_width="fill_parent"
        android:layout_height="569dp"
        class="com.example.omer.battleship.BoardView"
        android:id="@+id/boardView"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true" />
</android.support.constraint.ConstraintLayout>

Logcat

2018-12-01 13:50:17.755 10098-10098/com.example.omer.battleship I/art: Not late-enabling -Xcheck:jni (already on)
2018-12-01 13:50:17.755 10098-10098/com.example.omer.battleship W/art: Unexpected CPU variant for X86 using defaults: x86
2018-12-01 13:50:17.870 10098-10098/com.example.omer.battleship W/System: ClassLoader referenced unknown path: /data/app/com.example.omer.battleship-1/lib/x86
2018-12-01 13:50:17.892 10098-10098/com.example.omer.battleship I/InstantRun: starting instant run server: is main process
2018-12-01 13:50:18.025 10098-10098/com.example.omer.battleship W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
2018-12-01 13:50:18.646 10098-10117/com.example.omer.battleship I/OpenGLRenderer: Initialized EGL, version 1.4
2018-12-01 13:50:18.646 10098-10117/com.example.omer.battleship D/OpenGLRenderer: Swap behavior 1
2018-12-01 13:50:18.647 10098-10117/com.example.omer.battleship W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2018-12-01 13:50:18.647 10098-10117/com.example.omer.battleship D/OpenGLRenderer: Swap behavior 0
2018-12-01 13:50:18.741 10098-10117/com.example.omer.battleship D/EGL_emulation: eglCreateContext: 0x9f78eda0: maj 2 min 0 rcv 2
2018-12-01 13:50:18.773 10098-10117/com.example.omer.battleship D/EGL_emulation: eglMakeCurrent: 0x9f78eda0: ver 2 0 (tinfo 0x9f790660)
2018-12-01 13:50:18.827 10098-10098/com.example.omer.battleship W/art: Before Android 4.1, method int android.support.v7.widget.DropDownListView.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
2018-12-01 13:50:18.862 10098-10117/com.example.omer.battleship D/EGL_emulation: eglMakeCurrent: 0x9f78eda0: ver 2 0 (tinfo 0x9f790660)
2018-12-01 13:50:24.916 10098-10098/com.example.omer.battleship D/AndroidRuntime: Shutting down VM
2018-12-01 13:50:24.917 10098-10098/com.example.omer.battleship E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.omer.battleship, PID: 10098
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.omer.battleship.GameCell.setCellHeight(int)' on a null object reference
        at com.example.omer.battleship.BoardView.onDraw(BoardView.java:58)
        at android.view.View.draw(View.java:17071)
        at android.view.View.updateDisplayListIfDirty(View.java:16053)
        at android.view.View.draw(View.java:16837)
        at android.view.ViewGroup.drawChild(ViewGroup.java:3764)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3550)
        at android.support.constraint.ConstraintLayout.dispatchDraw(ConstraintLayout.java:2023)
        at android.view.View.updateDisplayListIfDirty(View.java:16048)
        at android.view.View.draw(View.java:16837)
        at android.view.ViewGroup.drawChild(ViewGroup.java:3764)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3550)
        at android.view.View.updateDisplayListIfDirty(View.java:16048)
        at android.view.View.draw(View.java:16837)
        at android.view.ViewGroup.drawChild(ViewGroup.java:3764)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3550)
        at android.view.View.updateDisplayListIfDirty(View.java:16048)
        at android.view.View.draw(View.java:16837)
        at android.view.ViewGroup.drawChild(ViewGroup.java:3764)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3550)
        at android.view.View.updateDisplayListIfDirty(View.java:16048)
        at android.view.View.draw(View.java:16837)
        at android.view.ViewGroup.drawChild(ViewGroup.java:3764)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3550)
        at android.view.View.updateDisplayListIfDirty(View.java:16048)
        at android.view.View.draw(View.java:16837)
        at android.view.ViewGroup.drawChild(ViewGroup.java:3764)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3550)
        at android.view.View.draw(View.java:17074)
        at com.android.internal.policy.DecorView.draw(DecorView.java:751)
        at android.view.View.updateDisplayListIfDirty(View.java:16053)
        at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:656)
        at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:662)
        at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:770)
        at android.view.ViewRootImpl.draw(ViewRootImpl.java:2796)
        at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2604)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2211)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6301)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
        at android.view.Choreographer.doCallbacks(Choreographer.java:683)
        at android.view.Choreographer.doFrame(Choreographer.java:619)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        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:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...