Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从Android应用程序的google maps api解析数据时接收空语句_Java_Android_Xml_Google Maps_Parsing - Fatal编程技术网

Java 从Android应用程序的google maps api解析数据时接收空语句

Java 从Android应用程序的google maps api解析数据时接收空语句,java,android,xml,google-maps,parsing,Java,Android,Xml,Google Maps,Parsing,当解析来自Google maps api的URL的Xml时,我收到空语句。我不知道我哪里做错了什么。我认为这与我的元素和属性有关,但我不确定。有人能给我指出正确的方向或我的错误吗 下面是我正在使用的三个类: import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class HandlingXML extends Defau

当解析来自Google maps api的URL的Xml时,我收到空语句。我不知道我哪里做错了什么。我认为这与我的元素和属性有关,但我不确定。有人能给我指出正确的方向或我的错误吗

下面是我正在使用的三个类:

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class HandlingXML extends DefaultHandler {

    XMLDataCollected info = new XMLDataCollected();

    public String getInformation(){
        return info.dataToString();
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        // TODO Auto-generated method stub

        if (localName.equals("text")){
            String time = attributes.getValue("duration");
            info.setTime(time);
        }else if (localName.equals("text")){
            String distance = attributes.getValue("distance");
            info.setDistance(distance);
        }
    }

}


public class XMLDataCollected {
    String distance = null;
    String time = null;

    public void setTime(String t){
        time = t;
    }

    public void setDistance(String d){
        distance = d;
    }

    public String dataToString(){
        return "Total Distance: " + distance + ", Total Duration: " + time;
    }
}



import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class MapParsing extends Activity implements OnClickListener {

    static final String baseURL = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=";
    TextView tv;
    EditText origin, destination;

    @Override
    public void onCreate(Bundle icicle){
        super.onCreate(icicle);

        setContentView(R.layout.activity_main);
        Button b = (Button)findViewById(R.id.destination_next_button);
        tv = (TextView)findViewById(R.id.time_distance);
        origin = (EditText)findViewById(R.id.startinglocation);
        destination = (EditText)findViewById(R.id.endinglocation);
        b.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        String start = origin.getText().toString();
        String end = destination.getText().toString();

        StringBuilder URL = new StringBuilder(baseURL);
        URL.append(start + "&destinations=" + end + "&sensor=false");
        String fullUrl = URL.toString();
        try{
            URL website = new URL(fullUrl);
            //getting xmlreader to parse data
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            HandlingXML doWork = new HandlingXML();
            xr.setContentHandler(doWork);
            xr.parse(new InputSource(website.openStream()));
            String information = doWork.getInformation();
            tv.setText(information);
        }catch(Exception e){
            tv.setText("Error!");
        }
    }



    }
以下是我的活动\u Main\u xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/gc"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/startinglocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="27dp"
        android:layout_marginTop="22dp"
        android:ems="10"
        android:hint="@string/starting_location" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/endinglocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/startinglocation"
        android:layout_below="@+id/startinglocation"
        android:layout_marginTop="28dp"
        android:ems="10"
        android:hint="@string/ending_location" />

    <Button
        android:id="@+id/destination_next_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="22dp"
        android:layout_marginRight="37dp"
        android:text="@string/next" />

    <Spinner
        android:id="@+id/Vehicle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/endinglocation"
        android:layout_centerVertical="true"
        android:entries="@array/Vehicles" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/Vehicle"
        android:layout_alignLeft="@+id/Vehicle"
        android:text="Vehicle Type:"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/time_distance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/Vehicle"
        android:layout_below="@+id/Vehicle"
        android:layout_toLeftOf="@+id/destination_next_button"
        android:text="TIme and Distance" />

</RelativeLayout>

我试图解析的XML如下所示:

<DistanceMatrixResponse>
<status>OK</status><origin_address>Indianapolis, IN, USA</origin_address>           <destination_address>Denver, CO, USA</destination_address>
<row>
<element>
<status>OK</status>
<duration>
<value>55705</value>
<text>15 hours 28 mins</text>
</duration>
<distance>
<value>1742628</value>
<text>1,743 km</text>
</distance>
</element>
</row>
</DistanceMatrixResponse>

美国丹佛,科罗拉多州,美国
好啊
55705
15小时28分钟
1742628
1743公里
这是我试图从中提取的链接


请尝试此示例,它可用于解析XML:

public class DOMParserDemo {

public static void main(String[] args) throws Exception {
//Get the DOM Builder Factory
DocumentBuilderFactory factory = 
    DocumentBuilderFactory.newInstance();

//Get the DOM Builder
DocumentBuilder builder = factory.newDocumentBuilder();

//Load and Parse the XML document
//document contains the complete XML as a Tree.
Document document = 
  builder.parse(
    ClassLoader.getSystemResourceAsStream("xml/employee.xml"));

List<Employee> empList = new ArrayList<>();

//Iterating through the nodes and extracting the data.
NodeList nodeList = document.getDocumentElement().getChildNodes();

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

  //We have encountered an <employee> tag.
  Node node = nodeList.item(i);
  if (node instanceof Element) {
    Employee emp = new Employee();
    emp.id = node.getAttributes().
        getNamedItem("id").getNodeValue();

    NodeList childNodes = node.getChildNodes();
    for (int j = 0; j < childNodes.getLength(); j++) {
      Node cNode = childNodes.item(j);

      //Identifying the child tag of employee encountered. 
      if (cNode instanceof Element) {
        String content = cNode.getLastChild().
            getTextContent().trim();
        switch (cNode.getNodeName()) {
          case "firstName":
            emp.firstName = content;
            break;
          case "lastName":
            emp.lastName = content;
            break;
          case "location":
            emp.location = content;
            break;
        }
      }
    }
    empList.add(emp);
  }

}

//Printing the Employee list populated.
for (Employee emp : empList) {
  System.out.println(emp);
}

  }
 }

