输入活动时出现空指针异常

时间:2013-10-05 22:15:51

标签: android nullpointerexception

当我开始这个活动时,我得到一个空指针exveption,我遇到了一些问题,找到了罪魁祸首。此活动位于我的清单文件中。此活动依赖于三个类。其中一个活动扩展了线程类。这些课程不在我的清单中。

的活动:

package com.example.soft;

import com.example.soft.util.SystemUiHider;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;


public class PlayGame extends Activity {
    private static final boolean AUTO_HIDE = true;
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
    private static final boolean TOGGLE_ON_CLICK = true;
    private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
    private SystemUiHider mSystemUiHider;

    private GraphicsMole im;
    private int currentMolePos = -1;
    private int scoreCurr = 0;
    private int lifeCurr = 9;
    private Handler step;
    private Handler Update;
    private MoleGame mg;
    private boolean isMole = true;
    private Mole mole = new Mole();
    private double prob=0.7;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setRequestedOrientation(0);//Horizontal Screen Orientation      
        setContentView(R.layout.activity_play_game);

        final View controlsView = findViewById(R.id.fullscreen_content_controls);
        final View contentView = findViewById(R.id.fullscreen_content);

        final TextView scoreTview = (TextView) findViewById(R.id.Score);
        final TextView lifeTview = (TextView) findViewById(R.id.Life);
        final GridView gw = (GridView) findViewById(R.id.gridview);
        step = new ChangeImage();
        Update = new Handler();
        im = new GraphicsMole(this);
        gw.setAdapter(im);

        // ----------------------------

        mSystemUiHider = SystemUiHider.getInstance(this, contentView,
                HIDER_FLAGS);
        mSystemUiHider.setup();
        mSystemUiHider
                .setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
                    // Cached values.
                    int mControlsHeight;
                    int mShortAnimTime;

                    @Override
                    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
                    public void onVisibilityChange(boolean visible) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
                            if (mControlsHeight == 0) {
                                mControlsHeight = controlsView.getHeight();
                            }
                            if (mShortAnimTime == 0) {
                                mShortAnimTime = getResources().getInteger(
                                        android.R.integer.config_shortAnimTime);
                            }
                            controlsView
                                    .animate()
                                    .translationY(visible ? 0 : mControlsHeight)
                                    .setDuration(mShortAnimTime);
                        } else {
                            controlsView.setVisibility(visible ? View.VISIBLE
                                    : View.GONE);
                        }

                        if (visible && AUTO_HIDE) {
                            delayedHide(AUTO_HIDE_DELAY_MILLIS);
                        }
                    }
                });

        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TOGGLE_ON_CLICK) {
                    mSystemUiHider.toggle();
                } else {
                    mSystemUiHider.show();
                }
            }
        });

        gw.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, final View v,
                    int position, long id) {
                if (currentMolePos == position) {

                    Update.post(new Runnable() {

                        @Override
                        public void run() {

                            if (isMole == true) {
                                scoreCurr = scoreCurr + 150;
                                scoreTview.setText("Score: " + scoreCurr);
                                scoreTview.refreshDrawableState();
                                if(scoreCurr==3000){
                                    setProbability(0.60);
                                    mg.setTimeToWait(700);

                                }
                                else if(scoreCurr==7500){
                                    setProbability(0.45);
                                    mg.setTimeToWait(500);
                                }
                            } 
                            else {
                                lifeCurr = lifeCurr - 1;
                                lifeTview.setText("Life: " + lifeCurr);
                                lifeTview.refreshDrawableState();
                                if (lifeCurr == 0) {
                                    mg.stopThread();

                                    Intent gameOverIntent = new Intent(
                                            PlayGame.this, GameMenu.class);
                                    gameOverIntent.putExtra("score", scoreCurr);
                                    startActivity(gameOverIntent);
                                    finish();

                                }
                            }

                        }
                    });
                }
            }
        });
        mg = new MoleGame(step);
        mg.start();
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }
    View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (AUTO_HIDE) {
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
            return false;
        }
    };

    Handler mHideHandler = new Handler();
    Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            mSystemUiHider.hide();
        }
    };
private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }

