java - 烦人的空指针异常

标签 java android nullpointerexception

这是我的主要类(class):

import android.graphics.Rect;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

public final class HomeScreen implements OnTouchListener
{
    public HomeScreen(Viewer view) 
    {
        this.view = view;
        RelativeLayout layout = (RelativeLayout)view.findViewById(R.id.home_screen_lay);
        layout.setOnTouchListener(this); // this is where the error points to
        network.setFocus(this);
        view.setContentView(R.layout.home);
    }

    public boolean onTouch(View v, MotionEvent e) 
    {
        switch(e.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                onPress(v,e);
                break;
            case MotionEvent.ACTION_MOVE:
                onMove(v,e);
                break;
            case MotionEvent.ACTION_UP:
                onRelease(v,e);
                break;
        }
        return true;
    }

    public void onPress(View v, MotionEvent e)
    {
        for(int x=0;x<buttons.length;x++)
        {
            if(buttons[x].contains((int)e.getX(),(int)e.getY()))
            {
                if(buttons[x]==exitRect)
                    view.finish();
                if(buttons[x]==newUserRect)
                    new NewUser(view,network);
                if(buttons[x]==loginRect)
                    new Login(view,network);
            }
        }
    }
    public void onMove(View v, MotionEvent e){}
    public void onRelease(View v, MotionEvent e){}

    public void handleMessage(String message){}
    private NetworkManager network;
    private Viewer view;
    private Rect loginRect;
    private Rect newUserRect;
    private Rect exitRect;
    private Rect[] buttons;
}

这是 home.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/home_screen_lay"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/home_screen">
</RelativeLayout>

NullPointerExeption 指向我的 HomeScreen 类中的该行,它表示布局为空。我已经看了几个小时了,但我看不出有什么问题。其他人可以看到我缺少什么吗?欢迎所有相关答案!

最佳答案

如果你搬家怎么办:

view.setContentView(R.layout.home);

在尝试获取布局对象之前先到方法的顶部?

关于java - 烦人的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6880550/

相关文章:

java - JOptionPane 输入到 int

java - 如何处理 Android 中的 3 个硬键

java - 什么是 NullPointerException,我该如何解决?

java - mapreduce 中 map 任务中的 NullPointer 异常

java - 使用链表实现队列时出现 NullPointerException

java - 忽略/关闭 Jmeter/Java 中的证书验证

java - 按 MM/DD/YYYY 格式的日期对数组列表进行排序

android - 安卓上的图像映射

java - 我想在 quickblox catting 应用程序中发送推送通知

android - 如何设置android目标级别21