2011-12-10 44 views
7

我剛剛開始嘗試使用SimpleXML進行Android開發,並認爲它運行良好,直到遇到障礙。下面的代碼產生SimpleXML構造函數異常 - 無法創建內部類

W/System.err的的異常(665):org.simpleframework.xml.core.ConstructorException:無法構建內部類

我通過看問題在內部類,並認爲我明白你爲什麼要使用它們(不是我的意圖是必然的),但儘管我的代碼輪到嘗試和避免使用我仍然有點卡住,並會感謝任何幫助。

源代碼:

public class InCaseOfEmergencyMedAlertAllergiesActivity extends Activity { 
public void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 


    Serializer serializer = new Persister(); 
    InputStream xmlstream = this.getResources().openRawResource(R.raw.sample_data_allergies); 
    try { 
     medalertdata allergyObject = serializer.read(medalertdata.class, xmlstream); 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    setContentView(R.layout.allergies); 
} 

@Root 
public class medalertdata { 
    @ElementList 
    private List<allergy> allergyList; 

    public List getAllergies() { 
     return allergyList; 
    } 
} 

@Root 
public class allergy{ 

    @Element 
    private String to; 

    @Element 
    private Boolean medical; 

    @Element 
    private String notes; 

    public allergy(String to, Boolean medical, String notes){ 
     this.to = to; 
     this.medical = medical; 
     this.notes = notes; 
    } 

    public String getTo() { 
     return to; 
    } 

    public Boolean getMedical() { 
     return medical; 
    } 

    public String getNotes() { 
     return notes; 
    } 


} 

}

隨着XML文件中引用的結構爲:

<?xml version="1.0" encoding="ISO-8859-1"?> 
<medalertdata> 
<allergy> 
    <to>Penicillin</to> 
    <medical>true</medical> 
    <notes></notes> 
</allergy> 
<allergy> 
    <to>Bee Stings</to> 
    <medical>false</medical> 
    <notes>Sample</notes> 
</allergy> 
</medalertdata> 

是與我是如何詮釋了SimpleXML的班或者我想這個問題閱讀他們?謝謝!

回答

5

嘗試從allergy類中刪除@Root

另外:你有這兩個類每個在它的單獨的文件:allergy.java和medalertdata.java?

+0

謝謝你的回覆。不幸的是,刪除@Root符號沒有效果。目前這兩個類都是在onCreate()關閉後在Activity類中聲明的 - 它們是否應該放在不同的文件中? – Rory

+4

是的,Java中的所有普通公共類必須在其自己的文件中聲明。另一個選擇是讓它們成爲'靜態'(不知道SimpleXML如何處理這個)。 –

+2

讓他們在同一個文件中肯定是這個問題=) – Rory

12

我也讀過一些深度嵌套的XML數據到Java對象(並希望通過在同一個文件中定義類保持簡單的對象結構)。

該解決方案(不涉及拆分成單獨的文件)是使嵌套類靜態。 (換句話說,轉換爲inner classes into static nested classes。)有點在回顧中很明顯。

示例;
嵌套結構:

// ScoreData 
// Sport 
//  Category 
//  Tournament 

的Java:

@Root 
public class ScoreData { 

    @ElementList(entry = "Sport", inline = true) 
    List<Sport> sport; 

    static class Sport { 
     @ElementList(entry = "Category", inline = true) 
     List<Category> category; 
    } 

    // ... 
} 

免責聲明:我知道OP了這個問題已經解決了,但也許這可以幫助其他人誰碰上 org.simpleframework.xml.core.ConstructorException: Can not construct inner class,不想定義建議在Peter's answer的單獨文件中使用類。

+3

謝謝。這感覺比將一堆單次使用的類分成單獨的文件要乾淨得多。 –