2

How to parse XML data from a URL to Google Map V2?

I'm retrieving the Longitude and latitude from " http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&location=singapore "

I would like to parse the lng and lat into google map. This is how I would like it to work.

By selecting on the "title", it will show me the location of the title on the map.

The title,lng and lat have been retrieved.

However, in my map, it doesn't show up. May I know which part of my coding, have I yet to done up?

in Conclusion First of all, I would like to retrieve "title","lng", and "lat" from api.eventful.com/rest/events/… I've already done that... (:

Next, i would like to show the location on the google map, Which I would like it to be On select the "title", it will show me the location on google map, BUT! the coding for parsing XML data to google map, I'm not sure about it..

MainActivity.java

public class MainActivity extends Activity {

    ArrayList<String> title;
    ArrayList<String> start_time;
    ArrayList<String> latitude;
    ArrayList<String> longitude;

    ItemAdapter adapter1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView list = (ListView) findViewById(R.id.list);
        title = new ArrayList<String>();
        start_time = new ArrayList<String>();
        latitude = new ArrayList<String>();  
        longitude = new ArrayList<String>();
        try {

            URL url = new URL(
                    "http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&location=singapore");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(url.openStream()));
            doc.getDocumentElement().normalize();

            NodeList nodeList = doc.getElementsByTagName("event");
            for (int i = 0; i < nodeList.getLength(); i++) {

                Node node = nodeList.item(i);      

                Element fstElmnt = (Element) node;

                NodeList nameList = fstElmnt.getElementsByTagName("title");
                Element nameElement = (Element) nameList.item(0);
                nameList = nameElement.getChildNodes();        
                title.add(""+ ((Node) nameList.item(0)).getNodeValue());

                NodeList websiteList = fstElmnt.getElementsByTagName("start_time");
                Element websiteElement = (Element) websiteList.item(0);
                websiteList = websiteElement.getChildNodes();
                start_time.add(""+ ((Node) websiteList.item(0)).getNodeValue());          

                NodeList websiteList1 = fstElmnt.getElementsByTagName("latitude");
                Element websiteElement1 = (Element) websiteList1.item(0);
                websiteList1 = websiteElement1.getChildNodes();
                latitude.add(""+ ((Node) websiteList1.item(0)).getNodeValue());          


                NodeList websiteList2 = fstElmnt.getElementsByTagName("longitude");
                Element websiteElement2 = (Element) websiteList2.item(0);
                websiteList2 = websiteElement2.getChildNodes();
                longitude.add(""+ ((Node) websiteList2.item(0)).getNodeValue());




            }
        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);
        }

        adapter1 = new ItemAdapter(this);
        list.setAdapter(adapter1);
    }


    class ItemAdapter extends BaseAdapter {

        final LayoutInflater mInflater;

        private class ViewHolder {
            public TextView title_text;
            public TextView des_text;


        }

        public ItemAdapter(Context context) {
            // TODO Auto-generated constructor stub
            super();
            mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);    
        }

        //@Override
        public int getCount() {
            return title.size();
        }

        //@Override
        public Object getItem(int position) {
            return position;
        }

        //@Override
        public long getItemId(int position) {
            return position;
        }

        //@Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = convertView;
            final ViewHolder holder;
            if (convertView == null) {
                view = mInflater.inflate(R.layout.mainpage_list,parent, false);
                holder = new ViewHolder();
                holder.title_text = (TextView) view.findViewById(R.id.title_text);
                holder.des_text = (TextView) view.findViewById(R.id.des_text);



                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }

            holder.title_text.setText(""+title.get(position));

            holder.des_text.setText(""+Html.fromHtml(start_time.get(position)));



        return view;
        }
    }

    public void onListItemClick(ListView parent, View v, int position,long id) 
    {; 


 Intent n = new Intent(MainActivity.this,map.class); 
n.putExtra("lat",latitude.get(position).toString()); 
n.putExtra("lng",longitude.get(position).toString());
startActivity(n); 
        }
}

map.java

