-1

我写了一些简单的游戏,比如打猫。但是当我运行它时它崩溃了。我真的不明白为什么。

MainActivity.java

import android.os.Bundle;
import android.app.Activity;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private static final long duration = 50000;
    private static final long interval = 1500;

    private ImageView[][] gameField = {{(ImageView)findViewById(R.id.enemy1_1),(ImageView)findViewById(R.id.enemy1_2),(ImageView)findViewById(R.id.enemy1_3)},
            {(ImageView)findViewById(R.id.enemy2_1),(ImageView)findViewById(R.id.enemy2_2),(ImageView)findViewById(R.id.enemy2_3)},
            {(ImageView)findViewById(R.id.enemy3_1),(ImageView)findViewById(R.id.enemy3_2),(ImageView)findViewById(R.id.enemy3_3)}};


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

        GameCountDownTimer gameCountDownTimer = new GameCountDownTimer(duration, interval);
        gameCountDownTimer.start();
    }

    public class GameCountDownTimer extends CountDownTimer {

        Game game = new Game();
        ImageView imgLose = (ImageView)findViewById(R.drawable.cat_sing); //Lost cat
        ImageView imgTouch = (ImageView)findViewById(R.drawable.cat_pirate); //Touched cat


        public GameCountDownTimer(long duration, long interval) {
            super(duration, interval);    
        }

        @Override
        public void onFinish() {

            for (int i = 0; i < Game.rows; i++) {
                for (int j = 0; j < Game.cols; j++) {

                    gameField[i][j].setImageResource(0);

                }
            }

            Toast resultToast = Toast.makeText(getApplicationContext(), "You missed " + game.gameScore() + " cats:)",Toast.LENGTH_LONG);
            resultToast.setGravity(Gravity.CENTER, 0, 0);
            resultToast.show();

        }

        @Override
        public void onTick(long millisUntilFinished) {

            boolean[][] newEnemies = game.generateEnemy();
            int score = 0;

            for (int i = 0; i < Game.rows; i++) {
                for (int j = 0; j < Game.cols; j++) {

                    if (gameField[i][j].getResources() == imgLose.getResources()) {
                        score++;                             //Если кот пропущен, увеличиваем счетчик
                    }

                    if (gameField[i][j].getResources() == imgTouch.getResources()) {
                        gameField[i][j].setImageResource(0); //Убираемся за отшлепанными котами
                    }

                    if (newEnemies[i][j]) {
                        gameField[i][j].setImageResource(R.drawable.cat_sing); //Выпускаем новых котов
                    }

                }
            }
            game.setScore(score);

        }
    }
}

游戏.java

import java.util.Random;

/**
 * User: Bringoff
 * Date: 30.10.13
 * Time: 8:07
 */
public class Game {

    static final int cols = 3;
    static final int rows = 3;
    private int score;
    private boolean[][] arEnemies = null;

    public int results = 0;

    public void setScore(int score) {
        this.score+= score;
    }
    public int gameScore() {
        return score;
    }

    public boolean[][] generateEnemy() {
        arEnemies = new boolean[rows][cols];
        Random random = new Random();
        for (int i = 0; i < rows; i++) {
            for (int j = 0; i < cols; j++) {
                arEnemies[i][j] = random.nextBoolean();
            }
        }

        return arEnemies;
    }

}

activity_main.xml

 <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:id="@+id/main_l">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/results_view"
        android:id="@+id/tvResults"
        android:layout_weight="0.75"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:textStyle="bold"
        android:textSize="28dp"
        android:typeface="normal"
        android:gravity="center_vertical|center_horizontal" />

    <TableRow
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1">

        <ImageView
            android:id="@+id/enemy1_1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:scaleType="fitCenter"
            android:onClick="enemies_onClick"></ImageView>

        <ImageView
            android:id="@+id/enemy1_2"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:scaleType="fitCenter"
            android:onClick="enemies_onClick"></ImageView>

        <ImageView
            android:id="@+id/enemy1_3"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:scaleType="fitCenter"
            android:onClick="enemies_onClick"></ImageView>

    </TableRow>

    <TableRow
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1">

        <ImageView
            android:id="@+id/enemy2_1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:scaleType="fitCenter"
            android:onClick="enemies_onClick"></ImageView>

        <ImageView
            android:id="@+id/enemy2_2"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:scaleType="fitCenter"
            android:onClick="enemies_onClick"></ImageView>

        <ImageView
            android:id="@+id/enemy2_3"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:scaleType="fitCenter"
            android:onClick="enemies_onClick"></ImageView>

        </TableRow>

    <TableRow
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1">

        <ImageView
            android:id="@+id/enemy3_1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:scaleType="fitCenter"
            android:onClick="enemies_onClick"></ImageView>

        <ImageView
            android:id="@+id/enemy3_2"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:scaleType="fitCenter"
            android:onClick="enemies_onClick"></ImageView>

        <ImageView
            android:id="@+id/enemy3_3"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:scaleType="fitCenter"
            android:onClick="enemies_onClick"></ImageView>

        </TableRow>

