Android的AsyncTask的,$ P从冷冻$ pvent UI [英] Android asynctask, prevent UI from freezing

查看:143
本文介绍了Android的AsyncTask的,$ P从冷冻$ pvent UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的和平code,即从网址获取一些XML数据。

I have this peace of code, that fetches some xml data from an url.

它确实是正确的工作,但问题是,虽然它下载
并解析XML用户界面冻结,这可能是用户的一个问题。

It does it's job properly but the problem is that while it downloads and parses xml the UI freezes, and that might be a problem for the users.

下面是类

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.kategoria);

    // getting intent data
    Intent in = getIntent();
    String cat_name = in.getStringExtra("kategoria");
    //Update Textview
    TextView kategoriatw = (TextView)findViewById(R.id.name_of_cat);
    kategoriatw.setText(cat_name);



    // Kategoro URL
    String catUrl = "http://sample.com/xmldata.xml";


    ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
    //MOTHERLAJME MULTIDIMENSIONAl
    final List<HashMap<String, String>> MotherContainer= new ArrayList<HashMap<String, String>>();


    try{ 

        XMLParser parser = new XMLParser();
        String xml   = parser.getXmlFromUrl(catUrl); // getting XML
        Document doc = parser.getDomElement(xml); // getting DOM element


        //ALL
        NodeList forecastW = doc.getElementsByTagName("newsitem");

        for (int j = 0; j < forecastW.getLength(); j++)
        {
            HashMap<String, String> map = new HashMap<String, String>();

            Node nodeday = forecastW.item(j);
            Element dayElmnt = (Element) nodeday;

            map.put("title", (parser.getValue(dayElmnt, "title")) );
            map.put("intro", (parser.getValue(dayElmnt, "intro")).toString());

            map.put("story_id", ""+j ); 

            // adding HashList to ArrayList
            menuItems.add(map);


            //MULTI DIMENSIONAL ARRAY
            HashMap<String, String> TheStory= new HashMap<String, String>();
            TheStory .put("title", (parser.getValue(dayElmnt, "title")));
            TheStory .put("story_date", parser.getValue(dayElmnt, "datetime"));
            MotherContainer.add(j, TheStory);
            /////////////////////////

        }


    } catch (Exception e) {
        System.out.println("XML Pasing Excpetion = " + e);
    }



    // Adding menuItems to ListView
    ListAdapter adapter = new SimpleAdapter(this, menuItems,
            R.layout.week_day_item,
            new String[] { "title", "intro", "story_id"}, new int[] {
                    R.id.title_list,
                    R.id.intro_list,
                    R.id.story_id_list});

    setListAdapter(adapter);

    // selecting single ListView item
    ListView lv = getListView();


    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            // Starting new intent
            Intent in = new Intent(getApplicationContext(), SingleLajm.class);
            //start new intent....
            startActivity(in);

        }

    });

}

我想使用的AsyncTask,这样的UI不会冻结,并使用这个对我的类IM,
这是即时通讯使用类的升级版本,实现异步:

I want to use Asynctask so that the UI won't freeze and Im using this on my class, this is the "updated" version of the class that Im using, that implements async:

Document doc;
String xml;
ListView lv;
//ListViewAdapter adapter;
//ArrayList<HashMap<String, String>> menuItems;
ProgressDialog pDialog;


final ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
//MOTHERLAJME MULTIDIMENSIONAl
final List<HashMap<String, String>> MotherLajme= new ArrayList<HashMap<String, String>>();

final HashMap<String, String> nrLajmit = new HashMap<String, String>();


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.kategoria);

    // getting intent data
    Intent in = getIntent();
    // Get emr
    String catname = in.getStringExtra("kategoria");
    //Textview
    TextView kategoriatw = (TextView)findViewById(R.id.kategoria_emri);
    kategoriatw.setText(catname);



}

private class loadMoreListView extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        // Showing progress dialog before sending http request
        pDialog = new ProgressDialog(
                Kategoria.this);
        pDialog.setMessage("Please wait..");
        pDialog.setIndeterminate(true);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    protected Void doInBackground(Void... unused) {
        new Runnable() {
            public void run() {


                XMLParser parser = new XMLParser();
                String xml   = parser.getXmlFromUrl("http://sample.com/data.xml"); // getting XML
                Document doc = parser.getDomElement(xml); // getting DOM element


                //ALL
                NodeList forecastW = doc.getElementsByTagName("newsitem");

                for (int j = 0; j < forecastW.getLength(); j++)
                {
                    HashMap<String, String> map = new HashMap<String, String>();

                    Node nodeday = forecastW.item(j);
                    Element dayElmnt = (Element) nodeday;

                    map.put("title", (parser.getValue(dayElmnt, "title")) );
                    map.put("intro", (parser.getValue(dayElmnt, "intro")) );

                    map.put("story_id", ""+j ); 
                    // adding HashList to ArrayList
                    menuItems.add(map);


                    //MULTI DIMENSIONAL ARRAY
                    HashMap<String, String> TheLajmi= new HashMap<String, String>();
                    TheLajmi .put("title", (parser.getValue(dayElmnt, "title")));
                    TheLajmi .put("newsdate", parser.getValue(dayElmnt, "datetime"));
                    MotherLajme.add(j, TheLajmi);
                    /////////////////////////

                }


            }
        };

        return (null);
    }


    protected void onPostExecute(Void unused) {
        // closing progress dialog
        pDialog.dismiss();

        // Adding menuItems to ListView
        ListAdapter adapter = new SimpleAdapter(Kategoria.this, menuItems,
                R.layout.week_day_item,
                new String[] { "title", "intro", "story_id"}, new int[] {
                        R.id.title_list,
                        R.id.intro_list,
                        R.id.story_id_list});

        setListAdapter(adapter);

        // selecting single ListView item
        ListView lv = getListView();

        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem

                // Starting new intent
                Intent in = new Intent(getApplicationContext(), SingleLajm.class);
                in.putExtra("title", "blabla");
                startActivity(in);

            }

        });

    }
}

