来自本地XML的标记

时间:2014-01-12 19:04:18

标签: android xml google-maps

希望这是第三次幸运。我正在尝试从存储在原始文件夹中的xml文件中添加标记。但是在我的解析循环中,每当我输入item时,我都没有获得item.getAttribute选项。我得到一个选项列表但不是getAttribute。我添加了我的xml,我的代码如下,有人可以告诉我我做错了什么。 (我已尝试将所有内容都包含在try / catch中,但直到没有发生)。

此外,我的代码中有一些我没有使用的导入,因此需要删除,请忽略它们,除非它们导致问题。

提前谢谢

我的XML

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

<marker>
<lat>51.60002</lat>
<lng>0.518862</lng>
<icon>landmark</icon>
</marker>

</markers>

这是我的MainActivity

package com.mhmedia.landmarks;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.NodeList;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.sax.Element;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;


public class MainActivity extends Activity implements LocationListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationSource {

private GoogleMap mMap;
private OnLocationChangedListener mListener;
private LocationManager locationmanager;
GoogleMap googlemap;
LatLng myposition;
private String stringLat;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);     
locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
showmypoi();

if(locationmanager != null){
boolean gpsIsEnabled = locationmanager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean networkIsEnabled = locationmanager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if(gpsIsEnabled){
                locationmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L, 10F, this);
}
else if(networkIsEnabled)
{
                locationmanager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000L, 10F, this);
}
else
{
Toast.makeText(this, "Your GPS is not enabled", Toast.LENGTH_SHORT).show();
}
setUpMapIfNeeded();
}
}

@Override
public void onPause()
{
if(locationmanager != null){
locationmanager.removeUpdates(this);
}
super.onPause();
}

@Override
public void onResume(){
super.onResume();
setUpMapIfNeeded();
if(locationmanager != null){
mMap.setMyLocationEnabled(true);
}
}

private void setUpMapIfNeeded() {
if (mMap == null){
mMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();

if (mMap != null){
setUpMap();
}
mMap.setLocationSource(this);
}

}

private void setUpMap() {
mMap.setMyLocationEnabled(true);

}

@Override
public void activate(OnLocationChangedListener listener) {
mListener = listener;

}

@Override
public void deactivate() {
mListener = null;

}

@Override
public void onConnectionFailed(ConnectionResult result) {}

@Override
public void onConnected(Bundle connectionHint) {}

@Override
public void onDisconnected() {}

@Override
public void onLocationChanged(Location location) {
if( mListener != null){
mListener.onLocationChanged( location );

LatLngBounds bounds = this.mMap.getProjection().getVisibleRegion().latLngBounds;

if(!bounds.contains(new LatLng(location.getAltitude(), location.getLongitude())));{
mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
}

}

}

@Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Provider Disabled", Toast.LENGTH_SHORT).show();

}

@Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Provider Enabled", Toast.LENGTH_SHORT).show();

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(this, "Status Changed", Toast.LENGTH_SHORT).show();

}


public void showmypoi(){
InputStream in = this.getResources().openRawResource(R.raw.markers);

DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dfactory.newDocumentBuilder();
Document doc = db.parse(in, null);

NodeList markers = doc.getElementsByTagName("marker");

for (int i = 0; i < markers.getLength(); i++){

Element item = (Element) markers;
String stringLat = item.getAttribute("lat"); //Not getting .getAttribute option
String stringLng = item.getAttribute("lng"); //Not getting .getAttribute option
String icon = item.getAttribute("icon"); //Not getting .getAttribute option
Double lat = Double.valueOf(stringLat);
Double lng = Double.valueOf(stringLng);
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.the_map)).getMap();

}


}
}

1 个答案:

答案 0 :(得分:0)

引用文档

我们建议使用XmlPullParser,这是一种在Android上解析XML的高效且可维护的方法

http://developer.android.com/training/basics/network-ops/xml.html

您可以使用XmlPullParser

活动

   InputStream is = MainActivity.this.getResources()
                 .getAssets().open("xmlparser.xml"); 
   // local xml file in assests folder            
   ArrayList<Entry> entries= (ArrayList<Entry>) new ParserParsing().parse(is);  

