Java 如何获取editText并对其执行网络操作?

Java 如何获取editText并对其执行网络操作?,java,android,android-asynctask,networkonmainthread,Java,Android,Android Asynctask,Networkonmainthread,我的程序只需要能够根据Google的Directions API的输出来计算旅行时间。我计划用这个数字做更多的事情,但现在,我只想能够显示它。以下是代码的要点: public class DirectionDuration { public DirectionDuration() { } @SuppressWarnings("deprecation") public Document getDocument(String url) { try { URL u =

我的程序只需要能够根据Google的Directions API的输出来计算旅行时间。我计划用这个数字做更多的事情,但现在,我只想能够显示它。以下是代码的要点:

public class DirectionDuration {

public DirectionDuration() {

}

@SuppressWarnings("deprecation")
public Document getDocument(String url) {

    try {
        URL u = new URL(url);
        URLConnection connection = u.openConnection();
        InputStream in = (InputStream) connection.getContent();
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(in);
        return doc;
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

public int getDurationValue (Document doc) //Used to read the travel time from the XML file
{
    NodeList nl1 = doc.getElementsByTagName("duration");
    Node node1 = (Node) nl1.item(nl1.getLength() - 1);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = (Node) nl2.item(getNodeIndex(nl2, "value"));
    Log.i("DurationValue", node2.getTextContent());
    return Integer.parseInt(node2.getTextContent());
}

private int getNodeIndex(NodeList nl, String nodename) {
    for(int i = 0 ; i < nl.getLength() ; i++) {
        if(nl.item(i).getNodeName().equals(nodename))
            return i;
    }
    return -1;
}
}
公共类方向持续时间{
公共方向持续时间(){
}
@抑制警告(“弃用”)
公共文档getDocument(字符串url){
试一试{
URL u=新的URL(URL);
URLConnection=u.openConnection();
InputStream in=(InputStream)connection.getContent();
DocumentBuilder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
文档doc=builder.parse(in);
退货单;
}捕获(格式错误){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(ParserConfiguration异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(SAXE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
返回null;
}
public int getDurationValue(Document doc)//用于从XML文件读取行程时间
{
NodeList nl1=doc.getElementsByTagName(“持续时间”);
Node node1=(Node)nl1.item(nl1.getLength()-1);
NodeList nl2=node1.getChildNodes();
Node node2=(Node)nl2.item(getNodeIndex(nl2,“value”);
i(“DurationValue”,node2.getTextContent());
返回Integer.parseInt(node2.getTextContent());
}
private int getNodeIndex(NodeList nl,字符串nodename){
对于(int i=0;i
这是我的主要课程:

public class MainActivity extends ActionBarActivity {

private String start = null;
private String end = null;
private String mode = null;
private int baseline = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final EditText st = (EditText) findViewById(R.id.st);
    final EditText en = (EditText) findViewById(R.id.en);
    Button button1 = (Button) findViewById(R.id.button);
    button1.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            start = st.getText().toString();
            end = en.getText().toString();
            mode = "driving";
            String url = "http://maps.googleapis.com/maps/api/directions/xml?"
                    + "origin=" + start
                    + "&destination=" + end
                    + "&sensor=false&units=metric&mode="+ mode;
            new DirectionAsync().execute(url);
        }
    });
}

private class DirectionAsync extends AsyncTask<String, Void, Integer>
{
    @Override
    protected Integer doInBackground(String... urls)
    {
        GMapV2Direction md = new GMapV2Direction();
        Document doc = md.getDocument(urls[0]);
        int duration = md.getDurationValue(doc);
        return duration;
    }

    @Override
    protected void onPostExecute(Integer result)
    {
        baseline = result;
        TextView res = (TextView) findViewById(R.id.res);
        res.setText((result / 3600) + " hours " + ((result % 3600) / 60) + " minutes " + (result % 60) + " seconds");
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}
公共类MainActivity扩展了ActionBarActivity{
私有字符串start=null;
私有字符串end=null;
私有字符串模式=null;
私有int基线=0;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
最终EditText st=(EditText)findViewById(R.id.st);
最终编辑文本en=(编辑文本)findViewById(R.id.en);
按钮button1=(按钮)findViewById(R.id.Button);
button1.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
start=st.getText().toString();
end=en.getText().toString();
mode=“驾驶”;
字符串url=”http://maps.googleapis.com/maps/api/directions/xml?"
+“origin=“+start”
+“&destination=“+end”
+“&sensor=false&units=metric&mode=“+mode;
新建DirectionAsync().execute(url);
}
});
}
私有类DirectionAsync扩展异步任务
{
@凌驾
受保护的整数doInBackground(字符串…URL)
{
GMapV2Direction md=新的GMapV2Direction();
Document doc=md.getDocument(URL[0]);
int duration=md.getDurationValue(doc);
返回时间;
}
@凌驾
受保护的void onPostExecute(整数结果)
{
基线=结果;
TextView res=(TextView)findViewById(R.id.res);
res.setText((结果/3600)+“小时”+((结果%3600)/60)+“分钟”+(结果%60)+“秒”);
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(右菜单菜单菜单主菜单);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//处理操作栏项目单击此处。操作栏将
//自动处理Home/Up按钮上的点击,只要
//在AndroidManifest.xml中指定父活动时。
int id=item.getItemId();
//noinspection SimplifiableIf语句
if(id==R.id.action\u设置){
返回true;
}
返回super.onOptionsItemSelected(项目);
}
}

问题已解决。

让我建议您如何重构代码

在创建视图onCreateView时,应该设置setOnClickListener和onClick,而不是在异步任务中

在onClick中,您需要创建一个新的异步任务来进行http调用:newdirectionasync(…).execute()

在doInBackground()中,进行URL连接并获得结果。作为doInBackground()的返回,您将收到的持续时间交给onPostExecute(),后者也在异步任务中

onPostExecute()中的代码在UI线程上运行,您可以使用res.setText()将结果写入接口

很抱歉,我没有时间为这个答案编写代码或伪代码,但我希望这个提纲能帮助您取得一些进展

将变量传递给异步任务的简单方法是在其构造函数中:

public class DirectionsAsync extends AsyncTask <String, Void, Integer> {

String startPoint;
String endPoint;

public DirectionsAsync(String start, String end) {
    startPoint = start;
    endPoint = end;
}
公共类方向异步扩展异步任务{
字符串起始点;
字符串端点;
公共方向异步(字符串开始、字符串结束){
开始点=开始;
终点=终点;
}

然后doInBackground引用startPoint和endPoint。

但是如何将开始和结束目标传递给DirectionAsync()?我有x.getText().toString(),但我只能在主线程中这样做。一个简单的方法是将它们传递到构造函数中:呵呵。现在感觉有点傻。这是一个多么简单的修复方法…谢谢你,我编辑了我的第一篇文章,以显示我的新代码和这些更改,这样你就可以看到我正在查看的内容。我无法让PostExecute正常工作,因为它随时都会给我错误我试着做一些类似activity.handleResults(result)的事情;也许你可以详细解释一下当你说onPostExecute()中的代码在UI线程上运行时的意思,你能发布一个错误吗?同时