将URL解析为不使用新线程的字符串

时间:2014-03-08 23:39:46

标签: java android string multithreading url

我是android的新手,Async任务对我来说实现起来太难了,所以我尝试运行我的URL来对新线程进行字符串解析,但它不起作用。 "天气的长度"应该从URL获取所有数据的变量返回0

我的代码:

 Thread thread = new Thread(new Runnable(){
                @Override
                public void run() {
                    try {

                        int num1;
                        int num2;
                        int num3;
                        int num4;
                        int num5;



                        String weather="";
                        try {
                            weather = new Scanner(new URL("http://api.openweathermap.org/data/2.5/forecast?lat="+lat+"&lon="+longi+"&units=metric&mode=xml").openStream(), "UTF-8").useDelimiter("\\A").next();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        num1=weather.length();

                        String location=Integer.toString(num1);

                        String status="";

                        String xml = "<resp><status>good</status><msg>hi</msg></resp>";

                        XPathFactory xpathFactory = XPathFactory.newInstance();
                        XPath xpath = xpathFactory.newXPath();
                        InputSource source = new InputSource(new StringReader(weather));

                        try{
                            status = xpath.evaluate("/weatherdata/location/name", source);
                        }
                        catch (Exception e) {
                            // e.printStackTrace();
                        }
//System.out.println(weather);
                        System.out.println("weatherdisplay=" + weather);
                        System.out.println("status=" + status);
                        System.out.println("Location display=" + location);


                        textCountry=(TextView)findViewById(R.id.textView6);

                        textCountry.setText(location);

                        //Your code goes here
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

            thread.start();

1 个答案:

答案 0 :(得分:0)

我只能建议您实际实现AsyncTask。

这些非常简单并且效果很好。

请花点时间学习如何实施它们,你才会感到更快乐。