请帮忙 - 如何在android中解析这个xml - 总是出错

时间:2011-08-09 21:08:17

标签: android listview xml-parsing

这是xml文件: http://dating.rs/nemanja/WebService/getPlaces.php?lat=44.8061999&lon=20.4595333&rad=3502&tfs=0

<places>
  <place>
    <id>
      6
    </id>
    <name>
      McDonalds
    </name>
    <type>
      Fast Food
    </type>
    <longitude>
      20.4658031097
    </longitude>
    <latitude>
      44.80228031097
    </latitude>
  </place>
  <place>
    <id>
      5
    </id>
    <name>
      Pizza hut
    </name>
    <type>
      Fast Food
    </type>
    <longitude>
      20.47832518815
    </longitude>
    <latitude>
      44.792844714
    </latitude>
  </place>
</places>

这是我的代码:

public class ShopList {

    private ArrayList<String> id = new ArrayList<String>();
    private ArrayList<String> name = new ArrayList<String>();
    private ArrayList<String> type = new ArrayList<String>();
    private ArrayList<String> latitude = new ArrayList<String>();
    private ArrayList<String> longitude = new ArrayList<String>();

with get i set metods...

public class ReturnPlaces extends DefaultHandler {

    Boolean currentElement = false;
    String currentValue = null;
    public static ShopList shopList = null;

    public static ShopList getShopList(){
        return shopList;
    }

    public static void setShopList(ShopList shopList) {
        ReturnPlaces.shopList = shopList;
    }



    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        if (currentElement) {
            currentValue = new String(ch, start, length);
            currentElement = false;
        }

        //super.characters(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        currentElement = false;
        if (localName.equalsIgnoreCase("id"))
            shopList.setId(currentValue);
        else if (localName.equalsIgnoreCase("name"))
            shopList.setName(currentValue);
        else if (localName.equalsIgnoreCase("type"))
            shopList.setType(currentValue);
        else if (localName.equalsIgnoreCase("latitude"))
            shopList.setLatitude(currentValue);
        else if (localName.equalsIgnoreCase("longitude"))
            shopList.setLongitude(currentValue);        
        //super.endElement(uri, localName, qName);
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {        
        currentElement = true;
        if(localName.equalsIgnoreCase("place")){
            shopList = new ShopList();
        }else if (localName.equalsIgnoreCase("id")) {
            String id1 = attributes.getValue("id");
            shopList.setId(id1);
        }else if (localName.equalsIgnoreCase("name")) {
            String name1 = attributes.getValue("name");
            shopList.setName(name1);
        }else if (localName.equalsIgnoreCase("type")) {
            String type1 = attributes.getValue("type");
            shopList.setType(type1);
        }else if (localName.equalsIgnoreCase("latitude")) {
            String latitude1 = attributes.getValue("latitude");
            shopList.setLatitude(latitude1);
        }else if (localName.equalsIgnoreCase("longitude")) {
            String longitude1 = attributes.getValue("longitude");
            shopList.setLatitude(longitude1);
        }
        //super.startElement(uri, localName, qName, attributes);
    }

and this is my activity:

protected void onCreate(Bundle savedInstance) {     
        super.onCreate(savedInstance);
        setContentView(R.layout.pretraga);

        mapView = (MapView) findViewById(R.id.mapView1);
        mapView.setBuiltInZoomControls(true);
        mapController = mapView.getController();        
        mapController.setZoom(17);
        mapView.setStreetView(true);
        listView = (ListView) findViewById(R.id.listView);

        Intent i = getIntent();
        final double niz [] = i.getDoubleArrayExtra("Trenutna lokacija");
        double lat = niz [0];
        double lng = niz [1];
        int radius = i.getIntExtra("Radius", 501);
        boolean vreme = i.getBooleanExtra("Radno vreme", false);        

        try{
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();

            URL sourceUrl = new URL("http://dating.rs/nemanja/WebService/getPlaces.php?lat=44.8061999&lon=20.4595333&rad=3502&tfs=0");
            ReturnPlaces returnPlacesHandler = new ReturnPlaces();
            xr.setContentHandler(returnPlacesHandler);
            xr.parse(new InputSource(sourceUrl.openStream()));
        }catch (Exception e) {
            System.out.println("XML parsing exception"+e);
        }

        shopList = ReturnPlaces.getShopList();

        for(int u = 0; u<shopList.getId().size();u++){
            map = new HashMap<String, String>();
            float distance;                     
            map.put("name", shopList.getName().get(u));
            map.put("type", shopList.getType().get(u));         
            myList.add(map);            
        }

        SimpleAdapter adapter = new SimpleAdapter(this.getApplicationContext(), myList,R.layout.listview1, new String[]{"name","type"},
                new int[]{R.id.textViewName,R.id.textViewType});

        listView.setAdapter(adapter);

3 个答案:

答案 0 :(得分:0)

您不应该在onCreate中建立网址连接。这在早期的Android版本中是不受欢迎的,并且由Honeycomb框架强制执行。您需要使用工作线程或(等效,但更容易)AsyncTask。请参阅Android文档中的Painless Threading blog post

答案 1 :(得分:0)

答案 2 :(得分:0)

我认为这可能会对你有帮助。

//主类

public class Place extends ListActivity 
{

HashMap<String, String> map;

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

    ArrayList<HashMap<String, String>> accountlist = new ArrayList<HashMap<String, String>>();

    String xml = XMLParser.getXML();
    Log.i("Retrieved Xml", xml);
    Document doc = XMLParser.parse(xml);

    //Parsing data directly from the XML
    NodeList nodes = doc.getElementsByTagName("place");

    for (int i = 0; i < nodes.getLength(); i++) 
    {                           
        map = new HashMap<String, String>();    

        Element e = (Element)nodes.item(i);
        map.put("id", XMLParser.getValue(e, "id"));
            map.put("name", XMLParser.getValue(e, "name"));

        accountlist.add(map);           
    }       

    ListAdapter adapter = new PlaceAdapter(this, accountlist , R.layout.main, 
                    new String[] { "id", "name" }, 
                    new int[] { R.id.id, R.id.name });

    setListAdapter(adapter);

     final ListView lv = getListView();
     lv.setTextFilterEnabled(true); 
     lv.setOnItemClickListener(new OnItemClickListener() 
     {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
        {               

            @SuppressWarnings("unchecked")
            HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);   

            Intent intent = new Intent(Place.this, Results.class); 
            Bundle b = new Bundle();

            b.putString("name",  o.get("name"));
        b.putString("id",  o.get("id"));

            intent.putExtras(b);    
            startActivity(intent); 
        }
    });
}

//Place-Adapter

public class PlaceAdapter extends SimpleAdapter 
{

