为什么我必须在函数中而不是在onCreate中调用XML元素



onCreate的完整代码在这里:

//Global variables
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
int expandedGroup = -1;
boolean notification;
boolean vibrate;
String ringtone;
int hour;
int minutes;
int day;
//UI elementi
TextView dan;
TextView ura;
ImageView facebook;
ImageView twitter;
TextView tw1, tw2, tw3, tw4, tw5, tw6, tw7, tw8, tw9, tw10, tw11, tw12, tw13, tw14, tw15, tw16, tw17, tw18, tw19, tw20, tw21, tw22, tw23, tw24, tw25, tw26, tw27, tw28, tw29, tw30;
Button nadomescanja;
//Mapa aplikacije
public static File appDir = new File(Environment.getExternalStorageDirectory().getPath() + "/Android/data/com.whizzapps.stpsurniki/");

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //Mapa aplikacije se naredi, če ne obstaja
    if (!appDir.exists())
    {
        appDir.mkdirs();
    }
    //Povezava z elementi iz navigacije
    expListView = (ExpandableListView) findViewById(R.id.lvExp);
    dan = (TextView) findViewById(R.id.dan);
    ura = (TextView) findViewById(R.id.ura);
    tw15 = (TextView) findViewById(R.id.textView22);
    facebook = (ImageView) findViewById(R.id.facebook);
    twitter = (ImageView) findViewById(R.id.twitter);
    //Nastavitev glave in noge
    View headerView = ((LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.header, null, false);
    View footerView = ((LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer, null, false);
    expListView.addHeaderView(headerView);
    expListView.addFooterView(footerView);
    //Nastavitev ExpandableListView adapterja
    prepareListData();
    listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
    expListView.setAdapter(listAdapter);
    //Klicanje pomembnih funkcij
    nadomescanjaClickListener();
    setCustomFontToAllTextViews();
    loadRandomQuote();
    getDay();
    getTime();
    expListViewClickListeners();
    posodabljanjeUre();
}

正如您所看到的,在onCreate方法之前,我声明全局变量,然后在onCreate中实例化这些变量。在那之后的几行中,我调用了onCreate中需要执行的所有方法。但是这些方法会因为nullpointerexception而导致应用程序崩溃(它们还没有得到变量)。但是,如果我在onCreate中删除这些变量,并在方法本身中实例化它们,那么它就可以工作了。

我现在不能发布logcat,因为我不在家,但我可以让你知道这是一个简单的nullpointerexception错误,因为它没有得到我在onCreate中设置的变量。

facebook和twitter ImageView在添加之前不会成为"活动"布局的一部分。所以findViewById()将在添加视图之前返回null。将footerView添加到expandableListView后,搜索twitter和facebook视图。

expListView.addFooterView(footerView);
facebook = (ImageView)footerView.findViewById(R.id.facebook);
twitter = (ImageView)footerView.findViewById(R.id.twitter);