Java/Android从xml获取数组

Ash*_*ley 6 java xml android

我有一个在我的应用程序中使用的xml文件中的经度和经度点列表.我发现自己重复这段代码以获得积分并认为必须有更好的方法吗?

    String[] mTempArray = getResources().getStringArray(R.array.stations);
    int len = mTempArray.length;
    mStationArray = new ArrayList<Station>();
    for(int i = 0; i < len; i++){
        Station s = new Station();
        String[] fields = mTempArray[i].split("[\t ]");
        s.setValuesFromArray(fields);
        Log.i("ADD STATION", ""+s);
        mStationArray.add(s);
    }
Run Code Online (Sandbox Code Playgroud)

XML的格式为:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="stations">
        <item>
            <name>Station name</name>
            <longitude>1111111</longitude>
            <latitude>11111</latitude>
            <code>1</code>
        </item>
Run Code Online (Sandbox Code Playgroud)

另一个(可能的)问题是,为了得到一个站,我必须得到所有这些并从阵列中拉出我想要的那个.这会慢得多吗?我可以在整个应用程序中使这个数组一致吗?(但保持单独的Intent方法)

Dan*_*lau 4

我和MilkJug有同样的想法,使用实用程序方法来创建站点,但我想提供一种稍微不同的方法:将尽可能多的构造逻辑移到Station类构造函数中。为了使示例简单,我还将实用程序方法移至类中Station

这提供了一个整体更清晰的设计,因为在 Station 类本身之外,您的代码永远不必处理其构造/初始化步骤尚未完全完成的 Station 对象。

(如果您有很多 Station 对象,kgiannakakis建议使用数据库可能是更好的方法。)

public class Station {
    private static List<Station> sStationArray = null;

    /**
     * Construct a Station from a specially-encoded String. The String
     * must have all the necessary values for the Station, separated by tabs.
     */ 
    public Station(String fieldString) {
        String[] fields = fieldString.split("[\t ]");

        // For safety, setValuesFromArray() should be declared 'final'.
        // Better yet, you could just move its body into this constructor.
        setValuesFromArray(fields);

        // I'm assuming 'mName' is the name field for the Station
        Log.i("Station", this.mName);
    }

    public static Station getStationArray(Context ctx) {
        if (sStationArray == null) {

            // (Please don't use the prefix 'm' for non-member variables!)
            final String[] tempArray = 
                ctx.getResources().getStringArray(R.array.stations);
            final int len = tempArray.length;

            // Passing the length into the ArrayList constructor (if it's
            // known, or can be guessed at) can be a very simple yet
            // effective optimization. In this case the performance boost
            // will almost certainly **not** be meaningful, but it's
            // helpful to be aware of it.
            sStationArray = new ArrayList<Station>(len);    

            for (int i = 0; i < len; i++) {
                Station s = new Station(tempArray[i]);
                sStationArray.add(s);
            }
        }
        return sStationArray;
    }
}
Run Code Online (Sandbox Code Playgroud)