</TableLayout>

崩溃日志:

11-01 09:44:23.810: D/dalvikvm(18847): 延迟启用 CheckJNI 11-01 09:44:23.910: D/AndroidRuntime(18847): 关闭 VM 11-01 09:44:23.910: W/ dalvikvm(18847):threadid = 1:线程以未捕获的异常退出(组= 0x416f6700)11-01 09:44:23.910:E / AndroidRuntime(18847):致命异常:主要11-01 09:44:23.910:E / AndroidRuntime(18847):java.lang.RuntimeException:无法实例化活动 ComponentInfo{com.bringoff.touchthemall/com.bringoff.touchthemall.MainActivity}:java.lang.NullPointerException 11-01 09:44:23.910:E/AndroidRuntime( 18847): 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2137) 11-01 09:44:23.910: E/AndroidRuntime(18847): 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261) 11 -01 09:44:23.910:E/AndroidRuntime(18847):在 android.app.ActivityThread。访问$600(ActivityThread.java:141) 11-01 09:44:23.910: E/AndroidRuntime(18847): 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256) 11-01 09:44:23.910 : E/AndroidRuntime(18847): 在 android.os.Handler.dispatchMessage(Handler.java:99) 11-01 09:44:23.910: E/AndroidRuntime(18847): 在 android.os.Looper.loop(Looper. java:137) 11-01 09:44:23.910: E/AndroidRuntime(18847): 在 android.app.ActivityThread.main(ActivityThread.java:5103) 11-01 09:44:23.910: E/AndroidRuntime(18847) : 在 java.lang.reflect.Method.invokeNative(Native Method) 11-01 09:44:23.910: E/AndroidRuntime(18847): 在 java.lang.reflect.Method.invoke(Method.java:525) 11- 01 09:44:23.910: E/AndroidRuntime(18847): 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 11-01 09:44:23.910: E/AndroidRuntime(18847) : 在 com.android。internal.os.ZygoteInit.main(ZygoteInit.java:553) 11-01 09:44:23.910: E/AndroidRuntime(18847): at dalvik.system.NativeStart.main(Native Method) 11-01 09:44:23.910 : E/AndroidRuntime(18847): 引起: java.lang.NullPointerException 11-01 09:44:23.910: E/AndroidRuntime(18847): 在 android.app.Activity.findViewById(Activity.java:1853) 11-01 09:44:23.910: E/AndroidRuntime(18847): 在 com.bringoff.touchthemall.MainActivity.(MainActivity.java:17) 11-01 09:44:23.910: E/AndroidRuntime(18847): 在 java.lang。 Class.newInstanceImpl(Native Method) 11-01 09:44:23.910: E/AndroidRuntime(18847): at java.lang.Class.newInstance(Class.java:1130) 11-01 09:44:23.910: E/AndroidRuntime (18847): 在 android.app.Instrumentation.newActivity(Instrumentation.java:1061) 11-01 09:44:23.910: E/AndroidRuntime(18847): 在 android.app.ActivityThread。performLaunchActivity(ActivityThread.java:2128) 11-01 09:44:23.910: E/AndroidRuntime(18847): ... 11 更多
4

5 回答 5

0

SO 不是调试器,但由于您的错误非常愚蠢:

您正在尝试在 setContentView 之前使用 findViewById!

此代码在 onCreate 之前执行:

