Java/Android 从 xml 获取数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4691706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java/Android get array from xml
提问by Ashley
I have a list of longitude and longitude points in an xml file that is used throughout my application. I find my self repeating this code to get points often and think there must be a better way?
我在整个应用程序中使用的 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);
}
XML is in the format of:
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>
And another (possible) problem is that to get just one station I have to get all of them and pull the one I want from the array. Is this going to be considerably slower? Can I make this array consistent throughout the app? (But keeping the separate Intent methodology)
另一个(可能的)问题是,要获得一个站,我必须获得所有站并从阵列中拉出我想要的站。这会慢很多吗?我可以使这个数组在整个应用程序中保持一致吗?(但保持单独的意图方法)
采纳答案by Dan Breslau
I had the same thought as MilkJug, to use a utility method to create the stations, but I want to offer a slightly different approach: Move as much of the construction logic as possible into the Station
class constructor. To keep the example simple, I'm moving the utility method into the Station
class as well.
我和MilkJug有同样的想法,使用实用方法来创建站,但我想提供一种稍微不同的方法:将尽可能多的构造逻辑移到Station
类构造函数中。为了使示例保持简单,我还将实用程序方法移到Station
类中。
This provides an overall cleaner design, as outside of the Station class itself, your code should never have to deal with a Station object whose construction/initialization steps haven't been fully completed.
这提供了一个整体更简洁的设计,因为在 Station 类本身之外,您的代码永远不必处理其构造/初始化步骤尚未完全完成的 Station 对象。
(kgiannakakis'ssuggestion to use a database may be a better way to go if you have a lot of Station objects.)
(如果您有很多 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;
}
}
回答by MilkJug
Why not create a utility method that takes a context as a parameter and returns the station resources? For example:
为什么不创建一个以上下文为参数并返回站点资源的实用方法呢?例如:
public class StatUtil {
private static List<Station> mStationArray = null;
public static Station getStation(Context ctx) {
if (mStationArray == null) {
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);
}
}
return mStationArray;
}
}
and call it from your code with:
并从您的代码中调用它:
stationArray = StatUtil.getStation(this);
Repeatedly fetching the stations will be slower than caching them, but not significantly slower unless you are fetching them in a loop. Doing as above will prevent multiple copies from being fetched.
重复获取站点将比缓存它们慢,但除非您在循环中获取它们,否则不会明显更慢。执行上述操作将防止获取多个副本。
回答by kgiannakakis
I could propose two solutions:
我可以提出两种解决方案:
- You could create a Singleton class that initializes once, reads the data from the XML and stores the stations in a List or a Map. Use a Map if you want to quickly find a station based on its name. The Singleton class will provide methods for retrieving all stations or just one of them.
- Create a database table and store the information there. You may need more code, but the advantage will be that you will be able to run more advanced queries.
- 您可以创建一个初始化一次的 Singleton 类,从 XML 读取数据并将站点存储在列表或地图中。如果您想根据名称快速找到车站,请使用地图。Singleton 类将提供检索所有电台或仅其中一个电台的方法。
- 创建一个数据库表并将信息存储在那里。您可能需要更多代码,但好处是您将能够运行更高级的查询。