Domanda

Why is this returning "null"? It should return "Beedrill & Bug"...

Data.java:

package com.example.pokemon;

import java.io.Serializable;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

@Root(name="Data", strict=false)
public class Data implements Serializable {

    public Data() {}

    @Element(name = "nm", required=false)
    private String nm;

    public String gtNm(){
        return nm;
    }
    @Element(name = "tp", required=false)
    private String tp;

    public String gtTp(){
        return tp;
    }
}

Data.xml:

<?xml version = "1.0" encoding = "utf-8" ?>

<Data>

    <Pokemon> 
        <nm>Beedrill</nm> 
        <tp>bug</tp> 
        <ablt>swarm</ablt>
        <wkns>fire</wkns>
        <img>beedrill</img>
    </Pokemon> 


</Data>

MainActivity.java:

    try {
        Serializer serializer = new Persister();
        AssetManager assetManager = getAssets();
        InputStream inputStream = assetManager.open("data.xml");
        Data d = serializer.read(Data.class, inputStream);
        System.out.println("[JOE]: It worked! "+d.gtNm());
        System.out.println("[JOE]: It worked! "+d.gtTp());
    } 
    catch (Exception e) {
        e.printStackTrace();
        System.out.println("[JOE]: error! "+e.getMessage());
    }

LogCat:

[JOE]: It worked! null
[JOE]: It worked! null
È stato utile?

Soluzione

Your xml tree is...

<Data>
    <Pokemon> 
        <nm>Beedrill</nm> 

This means, you need the following in Data as Pokemon is an element of Data and Nm is an attribute of the pokemon.

   @Element
   private Pokemon pokemon;

You then need to create a class called Pokemon which has the attributes you've specified in Data, this way, you can d.getPokemon().gtNm();

Follow the example here under "Nested object serialization"

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top