setTypeface 空指针异常

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);,即使我切换了最后两行的位置,我也收到了一个N​​ullPointerException,但我已经很久找不到它的来源了搜索。 (在 Whosebug 上搜索答案也是如此) 你知道是什么导致了这个错误吗,你能帮我指出来吗?

您忘记为 activity 提供布局。你得打电话

setContentView(R.layout.activity)

An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View).

您可以阅读更多内容here

尝试以下修改后的代码:

    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);