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

时间:2015-04-27 04:20:27

标签: java android android-asynctask networkonmainthread

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

这是我的主要课程:

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

}

问题解决了。

1 个答案:

答案 0 :(得分:0)

让我建议一下如何重构代码。

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

在onClick中,您需要创建一个新的异步任务来进行http调用:new DirectionsAsync(...)。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。