在单独的线程网络相关的任务 [英] Network-related tasks on a separate thread

查看:199
本文介绍了在单独的线程网络相关的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在有一个花粉类,它是一类我写它使用JSoup库来解析HTML。这里还显示我的 PlaceholderFragment 类。

 公共静态类PlaceholderFragment扩展片段
    {
        @覆盖
        公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
                捆绑savedInstanceState)
        {
            最后Button按钮=(按钮)rootView.findViewById(R.id.button1);
            最终的TextView的TextView =(TextView中)rootView.findViewById(R.id.textview1);            button.setOnClickListener(新View.OnClickListener()
            {                @覆盖
                公共无效的onClick(视图v)
                {
                    花粉pollenObject =新的花粉(19104);
                    textview.setText(pollenObject.getCity());
                }
            });            返回rootView;
        }
    }

下面是我的花粉类。

 公共静态类花粉
{    @燮pressLint(的SimpleDateFormat)
    公共花粉(INT拉链code)
    {
        this.zip code =拉链code;
        文档文档;
        尝试
        {
            //通行证地址
            DOC = Jsoup.connect(http://www.wunderground.com/DisplayPollen.asp?Zip$c$c=+ this.zip code)获得();            //从XML获得地利
            元素位置= doc.select(div.columns)第一()。
            this.location = location.text();            从XML //得到花粉型
            元素pollenType = doc.select(div.panel H3)第一()。
            this.pollenType = pollenType.text();            SimpleDateFormat的格式=新的SimpleDateFormat(EEE MMMM DD,YYYY);            //添加四个项目花粉和日期
            //到各自的名单
            的for(int i = 0;我4;;我++)
            {
                元素日期= doc.select(td.text-center.even四)获得(一)。
                。元素水平= doc.select(td.levels)得到(一);                尝试
                {
                    pollenMap.put(format.parse(dates.text()),levels.text());
                }
                赶上(ParseException的E)
                {
                    e.printStackTrace();
                }
            }
        }
        赶上(IOException异常E)
        {
            // TODO自动生成catch块
            e.printStackTrace();
        }
    }
}

我学到了很多东西,每一个失败的尝试。我发现,在我使用的onClick 内调用我的花粉类的,我做一个昂贵的任务。因此,我应该把它放在一个单独的线程。要添加,因为我我的主/ UI线程中调用我的花粉类,它使我的应用程序崩溃。

我在帮助我试图解决我的问题征询问题#1:<一href=\"http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception\">android.os.NetworkOnMainThreadException

我发现我的错误和解决方案通过从logcat的这个错误日志,具体而言, NetworkOnMainThread ,其中Android的明确prevents我从我的UI线程做任何网络。

我的问题是 - 我怎么分配我的花粉类成一个单独的线程,是不是在我的UI类

继续我的上线#1教程中,我加入这个类。我不知道我在做什么。但我会尽我所能继续:

 抽象类RetrievePollenTask扩展的AsyncTask&LT;整数,太虚,花粉&GT;
{    保护花粉doInBackground(字符串... PARAMS)
    {
        // TODO自动生成方法存根
        返回null;
    }}


解决方案

是的,你正在尝试做的UI线程这是非法的内部网络和捕捉异常是 NetworkOnMainThreadException

相反,可以使用主线程内联的的AsyncTask ,你现在做的权利,但它不应该是抽象的,这只是一个普通的类,所以你可以执行的AsyncTask ..

例如:

 公共类RetrievePollenTask扩展的AsyncTask&LT;整数,太虚,花粉&GT;
{    保护花粉doInBackground(字符串... PARAMS)
    {
        花粉pollenObject =新的花粉(19104);
        返回pollenObject;
    }    保护无效onPostExecute(花粉结果){
         textview.setText(pollenObject.getCity());
     }}

你可以让你的AsyncTask作为一个内部类的片段你所以你不需要传递它的上下文参数。也不要把更新insidte任何视图中的 doInBackground 的原因这是一个不同的线程,它会捕获异常。

I currently have a Pollen class which is a class I wrote which uses the JSoup library to parse HTML. Also shown here is my PlaceholderFragment class.

    public static class PlaceholderFragment extends Fragment
    {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState)
        {
            final Button button = (Button) rootView.findViewById(R.id.button1);
            final TextView textview = (TextView) rootView.findViewById(R.id.textview1);

            button.setOnClickListener(new View.OnClickListener()
            {

                @Override
                public void onClick(View v)
                {
                    Pollen pollenObject = new Pollen(19104);
                    textview.setText(pollenObject.getCity());
                }
            });

            return rootView;
        }
    }

Here is my Pollen class.

public static class Pollen
{

    @SuppressLint("SimpleDateFormat")
    public Pollen(int zipcode)
    {
        this.zipcode = zipcode;
        Document doc;
        try
        {
            // pass address to 
            doc = Jsoup.connect("http://www.wunderground.com/DisplayPollen.asp?Zipcode=" + this.zipcode).get();

            // get "location" from XML
            Element location = doc.select("div.columns").first();
            this.location = location.text();

            // get "pollen type" from XML
            Element pollenType = doc.select("div.panel h3").first();
            this.pollenType = pollenType.text();

            SimpleDateFormat format = new SimpleDateFormat("EEE MMMM dd, yyyy");

            // add the four items of pollen and dates
            // to its respective list
            for(int i = 0; i < 4; i++)
            {
                Element dates = doc.select("td.text-center.even-four").get(i);
                Element levels = doc.select("td.levels").get(i);

                try
                {
                    pollenMap.put(format.parse(dates.text()), levels.text());
                }
                catch (ParseException e)
                {
                    e.printStackTrace();
                }
            }
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

I learned a lot while failing every attempt. I discovered that, in my use of calling my Pollen class within onClick, I am doing an expensive task. Thus, I should put it in a separate thread. To add, since I am calling my Pollen class within my main/UI thread, it causes my app to crash.

I consulted this Stackoverflow question in aiding my attempt to solve my issue: android.os.NetworkOnMainThreadException

I discovered my error and solution via this error log from logcat, specifically, NetworkOnMainThread where Android explicitly prevents me from doing anything network on my UI thread.

My question is - how do I allocate my Pollen class into a separate thread that is not in my UI class?

Continuing my tutorial on that Stackoverflow thread, I have added this class. I have no idea what I am doing.. But I will try my best to continue:

abstract class RetrievePollenTask extends AsyncTask<Integer, Void, Pollen>
{

    protected Pollen doInBackground(String... params)
    {
        // TODO Auto-generated method stub
        return null;
    }

}

解决方案

Yes you are trying to do networking inside the UI thread which is illegal and catch an exception which is NetworkOnMainThreadException.

Instead of connecting inside the main thread you can use the AsyncTask which you are doing right now but it shouldn't be abstract it is just a plain class so you can execute the AsyncTask..

example:

    public class RetrievePollenTask extends AsyncTask<Integer, Void, Pollen>
{

    protected Pollen doInBackground(String... params)
    {
        Pollen pollenObject = new Pollen(19104);
        return pollenObject;
    }

    protected void onPostExecute(Pollen result) {
         textview.setText(pollenObject.getCity());
     }

}

you can make your asynctask as an inner class of you fragment so you dont need to pass the context parameter on it. Also dont put update any view insidte the doInBackground cause it is a different thread that it will catch an exception.

这篇关于在单独的线程网络相关的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