2014-03-26 46 views
0

在我的應用程序中創建了一個ImageView並希望不斷旋轉它,但是當我嘗試在手機上運行應用程序時,它立即崩潰。這裏是我的代碼:Android應用程序在試圖連續旋轉圖像時崩潰

的Java活動文件:

public class FrontPage extends ActionBarActivity { 

ImageView iv; 

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

    RotateAnimation rotateAnimation1 = new RotateAnimation(0, 360, 
      Animation.RELATIVE_TO_SELF, 0.5f, 
      Animation.RELATIVE_TO_SELF, 0.5f); 
    rotateAnimation1.setInterpolator(new LinearInterpolator()); 
    rotateAnimation1.setDuration(2000); 
    rotateAnimation1.setRepeatCount(Animation.INFINITE); 
    iv.startAnimation(rotateAnimation1); 
} 

private void initialize() { 

    iv = (ImageView) findViewById(R.id.motorolaLogo); 

} 

XML文件:

<RelativeLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     > 

     <ImageView 
      android:layout_gravity="center_horizontal" 
      android:layout_height="150dp" 
      android:layout_width="150dp" 
      android:layout_marginTop="30dp" 
      android:id="@+id/motorolaLogo" 
      android:src="@drawable/motologo" 
      /> 

    </RelativeLayout> 

回答

0

你永遠不會初始化iv。這是一個Null Pointer Exception

空指針異常是嘗試使用空對象。在你的情況下,你聲明ImageView的iv,但從來沒有給它分配一個值。之後,您嘗試使用其中一種方法,但由於未正確初始化,因此它的寫法相當於null.startAnimation(rotateAnimation1);

爲了避免這些類型的錯誤,您只需確保您的對象在嘗試之前分配了適當的值使用他們的方法...

* *修正後討論 你膨脹了錯誤的XML。取而代之的

setContentView(R.layout.activity_front_page); 

你需要有

setContentView(R.layout.fragment_front_page); 

否則,您Activity將永遠找不到正確的對象。

+0

請您詳細說明一下嗎?你的答案很短。 – bjb568

+0

@ bjb568我恭敬地不同意。 user3462023問他爲什麼應用程序崩潰,我回答了原因。 – DigCamara

+0

什麼是空指針異常?我如何避免它?還有什麼我應該知道的?有沒有這方面的文件? – bjb568