public class map extends  FragmentActivity  {

LatLng storeLocation;
private GoogleMap MAP;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map_shown);
    Intent n = getIntent();
    String latitude = n.getStringExtra("lat");
    String longitude= n.getStringExtra("lng");
    SupportMapFragment fm = (SupportMapFragment)  getSupportFragmentManager().findFragmentById(R.id.map);
    MAP = fm.getMap(); 

    Double lat= Double.parseDouble(latitude);
    Double lng= Double.parseDouble(longitude);


    MAP = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
       // FragmentManager myFM = getActivity().getSupportFragmentManager();
        //SupportMapFragment myMAPF = (SupportMapFragment) myFM.findFragmentById(R.id.map);
    MAP = myMAPF.getMap();
    MAP.setMyLocationEnabled(true);
    MAP.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    storeLocation = new LatLng(lat,
            lng);

   MAP.addMarker(new MarkerOptions().position(storeLocation).title(
            storeLocation.toString()));



}
}   
2
  • In map.java, you create two String vars for lat and lon from the intent, but you don't use them in the fm or map, as far as I can tell! Commented Aug 8, 2013 at 12:36
  • this isn't the full source I guess, I want to add the lng and lat in it, so that when I click "title" it will show the location on map, however, I not sure about that ,seeking for help if possible Commented Aug 8, 2013 at 12:48

2 Answers 2

1

you should do this by:

public class map extends  FragmentActivity  {

LatLng storeLocation;
private GoogleMap MAP;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map_shown);
    Intent n = getIntent();
    String latitude = n.getStringExtra("lat");
    String longitude= n.getStringExtra("lng");
    SupportMapFragment fm = (SupportMapFragment)  getSupportFragmentManager().findFragmentById(R.id.map);
    map = fm.getMap(); 

    Double lat= Double.parseDouble(latitude);
    Double lng= Double.parseDouble(longitude);

    FragmentManager myFM = getActivity()
            .getSupportFragmentManager();
    SupportMapFragment myMAPF = (SupportMapFragment) myFM
            .findFragmentById(R.id.fragment1);
    MAP = myMAPF.getMap();
    MAP.setMyLocationEnabled(true);
    MAP.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    storeLocation = new LatLng(lat,
            lng);

   MAP.addMarker(new MarkerOptions().position(storeLocation).title(
            storeLocation.toString()));



}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use SAX parser. Extend DefaultHandler and override the document event methods: startDocument(), endDocument(), startElement(), and endElement(). Use the characters() method to populate a StringBuilder with any data you need inside xml tags, and dump that data with a toString() call inside the endElement() method. Put the data into a holder class and pass it to your fragment/activity when the parsing is done.

I was looking around the web for a clean example but I haven't seen one to my liking.

You will not be able to drop this code into your project, it's intended for human reading and comprehension, not compiler scrutiny. I hope this example helps you:

public class MapDataHandler extends DefaultHandler {
    private static final String WHATEVER_XML_TAG_YOU_WANT = //xml tag name as it appears in the document you want to parse.
    private StringBuilder mCharacters;
    private MapsDataHolder mData; //simple class with nothing but getters and setters

    @Override
    public void startDocument() throws SAXException {
        //Initialize your member variables.
        mCharacters = new StringBuilder();
        mData = new MapsDataHolder();
    }

    @Override
    public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
        mCharacters = new StringBuilder();
        //Clear the string builder for every new tag.
        //This is so that the contents of previous tags don't linger in the 
        //StringBuilder when you move on to later tags.

    }

    @Override
    public void endElement (String uri, String localName, String qName) throws SAXException {
        if (qName.equals(WHATEVER_XML_TAG_YOU_WANT)) {
            String contentsOfThatTag = mCharacters.toString();
            mData.setField(contentsOfThatTag); //put the data into your holder class object
        } else if (qName.equals(ANOTHER_EXAMPLE_TAG)) {
            //dump the contents of mCharacters again
            //
        }

    //parse any other tags you care about with additional 'else if' blocks

    }

    @Override
    public void endDocument() throws SAXException {
        mCharacters = null;
    }

    @Override
    public void characters (char[] ch, int start, int length) throws SAXException {
        mCharacters.append(ch, start, length);
        //keeps a running tally of characters between tags.
    }

    public MapsDataHolder getData() {
        return mData;
    }

}

When the parsing is done, you can return the MapsDataHolder object through a callback or by any means you prefer. Then you have a java class with nothing but the data you want and the access methods to get it.

2 Comments

is there any sample that I could follow after?
@randomize I added an example which I hope makes things more clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.