class Employee{
String id;
String firstName;
String lastName;
String location;

@Override
public String toString() {
 return firstName+" "+lastName+"("+id+")"+location;
}
}
公共类DOMParserDemo{
公共静态void main(字符串[]args)引发异常{
//获取DOM生成器工厂
DocumentBuilderFactory工厂=
DocumentBuilderFactory.newInstance();
//获取DOM生成器
DocumentBuilder=factory.newDocumentBuilder();
//加载并解析XML文档
//文档以树的形式包含完整的XML。
文件=
builder.parse(
getSystemResourceAsStream(“xml/employee.xml”);
List empList=new ArrayList();
//遍历节点并提取数据。
NodeList NodeList=document.getDocumentElement().getChildNodes();
for(int i=0;i
请参阅示例XML文件:

<employees>
<employee id="111">
<firstName>Rakesh</firstName>
<lastName>Mishra</lastName>
<location>Bangalore</location>
</employee>
<employee id="112">
<firstName>John</firstName>
<lastName>Davis</lastName>
<location>Chennai</location>
</employee>
<employee id="113">
<firstName>Rajesh</firstName>
<lastName>Sharma</lastName>
<location>Pune</location>
</employee>
</employees>

拉凯什
米什拉
班加罗尔
约翰
戴维斯
钦奈
拉杰什
沙玛
浦那

似乎在解析方面可能有一些问题。。。如果有用的话就用它

尝试使用Sax解析器:

public void ReadAndWriteXMLFileUsingSAXParser(){

    try
    {
        DefaultHandler handler = new MyHandler();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        InputStream rStream = null;
        rStream = getClass().getResourceAsStream("location.xml");
        saxParser.parse(rStream, handler);
    }catch (Exception e) 
    {
        System.out.println(e.getMessage());
    }

}
处理程序类:

class MyHandler extends DefaultHandler {
String rootname;Attributes atr;
private boolean flag=false;private Vector data;
public void startElement(String namespaceURI, String localName,
                         String qName, Attributes atts)  {
 rootname=localName;
 atr=atts;

 if(rootname.equalsIgnoreCase("address_component")){
     data=new Vector();
     flag=true;
 }


}
public void characters(char[] ch, int start, int length){
    String value=new String(ch,start,length);
    if(flag)
    {
        if(rootname.equalsIgnoreCase("type")){
            data.addElement(value) ;
            System.out.println("++++++++++++++"+value);
        }
        if(rootname.equalsIgnoreCase("long_name")){
            data.addElement(value) ;
            System.out.println("++++++++++++++"+value);
        }
        if(rootname.equalsIgnoreCase("short_name")){
            data.addElement(value) ;
            System.out.println("++++++++++++++"+value);
        }
    }

}
public void endElement(String uri, String localName, String qName){
    rootname=localName;
     if(rootname.equalsIgnoreCase("address_component")){
         flag=false;
     }
}
}
我的Xml如下所示:

<address_component>
<long_name>Gujarat</long_name>
<short_name>Gujarat</short_name>
<type>administrative_area_level_1</type>
<type>political</type>
</address_component>

古吉拉特邦
古吉拉特邦
行政区一级
政治的

嘿,如果您是新的,并且XML输出不是强制性的,那么调用Google API并从该API获取JSON o/p:

然后你可以像这样解析它:

    JSONObject jsonObject = new JSONObject(responseText);
    // routesArray contains ALL routes
    JSONArray rows = jsonObject.getJSONArray("rows");       
    JSONArray elements = route.getJSONArray("elements");
    JSONObject leg = elements.getJSONObject(0);
    JSONObject durationObject = leg.getJSONObject("duration");
    String duration = durationObject.getString("text"); 

试着使用JSON,它更快速、更容易解析,使用起来也更好。

也应该是XML文件中的一行,位于origin_address:Denver,CO,usa下。SAX解析器在这种情况下根本不起作用吗?我明白你的意思,但这个XML没有“id”或元素,它只有属性,不是吗?我的输出现在是空的,而不是空的。这是因为我拉int类型而不是字符串,因为文本元素是15小时28分钟和1743公里?或者这有什么关系?@user3496650-好吧,在我的回答中,你有一个address_组件元素,你可以访问其中的值。。在您的情况下,您可以根据通话时间和通话距离拨打不同的电话。所以address_component=(Duration/Distance)和获取类型的位置只是获取文本和值,我这样做,但不知道如何调用信息。public void characters(char[]ch,int start,int length){String value=新字符串(ch,start,length);if(flag){if(rootname.equalsIgnoreCase(“text”){data.addElement(value)这给了我一个空白的声明…抱歉我是新的:你在哪里得到路由变量?我试着创建一个本地变量,但是一直在接收一个错误。