2015-01-03 94 views
0

我進入另一個問題又來了,這次它更加混亂:setTypeface NullPointerException異常

public class MainActivity extends Activity { 
    TextView cityData; 
    TextView updatedData; 
    TextView detailsData; 
    TextView currentTemperatureData; 
    TextView weatherIcon; 
    Typeface weatherIcons; 
    Handler handleWeather; 

    public MainActivity() { 
     handleWeather = new Handler(); 
    } 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     cityData = (TextView) findViewById(R.id.city_field); 
     updatedData = (TextView) findViewById(R.id.updated_field); 
     detailsData = (TextView) findViewById(R.id.details_field); 
     currentTemperatureData = (TextView) findViewById(R.id.current_temperature_field); 
     weatherIcon = (TextView) findViewById(R.id.weather_icon); 

     weatherIcons = Typeface.createFromAsset(getAssets(), "weather.ttf"); //fonts found from https://github.com/erikflowers/weather-icons 
     weatherIcon.setTypeface(weatherIcons); 

在這裏,在這個代碼,我的錯誤在於weatherIcon.setTypeface(weatherIcons);,它接收即使一個NullPointerException我在長時間的搜索之後切換了最後兩行的位置,這些行的起源我找不到。 (在stackoverflow上搜索答案也是如此) 你知道是什麼原因導致了這個錯誤,你能幫我指出嗎?

+0

我認爲你有一個關於一個活動是如何工作的誤解。不要使用'Activity'構造函數來初始化變量(並且不提及對'setContentView'缺少的調用),它有它自己的生命週期。 –

回答

1

您忘記了爲您的活動提供佈局。你必須調用

setContentView(R.layout.activity) 

活動是單一的,集中的一點是,用戶可以做。幾乎 所有活動都與用戶進行交互,因此活動類需要 爲您創建一個窗口,您可以在其中使用您的界面 setContentView(View)

您可以閱讀更多here

+0

是的!是的,它的工作!我不知道'setContentView'與'onCreate'結合在一起。非常感謝! – blaberer

0

試試下面修改後的代碼:

public class MainActivity extends Activity { 
     TextView cityData; 
     TextView updatedData; 
     TextView detailsData; 
     TextView currentTemperatureData; 
     TextView weatherIcon; 
     Typeface weatherIcons; 
     Handler handleWeather; 

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

      cityData = (TextView) findViewById(R.id.city_field); 
      updatedData = (TextView) findViewById(R.id.updated_field); 
      detailsData = (TextView) findViewById(R.id.details_field); 
      currentTemperatureData = (TextView) findViewById(R.id.current_temperature_field); 
      weatherIcon = (TextView) findViewById(R.id.weather_icon); 

      weatherIcons = Typeface.createFromAsset(getAssets(), "weather.ttf"); //fonts found from https://github.com/erikflowers/weather-icons 
      weatherIcon.setTypeface(weatherIcons); 
+0

是的!這也適用! 'setContentView'對整個'onCreate'很重要! – blaberer

+0

請務必在設置View的組件之前調用setContentView() – VicJordan