public Activity getActivity(){
        return this.getActivity();
    }
    private class ChangeImage extends Handler {
        Hole hole = new Hole();
        private int oldPosition = -1;

        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();

            currentMolePos = bundle.getInt("newPosition");
            if (Math.random() < prob) {
                im.setItem(currentMolePos, mole.getmole());
                isMole = true;
            } 
            else {
                im.setItem(currentMolePos, mole.getphone());
                isMole = false;
            }

            if (oldPosition != -1 && currentMolePos != oldPosition) {
                im.setItem(oldPosition, hole.getHole());
            }

            oldPosition = currentMolePos;
            im.notifyDataSetChanged();
        }
    }
    public void setProbability(double prob){
        this.prob=prob;
    }
}

logcat的:

10-06 18:04:46.975: E/AndroidRuntime(3636): FATAL EXCEPTION: main
10-06 18:04:46.975: E/AndroidRuntime(3636): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.quitandbefree/com.example.quitandbefree.PlayGame}: java.lang.NullPointerException
10-06 18:04:46.975: E/AndroidRuntime(3636):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1939)
10-06 18:04:46.975: E/AndroidRuntime(3636):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1960)
10-06 18:04:46.975: E/AndroidRuntime(3636):     at android.app.ActivityThread.access$1500(ActivityThread.java:145)
10-06 18:04:46.975: E/AndroidRuntime(3636):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1045)
10-06 18:04:46.975: E/AndroidRuntime(3636):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-06 18:04:46.975: E/AndroidRuntime(3636):     at android.os.Looper.loop(Looper.java:150)
10-06 18:04:46.975: E/AndroidRuntime(3636):     at android.app.ActivityThread.main(ActivityThread.java:4369)
10-06 18:04:46.975: E/AndroidRuntime(3636):     at java.lang.reflect.Method.invokeNative(Native Method)
10-06 18:04:46.975: E/AndroidRuntime(3636):     at java.lang.reflect.Method.invoke(Method.java:507)
10-06 18:04:46.975: E/AndroidRuntime(3636):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:846)
10-06 18:04:46.975: E/AndroidRuntime(3636):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)
10-06 18:04:46.975: E/AndroidRuntime(3636):     at dalvik.system.NativeStart.main(Native Method)
10-06 18:04:46.975: E/AndroidRuntime(3636): Caused by: java.lang.NullPointerException
10-06 18:04:46.975: E/AndroidRuntime(3636):     at com.example.quitandbefree.PlayGame.onCreate(PlayGame.java:129)
10-06 18:04:46.975: E/AndroidRuntime(3636):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
10-06 18:04:46.975: E/AndroidRuntime(3636):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1891)
10-06 18:04:46.975: E/AndroidRuntime(3636):     ... 11 more

EDIT! XML布局:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/shadedbackground"
    tools:context=".PlayGame" >

    <!--
         The primary full-screen view. This can be replaced with whatever view
         is needed to present your content, e.g. VideoView, SurfaceView,
         TextureView, etc.
    -->

<!-- <ViewFlipper android:id="@+id/flipper" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"> 
    </ViewFlipper> 
    -->
    <TextView android:id="@+id/Score" android:layout_width="70px"
        android:layout_height="50px" android:text="Score: "
        android:textColor="#FF0000" android:textStyle="bold" android:textSize="15px">

    </TextView>
    <TextView android:id="@+id/Life" android:layout_width="70px"
        android:layout_gravity="right"
        android:layout_height="50px" android:text="Life: "
        android:textColor="#FF0000" android:textSize="15px" android:textStyle="bold">

    </TextView>

    <GridView android:id="@+id/gridview" android:numColumns="4"
        android:layout_marginTop="10dp"
        android:verticalSpacing="0px" android:horizontalSpacing="0px"
        android:stretchMode="columnWidth" android:gravity="center"
        android:layout_width="fill_parent" android:layout_height="600px">

    </GridView>

    <!--
         This FrameLayout insets its children based on system windows using
         android:fitsSystemWindows.
    -->



</FrameLayout>

2 个答案:

答案 0 :(得分:3)

xml布局中没有fullscreen_content视图,所以

findViewById(R.id.fullscreen_content);

返回null

contentView.setOnClickListener(new View.OnClickListener() {

抛出NullPointerException

答案 1 :(得分:1)

根据ssantos的回答,你没有fullscreen_content和fullscreen_content_controls 所以以下两个都是null;

final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);

可能是由于这个

  setRequestedOrientation(0);//Horizontal Screen Orientation 

用户

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);