但我不能得到它的工作。我看到的要么是空白页或一些错误
我不能修改意见。

But I can't get it to work. All I see is either a blank page or some error that I cannot edit the views.

有人可以帮助解决这个问题?

Can someone help to solve this issue?

感谢。

推荐答案

尝试以下code:

private class LoadMoreListView extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {

@Override
protected void onPreExecute() {
    // Showing progress dialog before sending http request
    pDialog = new ProgressDialog(
            AndroidListViewWithLoadMoreButtonActivity.this);
    pDialog.setMessage("Please wait..");
    pDialog.setIndeterminate(true);
    pDialog.setCancelable(false);
    pDialog.show();
}

protected ArrayList<HashMap<String, String>> doInBackground(Void... unused) {

      ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
//MOTHERLAJME MULTIDIMENSIONAl
final List<HashMap<String, String>> MotherContainer= new ArrayList<HashMap<String, String>>();


try{ 

    XMLParser parser = new XMLParser();
    String xml   = parser.getXmlFromUrl(catUrl); // getting XML
    Document doc = parser.getDomElement(xml); // getting DOM element


    //ALL
    NodeList forecastW = doc.getElementsByTagName("newsitem");

    for (int j = 0; j < forecastW.getLength(); j++)
    {
        HashMap<String, String> map = new HashMap<String, String>();

        Node nodeday = forecastW.item(j);
        Element dayElmnt = (Element) nodeday;

        map.put("title", (parser.getValue(dayElmnt, "title")) );
        map.put("intro", (parser.getValue(dayElmnt, "intro")).toString());

        map.put("story_id", ""+j ); 

        // adding HashList to ArrayList
        menuItems.add(map);


        //MULTI DIMENSIONAL ARRAY
        HashMap<String, String> TheStory= new HashMap<String, String>();
        TheStory .put("title", (parser.getValue(dayElmnt, "title")));
        TheStory .put("story_date", parser.getValue(dayElmnt, "datetime"));
        MotherContainer.add(j, TheStory);
        /////////////////////////

    }


} catch (Exception e) {
    System.out.println("XML Pasing Excpetion = " + e);
}


    return menuItems;
}


protected void onPostExecute(ArrayList<HashMap<String, String>> unused) {
    // closing progress dialog
    pDialog.dismiss();


     // Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(YourActivity.this, unused,
        R.layout.week_day_item,
        new String[] { "title", "intro", "story_id"}, new int[] {
                R.id.title_list,
                R.id.intro_list,
                R.id.story_id_list});

setListAdapter(adapter);


}

的AsyncTask

1参数意味着你可以通过执行类型。虚空意味着你可以通过任何

1st param means the type you can pass to execute. Void means you can pass nothing

Java中的类名称应与上层calse字母开头。请重新命名它为别人更好的可读性。

The class names in Java should start with upper-calse letter. Please rename it for better readability by others.

所以,适当的通话将

new LoadMoreListView().execute();

第二个参数是一个类型的数据可以发布调用 publishProgress() doInBackground()。不要使用 publishProgress ,所以没什么可在这种情况下,提了。

2nd param is a type of data you can publish calling publishProgress() from doInBackground(). You don't use publishProgress, so nothing to mention in this case.

这将传递给 onPostExecute第三个参数平均S型()。要通过菜单项来onPostExecute必须从doInBackground返回。所以你需要声明类

3rd param mean s type that will be passed to onPostExecute(). To pass the menuItems to onPostExecute you must return it from doInBackground. so you need declare your class with

AsyncTask<Void, Void, ArrayList<HashMap<String, String>>>

doInBackground运行在新的线程,所以你不需要以下code:

doInBackground runs on new thread so you don't need following code:

new Runnable() {
            public void run()

如果您想使用UI线程工作,你可以用下面的方法:

if you want work with UI thread you can use following method:


  1. 在preExecute

  1. onPreExecute

onPostExecute

onPostExecute

上preExecute 通常用于显示请稍候对话框或者类似的东西和 onPostExecute 用于显示下载和其他东西后的数据

onPreExecute usually used for showing please wait dialog or something like that and onPostExecute used for showing data after downloading and other thing

这篇关于Android的AsyncTask的,$ P从冷冻$ pvent UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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