Android Nullpointer异常按钮

时间:2014-10-03 07:17:16

标签: android button nullpointerexception

我的应用程序有时会崩溃,我知道在哪里,但我不知道为什么。请观看此代码:

private Button btFacebook     
@Override   
public final void onCreate(Bundle savedInstanceState) 
{
    ....
    btFacebook     = (Button) findViewById(R.id.bt_fb_zaloguj);
    btFacebook.setText(getResources().getString(R.string.act_logowanie_bt_facebook).toUpperCase()); //line crash 
    .... 
}

为什么btFacebook有时候是空的?

编辑:

> java.lang.RuntimeException: Unable to start activity ComponentInfo{pl.gosell.ghmaster/pl.gosell.ghmaster.activity.ActSplash}: java.lang.NullPointerException
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
android.app.ActivityThread.access$900(ActivityThread.java:161)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:157)
android.app.ActivityThread.main(ActivityThread.java:5356)8at java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
pl.gosell.ghmaster.activity.ActSplash.onActivityData(ActSplash.java:184)
com.android.lifter.activity.ActivityBase.onCreate(ActivityBase.java:99)
android.app.Activity.performCreate(Activity.java:5426)
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
19... 11 more

3 个答案:

答案 0 :(得分:2)

你错过了

  setContentView(R.layout.your_layout);

然后你初始化按钮,如:

protected  void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
btFacebook     = (Button) findViewById(R.id.bt_fb_zaloguj);
btFacebook.setText(getResources().getString(R.string.act_logowanie_bt_facebook).toUpperCase());      //line crash 
.... 
}

答案 1 :(得分:1)

如果你错过了这个,请查看你的代码。

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

然后添加

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

    btFacebook = (Button) findViewById(R.id.bt_fb_zaloguj);
    btFacebook.setText(getResources().getString(R.string.act_logowanie_bt_facebook).toUpperCase()); 

答案 2 :(得分:-1)

如果您已经在活动中,则可以简化您的呼叫

this.getString(R.string.act_logowanie_bt_facebook)

如果字符串在那里,它不应该给出异常。我认为你得到的例外是因为Button。不知何故,按钮对象为空。你能看一下你的观点并检查你的身份是否相同吗?