2012-01-20 108 views
0

我有一個Nullpointer異常與此代碼,它工作清楚。例外情況顯示在mainLayout.setOnTouchListener(this),但我不明白爲什麼。一個在另一個活動:空指針異常setOnTouchListener(this)

public class Assistantbuilder extends Activity implements OnTouchListener 
{ 
    private ViewFlipper flipper = null; 
    private float fromPosition; 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 
     setContentView(R.layout.main); 

     LinearLayout mainLayout = (LinearLayout) findViewById(R.id.main_layout); 
     mainLayout.setOnTouchListener(this); 

     flipper = (ViewFlipper) findViewById(R.id.flipper); 

     LayoutInflater inflater = (LayoutInflater)   getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     int layouts[] = new int[]{ R.layout.dashboard_layout, R.layout.dashboard_layout2, R.layout.dashboard_layout3, R.layout.dashboard_layout4 }; 
     for (int layout : layouts) 
      flipper.addView(inflater.inflate(layout, null)); 

     Button btndimensions_rafters = (Button) findViewById(R.id.home_btn_dimensions_rafters); 
     btndimensions_rafters.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View arg0) { 
       switch (arg0.getId()) { 
       case R.id.home_btn_dimensions_rafters: 
        Intent i = new Intent(Assistantbuilder.this, 
          dimensions_rafters.class); 
        startActivity(i); 
        break; 
       } 
      } 
     }); 
     Button btngable_roof = (Button) findViewById(R.id.home_btn_gable_roof); 
     btngable_roof.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View arg0) { 
       switch (arg0.getId()) { 
       case R.id.home_btn_gable_roof: 
        Intent i = new Intent(Assistantbuilder.this, 
          GableRoof.class); 
        startActivity(i); 
        break; 
       } 
      } 
     }); 

    } 

改變了一些代碼可以在這裏的一些錯誤:

public boolean onTouch(View view, MotionEvent event) 
    { 
     switch (event.getAction()) 
     { 
     case MotionEvent.ACTION_DOWN: 
      fromPosition = event.getX(); 
      break; 
     case MotionEvent.ACTION_UP: 
      float toPosition = event.getX(); 
      if (fromPosition > toPosition) 
      { 
       flipper.setInAnimation(AnimationUtils.loadAnimation(this,R.anim.go_next_in)); 
       flipper.setOutAnimation(AnimationUtils.loadAnimation(this,R.anim.go_next_out)); 
       flipper.showNext(); 
      } 
      else if (fromPosition < toPosition) 
      { 
       flipper.setInAnimation(AnimationUtils.loadAnimation(this,R.anim.go_prev_in)); 
       flipper.setOutAnimation(AnimationUtils.loadAnimation(this,R.anim.go_prev_out)); 
       flipper.showPrevious(); 
      } 
     default: 
      break; 
     } 
     return true; 
    } 
} 

非常感謝。

+0

您是否認爲在不添加異常的情況下,任何人都可以知道它將在哪裏添加一些日誌。 – AAnkit

回答

1

那麼,鑑於該行在您的活動的onCreate中,因此this應始終有效,因此唯一可能爲空的其他項是mainLayout。你有沒有改變你的XML佈局文件?運行時無法找到ID爲main_layoutLinearLayout