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

How do I get editText and perform network operations on it?

我的程序只需要能够根据 Google 的方向 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;
}
}

这是我的主要内容 class:

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);
}

}

问题已解决。

让我提出一个关于您应该如何重构代码的大纲。

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

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

在 doInBackground() 中建立 URL 连接并获得结果。作为来自 doInBackground() 的 return,您将收到的持续时间传递给也在异步任务中的 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。