首页 > 解决方案 > 如何在android studio中修复java中的java运行时异常?

问题描述

这一定是一个简单的问题,我不明白如何解决。我正在制作一个程序,该程序通过使用单元格(正方形)并随机洗牌来随机生成迷宫。当我尝试运行代码时它崩溃并在 logcat 中给了我这个:

    2020-05-05 01:34:14.798 5891-5891/com.example.maze E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.maze, PID: 5891
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.maze/com.example.maze.MainActivity}: android.view.InflateException: Binary XML file line #19 in com.example.maze:layout/activity_main: Binary XML file line #19 in com.example.maze:layout/activity_main: Error inflating class com.example.maze.GameView
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3333)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3477)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2043)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7464)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:955)
     Caused by: android.view.InflateException: Binary XML file line #19 in com.example.maze:layout/activity_main: Binary XML file line #19 in com.example.maze:layout/activity_main: Error inflating class com.example.maze.GameView
     Caused by: android.view.InflateException: Binary XML file line #19 in com.example.maze:layout/activity_main: Error inflating class com.example.maze.GameView
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at android.view.LayoutInflater.createView(LayoutInflater.java:852)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1004)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1121)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:555)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:161)
        at com.example.maze.MainActivity.onCreate(MainActivity.java:12)
        at android.app.Activity.performCreate(Activity.java:7990)
        at android.app.Activity.performCreate(Activity.java:7979)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3308)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3477)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2043)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7464)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:955)
     Caused by: java.lang.OutOfMemoryError: Failed to allocate a 167772176 byte allocation with 8388608 free bytes and 110MB until OOM, target footprint 93743400, growth limit 201326592
        at java.util.Arrays.copyOf(Arrays.java:3136)
        at java.util.Arrays.copyOf(Arrays.java:3106)
    2020-05-05 01:34:14.799 5891-5891/com.example.maze E/AndroidRuntime:     at java.util.Vector.grow(Vector.java:266)
        at java.util.Vector.ensureCapacityHelper(Vector.java:246)
        at java.util.Vector.addElement(Vector.java:620)
        at java.util.Stack.push(Stack.java:67)
        at com.example.maze.GameView.createMaze(GameView.java:108)
        at com.example.maze.GameView.<init>(GameView.java:34)
            ... 28 more

下面是我的程序。我认为问题出在 stack.push(current) 代码行(java 108)。该程序不在主要活动类中。创建项目时,我没有触及主要的活动类。这是在它自己的名为 GameView 的类中。

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.Random;
import java.util.Stack;

public class GameView extends View {
    private Cell[][] cells;
    private static final int COLS = 14, ROWS = 5;
    private static final float WALL_THICKNESS = 4;
    private float cellSize, hMargin, vMargin;
    private Paint wallPaint;
    private Random random;

    public GameView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        wallPaint = new Paint();
        wallPaint.setColor(Color.BLACK);
        wallPaint.setStrokeWidth(WALL_THICKNESS);

        random = new Random();

