2015-04-06 55 views
1

我使用純代碼創建了我的佈局。 它工作,我決定創建另一個類來重用我的佈局。在代碼中創建佈局並獲取nullPointerException

我添加了一個新的類(Designer.java)來重複使用我的頁腳和標題進行其他活動。

我傳遞一個上下文作爲其他活動的參數。

  • rel2MainActivity有3個孩子
  • relMainActivity是空

我不明白什麼是錯的。我一定是錯過了一些東西

MainActivity.java

RelativeLayout relMainActivity ; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    // ... 
    Designer design = new Designer(); 
    design.createDesign(relMainActivity, this); 
    // relMainActivity = null in debug 

    setContentView(relMainActivity); 
    // java.lang.NullPointerException 

} 

Designer.java

RelativeLayout relHeader, relFooter, relContent; 

public void createDesign(RelativeLayout rel2MainActivity, Context context) { 

    rel2MainActivity = new RelativeLayout(context); 
    // ... 
    rel2MainActivity.addView(relHeader, 0); 
    rel2MainActivity.addView(relContent, 1); 
    rel2MainActivity.addView(relFooter, 2); 
    // rel2MainActivity has 3 children in debug 

} 
+0

請發佈您的日誌貓trac即 – Keshav1234 2015-04-06 10:30:04

回答

1

您在createDesign()中添加了3個視圖,但是您沒有將該視圖傳回給被調用者。

在這裏,當你調用:

所以,這就是relMainActivity

解決方案,使得空

RelativeLayout relHeader, relFooter, relContent; 

public RelativeLayout createDesign(RelativeLayout rel2MainActivity, Context context) { 

    rel2MainActivity = new RelativeLayout(context); 
    // ... 
    rel2MainActivity.addView(relHeader, 0); 
    rel2MainActivity.addView(relContent, 1); 
    rel2MainActivity.addView(relFooter, 2); 
    // rel2MainActivity has 3 children in debug 
    // rel2MainActivity view is local to this scope 
    // you should return it 
    return rel2MainActivity; 


} 

,並在得到它:

RelativeLayout relMainActivity ; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    // ... 
    Designer design = new Designer(); 
    relMainActivity = design.createDesign(relMainActivity, this); 
    // relMainActivity = null in debug 

    setContentView(relMainActivity); 

} 
1

createDesign方法直接使用relMainActivity,或返回的RelativeLayout的實例,並將其分配給relMainActivity在撥打createDesign方法後立即創建。

+0

你說得對。它的工作感謝你。我之前做過,但我沒有意識到,錯誤消息是爲一個子視圖,它也是空的:) – Firerox 2015-04-06 11:02:24

+0

酷,玩得開心。 :) – AAnkit 2015-04-06 11:03:17

1

你的文件變量relMainActivity1保留S此行代碼之後空

design.createDesign(relMainActivity, this); 

你應該改變你的代碼中使用它之前初始化relMainActivity1

setContentView(relMainActivity); 

public RelativeLayout createDesign(RelativeLayout rel2MainActivity, Context context) { 

     rel2MainActivity = new RelativeLayout(context); 
     // ... 
     rel2MainActivity.addView(relHeader, 0); 
     rel2MainActivity.addView(relContent, 1); 
     rel2MainActivity.addView(relFooter, 2); 
     // rel2MainActivity has 3 children in debug 

    return rel2MainActivity 
    } 

然後用它作爲

relMainActivity= design.createDesign(relMainActivity, this); 
setContentView(relMainActivity);