2013-06-20 177 views
0

我在我的Android應用程序中調用了以下代碼。當我在舊的三星Dart上運行它時(api < 13),我得到一個NullPointer異常,如下所述。基於設備屏幕大小的Android調整大小

是否有一個特定的原因代碼是爲它上面的四行工作,但不是它獲得NullPointer的行?

@SuppressLint("NewApi") 
@SuppressWarnings("deprecation") 
public void adjustSize() { 
    int width, height; 

    Display display = getWindowManager().getDefaultDisplay(); 
    if (android.os.Build.VERSION.SDK_INT >= 13) { 
     Point size = new Point(); 
     display.getSize(size); 
     width = size.x; 
     height = size.y; 
    } else { 
     width = display.getWidth(); // deprecated 
     height = display.getHeight(); // deprecated 
    } 

    ImageView counties = (ImageView) findViewById(R.id.btnCounties); 
    ImageView members = (ImageView) findViewById(R.id.btnMembers); 
    ImageView webLink = (ImageView) findViewById(R.id.btnWebLink); 
    ImageView logo = (ImageView) findViewById(R.id.logo); 

    // Calculate image sizes 
    if (height > width) { 
     counties.getLayoutParams().height = (int) (width/2.5); 
     counties.getLayoutParams().width = (int) (width/2.5); 
     members.getLayoutParams().height = (int) (width/2.5); 
     members.getLayoutParams().width = (int) (width/2.5); 

     webLink.getLayoutParams().height = (int) ((width/2.4)/3.5); // Null pointer error 
     webLink.getLayoutParams().width = (int) (width/2.4); 
     logo.getLayoutParams().height = (int) (height/6); 
     logo.getLayoutParams().width = width; 
    } else { 
     counties.getLayoutParams().height = (int) (height/2.5); 
     counties.getLayoutParams().width = (int) (height/2.5); 
     members.getLayoutParams().height = (int) (height/2.5); 
     members.getLayoutParams().width = (int) (height/2.5); 
    } 
} 

回答

1

簡單,

ImageView webLink = (ImageView) findViewById(R.id.btnWebLink); 

webLink

檢查您的佈局xml:您確定名稱(btnWebLink)是否正確?你確定你正在加載正確的佈局xml文件嗎?

Probabily你有一個佈局ImageView但Android是加載佈局爲特定的屏幕尺寸那裏沒有btnWebLink。

在該行中有斷點並檢查變量webLink是否爲空。

空指針異常來第一次您嘗試使用該變量。

+0

謝謝!這正是應用程序的錯誤。 – mjhouseman

+0

它總是發生在我身上! ;) –

相關問題