        createMaze();
    }

    private Cell getNeighbor(Cell cell) {
        ArrayList<Cell> neighbors = new ArrayList<>();

        //left neighbor
        if(cell.col > 0)
            if(!cells[cell.col-1][cell.row].visited)
                neighbors.add(cells[cell.col-1][cell.row]);

        //right neighbor
        if(cell.col < COLS-1)
            if(!cells[cell.col+1][cell.row].visited)
                neighbors.add(cells[cell.col+1][cell.row]);

        //top neighbor
        if(cell.row > 0)
            if(!cells[cell.col][cell.row-1].visited)
                neighbors.add(cells[cell.col][cell.row-1]);

        //bottom neighbor
        if(cell.row < ROWS-1)
            if(!cells[cell.col][cell.row+1].visited)
                neighbors.add(cells[cell.col][cell.row+1]);

        if(neighbors.size() > 0) {
            int index = random.nextInt(neighbors.size());
            return neighbors.get(index);
        }
        return null;
    }

    private void removeWall(Cell current, Cell next) {
        if(current.col == next.col && current.row == next.row+1) {
            current.topWall = false;
            next.bottomWall = false;
        }

        if(current.col == next.col && current.row == next.row-1) {
            current.bottomWall = false;
            next.topWall = false;
        }

        if(current.col == next.col+1 && current.row == next.row) {
            current.leftWall = false;
            next.rightWall = false;
        }

        if(current.col == next.col-1 && current.row == next.row) {
            current.rightWall = false;
            next.leftWall = false;
        }
    }

    private void createMaze() {
        Stack<Cell> stack = new Stack<>();
        Cell current, next;

        cells = new Cell[COLS][ROWS];

        for(int x = 0; x < COLS; x++) {
            for(int y = 0; y < ROWS; y++) {
                cells[x][y] = new Cell(x, y);
            }
        }

        current = cells[0][0];
        current.visited = true;

        next = getNeighbor(current);
        do {
            if(next != null) {
                removeWall(current, next);
                stack.push(current);
                current = next;
                current.visited = true;
            } else
                current = stack.pop();
        } while(!stack.empty());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //super.onDraw(canvas);
        canvas.drawColor(Color.GREEN);

        int width = getWidth();
        int height = getHeight();

        if(width/height < COLS/ROWS)
            cellSize = width/(COLS+1);
        else
            cellSize = height/(ROWS+1);

        hMargin = (width - COLS * cellSize)/2;
        vMargin = (height-ROWS * cellSize)/2;

        canvas.translate(hMargin, vMargin);

        for(int x = 0; x < COLS; x++) {
            for(int y = 0; y < ROWS; y++) {
                if(cells[x][y].topWall)
                    canvas.drawLine(
                            x * cellSize,
                            y * cellSize,
                            (x+1) * cellSize,
                            y * cellSize,
                            wallPaint);

                if(cells[x][y].leftWall)
                    canvas.drawLine(
                            x * cellSize,
                            y * cellSize,
                            x * cellSize,
                            (y+1) * cellSize,
                            wallPaint);

                if(cells[x][y].bottomWall)
                    canvas.drawLine(
                            x * cellSize,
                            (y+1) * cellSize,
                            (x+1) * cellSize,
                            (y+1) * cellSize,
                            wallPaint);

                if(cells[x][y].rightWall)
                    canvas.drawLine(
                            (x+1) * cellSize,
                            y * cellSize,
                            (x+1) * cellSize,
                            (y+1) * cellSize,
                            wallPaint);
            }
        }
    }

    private class Cell {
        boolean
                topWall = true,
                leftWall = true,
                bottomWall = true,
                rightWall = true,
                visited = false;

        int col, row;

        public Cell(int col, int row) {
            this.col = col;
            this.row = row;
        }
    }
}

标签: java

解决方案


这是堆栈跟踪的相关部分:

Caused by: java.lang.OutOfMemoryError: Failed to allocate a 167772176 byte allocation with 8388608 free bytes and 110MB until OOM, target footprint 93743400, growth limit 201326592
    at java.util.Arrays.copyOf(Arrays.java:3136)
    at java.util.Arrays.copyOf(Arrays.java:3106)
    at java.util.Vector.grow(Vector.java:266)
    at java.util.Vector.ensureCapacityHelper(Vector.java:246)
    at java.util.Vector.addElement(Vector.java:620)
    at java.util.Stack.push(Stack.java:67)
    at com.example.maze.GameView.createMaze(GameView.java:108)
    at com.example.maze.GameView.<init>(GameView.java:34)

那么堆栈跟踪说明了什么?

  1. 它说应用程序正在尝试分配一个 167Mbyte 数组 (!!),但由于堆已满而失败。

  2. 它说分配发生在尝试创建数组的副本时

  3. 它说这个数组复制发生在它扩展一个Vector

  4. 它说Vector扩展发生在将元素推到Stack.

  5. 它表示Stack正在您的createMaze方法中调用推送。

简而言之,您的createMaze方法已经创建了一个Stack目前有数百万个元素深的......到目前为止。

问题出在这个循环中:

    do {
        if (next != null) {
            removeWall(current, next);
            stack.push(current);
            current = next;
            current.visited = true;
        } else
            current = stack.pop();
    } while(!stack.empty());

如果next不是null,你“推”,否则你“弹出”。但是你在哪里改变 next循环?


推荐阅读