    private ArrayList<HashMap<String, String>> results;

    public PlaceAdapter(Context context, ArrayList<HashMap<String, String>> data, int resource, String[] from, int[] to) 
    {
        super(context, data, resource, from, to);
        this.results = data;
    }

    public View getView(int position, View view, ViewGroup parent)
    {
        int[] colors = new int[] {0x30ffffff, 0x30ff2020, 0x30808080};

      View v = super.getView(position, view, parent);


        if (v == null) 
        {
            LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.main, null);
        }

        TextView id = (TextView) v.findViewById(R.id.id);
        id.setText(results.get(position).get("id"));

        TextView name = (TextView) v.findViewById(R.id.name);
        name.setText(results.get(position).get("Name"));

        int colorPos = position % colors.length;
        v.setBackgroundColor(colors[colorPos]);

        return v;
    }
}   }

//解析

 public class XMLParser {



public final static Document XMLfromString(String xml){



    Document doc = null;



    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    try {



        DocumentBuilder db = dbf.newDocumentBuilder();



        InputSource is = new InputSource();

        is.setCharacterStream(new StringReader(xml));

        doc = db.parse(is); 



    } catch (ParserConfigurationException e) {

        System.out.println("XML parse error: " + e.getMessage());

        return null;

    } catch (SAXException e) {

        System.out.println("Wrong XML file structure: " + e.getMessage());

        return null;

    } catch (IOException e) {

        System.out.println("I/O exeption: " + e.getMessage());

        return null;

    }



    return doc;



}



/** Returns element value

  * @param elem element (it is XML tag)

  * @return Element value otherwise empty String

  */

 public final static String getElementValue( Node elem ) {

     Node kid;

     if( elem != null){

         if (elem.hasChildNodes()){

             for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){

                 if( kid.getNodeType() == Node.TEXT_NODE  ){

                     return kid.getNodeValue();

                 }

             }

         }

     }

     return "";

 }



 public static String getXML(){  

        String line = null;



        try {



            DefaultHttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost("http://dating.rs/nemanja/WebService/getPlaces.php?lat=44.8061999&lon=20.4595333&rad=3502&tfs=0");



            HttpResponse httpResponse = httpClient.execute(httpPost);

            HttpEntity httpEntity = httpResponse.getEntity();

            line = EntityUtils.toString(httpEntity);



        } catch (UnsupportedEncodingException e) {

            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";

        } catch (MalformedURLException e) {

            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";

        } catch (IOException e) {

            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";

        }



        return line;



}



public static int numResults(Document doc){     

    Node results = doc.getDocumentElement();

    int res = -1;



    try{

        res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());

    }catch(Exception e ){

        res = -1;

    }



    return res;

}



public static String getValue(Element item, String str) {       

    NodeList n = item.getElementsByTagName(str);        

    return XMLParser.getElementValue(n.item(0));

}

}

//点击列表视图显示结果

public class Results extends Activity 
{
@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.results);

    Bundle b = getIntent().getExtras();
    String id = b.getString("id");
    String name = b.getString("name");

    EditText aid = (EditText) findViewById(R.id.eid);
    EditText aname = (EditText) findViewById(R.id.ename);

    aid.setText(id);
    aname.setText(name);
}

}