2011-07-30 49 views
1

這裏是我的主類:惱人的NullPointerException

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指向我的主屏幕類線,它說,佈局爲空。我一直在看這幾個小時,我不能看到什麼是錯的。其他人能看到我錯過的東西嗎?歡迎所有相關答案!

回答

5

如果你移動:

view.setContentView(R.layout.home); 

該方法的頂部,你試圖讓佈局對象之前?

+0

ohhh yeah thanks!我忘了你必須先做到這一點!謝謝你,我不能相信我錯過了那個。 – gsfd

1

我嘗試在添加任何偵聽器之前設置所有屬性(即layout)。在這個意義上的舉動:

layout.setOnTouchListener(this); 

的方法(可能重複的答案對不起@mharper)的底部。 this正在產生異常,所以在上面的語句中將this更改爲HomeScreen

1

您必須將setContentView方法放在名爲HomeScreen的方法的開頭。

view.setContentView(R.layout.home);