然后

public class ParserParsing {
    private static final String ns = null;
public ArrayList<Entry> parse(InputStream in)
{ 
    ArrayList<Entry> list = null;

    try {
        XmlPullParser parser = Xml.newPullParser();
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
        parser.setInput(in, null);
        parser.nextTag();
          list=readFeed(parser);
         for(int i=0;i<list.size();i++)
         {
             Log.i(".......",list.get(i).lat);
             Log.i(".......",list.get(i).lng);
             Log.i(".......",list.get(i).icon);
         }
    } catch(Exception e){

    }
     return list;
}
private  ArrayList<Entry> readFeed(XmlPullParser parser) throws XmlPullParserException, IOException {

    ArrayList<Entry> entry= new ArrayList<Entry>();
parser.require(XmlPullParser.START_TAG, ns, "markers");
    while (parser.next() != XmlPullParser.END_TAG) {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            continue;
        }
        String name = parser.getName();
        Log.i("............",name);
        // Starts by looking for the entry tag
        if (name.equals("marker")) {
            entry.add(readMarker(parser));
        } else {
            skip(parser);
        }
    }  
    return entry;
}
private Entry readMarker(XmlPullParser parser) throws XmlPullParserException, IOException {
    parser.require(XmlPullParser.START_TAG, ns, "marker");
    String lat = null;
    String lng = null;
    String icon =null;
    while (parser.next() != XmlPullParser.END_TAG) {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            continue;
        }
        String name = parser.getName();
        Log.i("............",name);
        if (name.equals("lat")) {
           lat = readLat(parser);
        } else if (name.equals("lng")) {
            lng = readLng(parser);
        } else if (name.equals("icon")) {
            icon = readIcon(parser);
        } 
        else {
            skip(parser);
        }
    }
    return new Entry(lat,lng,icon);
}
private String readLat(XmlPullParser parser) throws IOException, XmlPullParserException {
    parser.require(XmlPullParser.START_TAG, ns, "lat");
    String lat = readText(parser);
    parser.require(XmlPullParser.END_TAG, ns, "lat");
    return lat;
}
private String readLng(XmlPullParser parser) throws IOException, XmlPullParserException {
    parser.require(XmlPullParser.START_TAG, ns, "lng");
    String lng = readText(parser);
    parser.require(XmlPullParser.END_TAG, ns, "lng");
    return lng;
}
private String readIcon(XmlPullParser parser) throws IOException, XmlPullParserException {
    parser.require(XmlPullParser.START_TAG, ns, "icon");
    String icon = readText(parser);
    parser.require(XmlPullParser.END_TAG, ns, "icon");
    return icon;
}


     private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
            String result = "";
            if (parser.next() == XmlPullParser.TEXT) {
                result = parser.getText();
                parser.nextTag();
            }
            return result;
        }
        private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
            if (parser.getEventType() != XmlPullParser.START_TAG) {
                throw new IllegalStateException();
            }
            int depth = 1;
            while (depth != 0) {
                switch (parser.next()) {
                case XmlPullParser.END_TAG:
                    depth--;
                    break;
                case XmlPullParser.START_TAG:
                    depth++;
                    break;
                }
            }
         }    
}

Entry.java

public  class Entry {
    public final String lat;
    public final String lng;
    public final String icon;


    public Entry(String lat, String lng,String icon) {
        this.lat = lat;
        this.lng = lng;
        this.icon =icon; 

}
}

日志

01-12 14:36:58.051: I/.......(2004): 51.60002
01-12 14:36:58.051: I/.......(2004): 0.518862
01-12 14:36:58.051: I/.......(2004): landmark

显示标记

    Double latitude = Double.valueOf(entries.get(0).lat);
    Double longitude = Double.valueOf(entries.get(0).lng);
    String icon = entries.get(0).icon;
    LatLng lng = new LatLng(latitude,longitude);

   Marker destination= googlemap.addMarker(new MarkerOptions()
                .position(lng)
                .title(icon)
                .snippet("My Location");