空异常标志

时间:2015-10-13 18:43:15

标签: java android

我在理解Null引用被标记的原因时遇到了一些问题:

package com.example.adam.bcapplication;

import android.app.Activity;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements SensorEventListener {
    //Define thread handler for the main UI thread

    //define global variable types
    int counter = 9;
    String strcounter;
    int buttoncounter = 0;
    String strbcounter;

    //Define the sensor Manager
    SensorManager sm;

    //Define the Motion Sensor objects
    Sensor accelerometer;
    Sensor gravity;
    Sensor gyroscope;
    Sensor uncalgyro;
    Sensor lineaccel;
    Sensor rotatevector;
    Sensor sigmotion;
    Sensor stepcounter;
    Sensor stepdetector;
    //Define the changing Motion Sensor text values

    //Define the position sensor objects
    Sensor gamerotatevector;

    //Define the changing Position sensor objects
    TextView gamerotatesense;
    //may need these
    final ImageButton button1 = (ImageButton) findViewById(R.id.motbut_unpressed);
    final ImageView topbar2 = (ImageView) findViewById(R.id.topbarmain);
    final ImageButton button2 = (ImageButton) findViewById(R.id.posbut_unpressed);
    final ImageButton button3 = (ImageButton) findViewById(R.id.envbut_unpressed);
    final LinearLayout bcfield = (LinearLayout) findViewById(R.id.babcocklayout);
    final ImageButton arrowup = (ImageButton) findViewById(R.id.uparrow);
    final ImageButton arrowdown = (ImageButton) findViewById(R.id.downarrow);
    final ImageView navbar = (ImageView) findViewById(R.id.infospace);
    final TextView dynamictext = (TextView) findViewById(R.id.dynamictxt);
    final TextView dynamicheader = (TextView) findViewById(R.id.dynamiched);
    private final Handler handler = new Handler();

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

        //Global counter variables
        counter = 9;
        strcounter = Integer.toString(counter);
        buttoncounter = 0;
        strbcounter = Integer.toString(buttoncounter);
        //Set Nav bar invisible for now
        arrowup.setVisibility(View.GONE);
        arrowdown.setVisibility(View.GONE);
        navbar.setVisibility(View.GONE);
        dynamictext.setVisibility(View.GONE);
        dynamicheader.setVisibility(View.GONE);
        sm = (SensorManager) getSystemService(SENSOR_SERVICE);


        button1.setOnClickListener( //This is for the motion button
                new ImageButton.OnClickListener() {
                    public void onClick(View v) {
                        new Thread(new button1task()).start();
                        dynamicheader.setText("Acceleration:");
                        //Now we need to register unregister the sensors and whatnot
                        accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
                        if (sm.getSensorList(Sensor.TYPE_ACCELEROMETER).size() != 0) { // Add check to see if we have this sensor
                            sm.registerListener(MainActivity.this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
                        } else if (sm.getSensorList(Sensor.TYPE_ACCELEROMETER).size() == 0) {
                            dynamictext.setText("Sensor not detected");
                        }

                    }
                }
        );

然后是如下设置的runnable:

    private class button1task implements Runnable { //This is button task on new thread inside UI
        public void run() {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    button1.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.motionbutton_pressed, null));
                    topbar2.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.topbarmotion, null));
                    bcfield.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.logoandbarmotion, null));
                    //make sure the other two buttons are normal again
                    button2.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.positionbutton_normal, null));
                    button3.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.envirobutton_normal, null));
                    //make the arrows and infospace appear
                    arrowup.setVisibility(View.VISIBLE);
                    arrowdown.setVisibility(View.VISIBLE);
                    navbar.setVisibility(View.VISIBLE);
                    //Dynamic text appearance
                    //set the text inside infospace
                    dynamicheader.setVisibility(View.VISIBLE);
                    dynamictext.setVisibility(View.VISIBLE);
                }
            });
        }

    }

这标志着这个:

10-13 18:08:26.845    2345-2345/com.example.savag.babcockapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.savag.babcockapplication, PID: 2345
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.savag.babcockapplication/com.example.savag.babcockapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
            at android.app.ActivityThread.-wrap11(ActivityThread.java)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
            at android.app.Activity.findViewById(Activity.java:2090)
            at com.example.savag.babcockapplication.MainActivity.<init>(MainActivity.java:51)
            at java.lang.Class.newInstance(Native Method)
            at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
            at android.app.ActivityThread.-wrap11(ActivityThread.java)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
10-13 18:08:31.597    2345-2345/? I/Process﹕ Sending signal. PID: 2345 SIG: 9

此错误指的是顶部的第一个(可能是所有)声明。 现在这是我没有得到的......我没有正确宣布这些吗? 我说xml中的按钮是一个特定的id。我的意思是它是一个视图或小部件所以我不能设置为int或字符串可以吗?此外,我不明白为什么这是一个空指针,我不指向xml设计中的按钮?

我看过几个对new这个词的引用,但似乎没有一个对我有用。奇怪的是,如果没有处理程序,如果处理程序中的所有代码都在button1中写入条件以及声明...代码运行得很好。

1 个答案:

答案 0 :(得分:0)

您应该声明不同的UI视图(button1等),并且在调用onCreate之后,setContentView方法中应该进行分配,因为在您为活动setContentView执行视图之前不可用,因为它们是null,无论何时您尝试访问它们,您都会看到崩溃。

您需要替换这些

final ImageButton button1 = (ImageButton) findViewById(R.id.motbut_unpressed);
final ImageView topbar2 = (ImageView) findViewById(R.id.topbarmain);
final ImageButton button2 = (ImageButton) findViewById(R.id.posbut_unpressed);
final ImageButton button3 = (ImageButton) findViewById(R.id.envbut_unpressed);
final LinearLayout bcfield = (LinearLayout) findViewById(R.id.babcocklayout);
final ImageButton arrowup = (ImageButton) findViewById(R.id.uparrow);
final ImageButton arrowdown = (ImageButton) findViewById(R.id.downarrow);
final ImageView navbar = (ImageView) findViewById(R.id.infospace);
final TextView dynamictext = (TextView) findViewById(R.id.dynamictxt);
final TextView dynamicheader = (TextView) findViewById(R.id.dynamiched);

ImageButton button1;
ImageView topbar2;
ImageButton button2;
ImageButton button3;
LinearLayout bcfield;
ImageButton arrowup;
ImageButton arrowdown;
ImageView navbar;
TextView dynamictext;
TextView dynamicheader;

并在onCreate之后的setContentView函数内执行此类

之类的任务
    button1 = (ImageButton) findViewById(R.id.motbut_unpressed);
    topbar2 = (ImageView) findViewById(R.id.topbarmain);
    button2 = (ImageButton) findViewById(R.id.posbut_unpressed);
    button3 = (ImageButton) findViewById(R.id.envbut_unpressed);
    bcfield = (LinearLayout) findViewById(R.id.babcocklayout);
    arrowup = (ImageButton) findViewById(R.id.uparrow);
    arrowdown = (ImageButton) findViewById(R.id.downarrow);
    navbar = (ImageView) findViewById(R.id.infospace);
    dynamictext = (TextView) findViewById(R.id.dynamictxt);
    dynamicheader = (TextView) findViewById(R.id.dynamiched);