private ImageView[][] gameField = {{(ImageView)findViewById(R.id.enemy1_1),(ImageView)findViewById(R.id.enemy1_2),(ImageView)findViewById(R.id.enemy1_3)},
            {(ImageView)findViewById(R.id.enemy2_1),(ImageView)findViewById(R.id.enemy2_2),(ImageView)findViewById(R.id.enemy2_3)},
            {(ImageView)findViewById(R.id.enemy3_1),(ImageView)findViewById(R.id.enemy3_2),(ImageView)findViewById(R.id.enemy3_3)}};

您所要做的就是将代码更改为

private ImageView[][] gameField;

并在 setContentView 之后添加:

gameField = new ImageView[][]{{(ImageView)findViewById(R.id.enemy1_1),(ImageView)findViewById(R.id.enemy1_2),(ImageView)findViewById(R.id.enemy1_3)},
                {(ImageView)findViewById(R.id.enemy2_1),(ImageView)findViewById(R.id.enemy2_2),(ImageView)findViewById(R.id.enemy2_3)},
                {(ImageView)findViewById(R.id.enemy3_1),(ImageView)findViewById(R.id.enemy3_2),(ImageView)findViewById(R.id.enemy3_3)}};
于 2013-11-01T08:58:43.440 回答
0

你不能这样做

私有 ImageView[][] gameField = {{(ImageView)findViewById(R.id.enemy1_1),(ImageView)findViewById(R.id.enemy1_2),(ImageView)findViewById(R.id.enemy1_3)}, {(ImageView )findViewById(R.id.enemy2_1),(ImageView)findViewById(R.id.enemy2_2),(ImageView)findViewById(R.id.enemy2_3)}, {(ImageView)findViewById(R.id.enemy3_1),(ImageView )findViewById(R.id.enemy3_2),(ImageView)findViewById(R.id.enemy3_3)}};

您应该只保存 id 、 R.id.XXX 并在查询视图时使用 findViewById。

如果视图尚不存在,则无法按 id 查询视图。

于 2013-11-01T08:58:59.033 回答
0

您需要将所有初始化移到onCreate里面setContentView

ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); // must be first
    iv =(ImageView)findViewById(R.id.enemy1_1);  // then initialization
    //  same for the rest of the initializations

如果不膨胀布局,您将无法使用它findViewById来初始化视图。如果没有,你会得到NullPointerException.

于 2013-11-01T08:59:12.347 回答
0

问题就在这里。

private ImageView[][] gameField = {{(ImageView)findViewById(R.id.enemy1_1),(ImageView)findViewById(R.id.enemy1_2),(ImageView)findViewById(R.id.enemy1_3)},
        {(ImageView)findViewById(R.id.enemy2_1),(ImageView)findViewById(R.id.enemy2_2),(ImageView)findViewById(R.id.enemy2_3)},
        {(ImageView)findViewById(R.id.enemy3_1),(ImageView)findViewById(R.id.enemy3_2),(ImageView)findViewById(R.id.enemy3_3)}};

您不能将这些变量初始化为字段。您必须将它们放在 onCreate() 方法中。findViewById() 方法只能在 onCreate 之后使用……更具体地说,在调用 setContentView() 之后(在 onCreate 中)。

于 2013-11-01T09:00:25.543 回答
0

在设置内容视图之前,您不能初始化组件。

你可以这样设置:

    public class MainActivity extends Activity {

        private static final long duration = 50000;
        private static final long interval = 1500;

     // ID of Image View
public static int[] CellID=new int[]{
         R.id.mycell01,R.id.mycell02,R.id.mycell03,R.id.mycell04,
         R.id.mycell05,R.id.mycell06,R.id.mycell07,R.id.mycell08,R.id.mycell09};
     // Image View name
static ImageView img01,img02,img03,img04,img05,img06,img07,img08,img09;
    // Array of ImageView
public static ImageView[] ImageViewImg=new ImageView[]{
        img01,img02,img03,img04,img05,img06,img07,img08,img09};


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    for (int i = 0; i < ImageViewImg.length; i++) {
            ImageViewImg[i]=(ImageView)findViewById(CellID[i]);


        }

        }
于 2013-11-01T09:06:08.667 回答