2011-11-13 135 views
7

我正在嘗試進入Android編程,並從書中採取了一些例子。 在這些例子中要求把下面的代碼:爲什麼Bundle對象在onCreate()上始終爲空?

public class ExemploCicloVida extends Activity { 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle icicle) { 
     super.onCreate(icicle); 
     Log.i(TAG, getClassName() + " onCreate() called on: " + icicle); 

     TextView t = new TextView(this); 
     t.setText("Exemplo de ciclo de vida de uma Activity.\nConsulte os logs no LogCat"); 
     setContentView(t); 
    } 
} 

我不知道爲什麼Bundle對象總是在這種情況下空。

回答

2

運行此代碼並按Ctrl + F11旋轉屏幕。該包不會爲空。

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    if (savedInstanceState != null) { 
     Toast.makeText(this, savedInstanceState.getString("s"), 
       Toast.LENGTH_LONG).show(); 
    } 
} 

@Override 
protected void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 

    outState.putString("s", "hello"); 
} 

onSaveInstanceState(Bundle)將被調用。然後,創建活動對象並使用非空Bundle savedInstanceState調用onCreated(Bundle)

+1

謝謝wannik。 API給了我線索,也是你的,我只是在我自己的代碼上鍵入Ctrl + F11,而冰柱不再爲空。 –

8

就我而言,原因是特定的活動沒有在清單文件中聲明的主題。

要解決此問題,請打開AndroidManifest.xml,單擊應用程序,在應用程序節點中選擇崩潰活動,並在屬性的主題字段中添加主題。在我的情況下,它是

@style/Theme.AppCompat.Light.DarkActionBar 

但你可以複製你的其他活動之一的主題。

P.S .:我知道這是一個老問題的答案,但我在尋找修復程序時偶然發現了它,但沒有找到可行的解決方案,因此這可能對別人有幫助。

+1

非常感謝您對此輸入!你爲我節省了很多頭痛......我在之前的活動中改變了主題,但不是在獲得空指針的活動中!我永遠不會夢見這是問題!再一次... cead英里失敗! –

+0

非常歡迎!我浪費了很多時間來弄清楚,所以我很高興聽到它幫助別人不經歷這一切! –

0

我想你想讀取進入你的活動的參數。使用此功能:

protected String getStringExtra(Bundle savedInstanceState, String id) { 
String l; 
l = (savedInstanceState == null) ? null : (String) savedInstanceState 
      .getSerializable(id); 
if (l == null) { 
    Bundle extras = getIntent().getExtras(); 
    l = extras != null ? extras.getString(id) : null; 
} 
return l; 
} 
相關問題