我在整个应用程序中使用的 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 的格式为:
<?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>
另一个(可能的)问题是,为了只获取一个电台,我必须获取所有电台并从数组中取出我想要的电台。这会慢很多吗?我可以使这个数组在整个应用程序中保持一致吗? (但保留单独的意图方法)
我有同样的想法MilkJug https://stackoverflow.com/questions/4691706/java-android-get-array-from-xml/4691823#4691823,使用实用程序方法来创建站点,但我想提供一种稍微不同的方法:将尽可能多的构建逻辑移至Station
类构造函数。为了使示例简单,我将实用程序方法移至Station
类也是如此。
这提供了一个整体更清晰的设计,因为在 Station 类本身之外,您的代码永远不必处理其构造/初始化步骤尚未完全完成的 Station 对象。
(吉安纳卡基斯的 https://stackoverflow.com/questions/4691706/java-android-get-array-from-xml/4691852#4691852如果您有很多 Station 对象,建议使用数据库可能是更好的方法。)
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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)