Parsing local gpx file in Android

主宰稳场 提交于 2019-11-30 14:59:42

you have the "Node node = nodelist_trkpt.item(i);" in your first loop. Get the child elements from this node an run through these child elements.

e.g.:

NodeList nList = node.getChildNodes();
for(int j=0; j<nList.getLength(); j++) {
    Node el = nList.item(j);
    if(el.getNodeName().equals("ele")) {
     System.out.println(el.getTextContent());
  }
}

I will add my library for GPX parsing to these answers: https://github.com/ticofab/android-gpx-parser. It provides two ways to parse you GPX file: once you obtain / create a GPXParser object (mParser in the examples below), you can then either parse directly your GPX file

Gpx parsedGpx = null;
try {
    InputStream in = getAssets().open("test.gpx");
    parsedGpx = mParser.parse(in);
} catch (IOException | XmlPullParserException e) {
    e.printStackTrace();
}
if (parsedGpx == null) {
    // error parsing track
} else {
    // do something with the parsed track
}

or you can parse a remote file:

mParser.parse("http://myserver.com/track.gpx", new GpxFetchedAndParsed() {
    @Override
    public void onGpxFetchedAndParsed(Gpx gpx) {
        if (gpx == null) {
            // error parsing track
        } else {
            // do something with the parsed track
        }
    }
});

Contributions are welcome.

Update: I've added parsing "ele" element as well, so this code could match your requirements.

I will propose different approach: https://gist.github.com/kamituel/6465125.

In my approach I don't create an ArrayList of all track points (this is done in the example you posted). Such a list can consume quite a lot of memory, which can be an issue on Android.

I've even given up on using regex parsing to avoid allocating too many objects (which causes garbage collector to run).

As a result, running Java with 16Mb heap size, parsing GPX file with over 600 points, garbage collector will be run only 12 times. I'm sure one could go lower, but I didn't optimize it heavily yet.

Usage:

GpxParser parser = new GpxParser(new FileInputStream(file));
TrkPt point = null;
while ((point = parser.nextTrkPt()) != null) {
  // point.getLat()
  // point.getLon()
}

I've successfully used this code to parse around 100 Mb of GPX files on Android. Sorry it's not in the regular repo, I didn't plan to share it just yet.

I've ported the library GPXParser by ghitabot to Android.

https://github.com/urizev/j4gpx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!