使用AsyncTask进行Xml解析比在主线程中解析慢 [英] Xml parsing with AsyncTask slower than parsing in main Thread

查看:213
本文介绍了使用AsyncTask进行Xml解析比在主线程中解析慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有一个奇怪的行为:使用asyncTask解析模拟器上的本地xml文件比在主线程上解析更长时间。



这是我的代码与AsyncTask:

  public class MostraTutti扩展了SherlockActivity {
ListView lv;
final List< ListViewItem> items = new ArrayList< MostraTutti.ListViewItem>();
final ArrayList< String> nome = new ArrayList< String>();
final ArrayList< String> immagine = new ArrayList< String>();
...

final int array_image2 [] = {R.drawable.iodocloroidrossichinolina,R.drawable.acidoacetilsalicilico,
...};

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);

setContentView(R.layout.mostra_tutti);
lv =(ListView)findViewById(R.id.listView);
getSupportActionBar()。setDisplayShowHomeEnabled(false);

RssFeedTask rssTask = new RssFeedTask();
rssTask.execute();

}

private class RssFeedTask extends AsyncTask< String,Void,String> {
private ProgressDialog Dialog;
String response =;

@Override
protected void onPreExecute(){
Dialog = new ProgressDialog(MostraTutti.this);
Dialog.setMessage(Leggo le sostanze ...);
Dialog.show();
}

@Override
protected String doInBackground(String ... urls){
InputStream xmlFile = getResources()。openRawResource(R.raw.sostanze);
try {

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
final document document = documentBuilder.parse(xmlFile);
document.getDocumentElement()。normalize();
NodeList nodeList = document.getElementsByTagName(sostanza); (int i = 0; i< nodeList.getLength(); i ++){
final int indice = i;



nome.add(document.getElementsByTagName(nome)。item(indice).getTextContent());
iupac.add(document.getElementsByTagName(iupac)。item(indice).getTextContent());
aspetto.add(document.getElementsByTagName(aspetto)。item(indice).getTextContent());
formula.add(document.getElementsByTagName(formula)。item(indice).getTextContent());
immagine.add(document.getElementsByTagName(immagine)。item(indice).getTextContent());
appartenenza.add(document.getElementsByTagName(appartenenza)。item(indice).getTextContent());
spiegazione.add(document.getElementsByTagName(spiegazione)。item(indice).getTextContent());
tempFus.add(document.getElementsByTagName(temperaturaFusione)。item(indice).getTextContent());
tempEboll.add(document.getElementsByTagName(temperaturaEbollizione)。item(indice).getTextContent());
solubilita.add(document.getElementsByTagName(dissolve)。item(indice).getTextContent());
note.add(document.getElementsByTagName(eccezioni)。item(indice).getTextContent());

String str = document.getElementsByTagName(formula)。item(indice).getTextContent();

str = str.replaceAll(0,\\\₀);
str = str.replaceAll(1,\\\₁);
str = str.replaceAll(2,\\\₂);
str = str.replaceAll(3,\\\₃);
str = str.replaceAll(4,\\\₄);
str = str.replaceAll(5,\\\₅);
str = str.replaceAll(6,\\\₆);
str = str.replaceAll(7,\\\₇);
str = str.replaceAll(8,\\\₈);
str = str.replaceAll(9,\\\₉);

final String stringa = str;
formulaConvertita.add(stringa);

// CustomListViewAdapter adapter = new CustomListViewAdapter(MostraTutti.this,items);
//lv.setAdapter(adapter);
items.add(new ListViewItem()
{{
ThumbnailResource = array_image2 [indice];
标题= document.getElementsByTagName(nome)。item(indice).getTextContent ();
SubTitle = stringa;
}});
};

} catch(IOException e1){
// TODO自动生成的catch块
e1.printStackTrace();
} catch(ParserConfigurationException e){
// TODO自动生成的catch块
e.printStackTrace();
} catch(SAXException e){
// TODO自动生成的catch块
e.printStackTrace();
}

返回响应;
}
@Override
protected void onPostExecute(String result){
Dialog.dismiss();
CustomListViewAdapter adapter = new CustomListViewAdapter(MostraTutti.this,items);
lv.setAdapter(adapter);

lv.setOnItemClickListener(
new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0,View v,int position,long id)
{
Context context = getBaseContext();
Intent myIntent = new Intent(context,Dettagli.class);

myIntent.putExtra(nome_sostanza,nome。 get(position));
// myIntent.putExtra(formula,formula.get(position));
myIntent.putExtra(iupac,iupac.get(position));
myIntent.putExtra(aspetto,aspetto.get(position));
myIntent.putExtra(appartenenza,appartenenza.get(position));
myIntent.putExtra(dissolve solubilita.g等(位置));
myIntent.putExtra(tempFus,tempFus.get(position));
myIntent.putExtra(tempEboll,tempEboll.get(position));
myIntent.putExtra(spiegazione,spiegazione.get(position));
myIntent.putExtra(immagine,array_image2 [position]);
myIntent.putExtra(formulaConvertita,formulaConvertita.get(position));
myIntent.putExtra(note,note.get(position));
startActivityForResult(myIntent,0);
}

}
);
}
}

@Override
public boolean onCreateOptionsMenu(菜单菜单){
//充满菜单;如果存在,则会将项目添加到操作栏。
getSupportMenuInflater()。inflate(R.menu.activity_main,menu);
返回true;
}

class ListViewItem {
public int ThumbnailResource;
public String Title;
public String SubTitle;
}
}

这里是没有AsyncTask的代码:

  public class MostraTutti扩展SherlockActivity {
@Override
protected void onCreate(Bundle savedInstanceState){
super .onCreate(savedInstanceState);

setContentView(R.layout.mostra_tutti);
getSupportActionBar()。setDisplayShowHomeEnabled(false);

final ListView lv =(ListView)findViewById(R.id.listView);
final List< ListViewItem> items = new ArrayList< MostraTutti.ListViewItem>();
final ArrayList< String> nome = new ArrayList< String>();
final ArrayList< String> immagine = new ArrayList< String>();
...

final int array_image2 [] = {R.drawable.iodocloroidrossichinolina,R.drawable.acidoacetilsalicilico,
...};

InputStream xmlFile = getResources()。openRawResource(R.raw.sostanze);

  try {

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
final document document = documentBuilder.parse(xmlFile);
document.getDocumentElement()。normalize();
//tagHandler.handleChannelTag(document);
NodeList nodeList = document.getElementsByTagName(sostanza); (int i = 0; i< nodeList.getLength(); i ++){
final int indice = i;



nome.add(document.getElementsByTagName(nome)。item(indice).getTextContent());
iupac.add(document.getElementsByTagName(iupac)。item(indice).getTextContent());
aspetto.add(document.getElementsByTagName(aspetto)。item(indice).getTextContent());
formula.add(document.getElementsByTagName(formula)。item(indice).getTextContent());
immagine.add(document.getElementsByTagName(immagine)。item(indice).getTextContent());
appartenenza.add(document.getElementsByTagName(appartenenza)。item(indice).getTextContent());
spiegazione.add(document.getElementsByTagName(spiegazione)。item(indice).getTextContent());
tempFus.add(document.getElementsByTagName(temperaturaFusione)。item(indice).getTextContent());
tempEboll.add(document.getElementsByTagName(temperaturaEbollizione)。item(indice).getTextContent());
solubilita.add(document.getElementsByTagName(dissolve)。item(indice).getTextContent());
note.add(document.getElementsByTagName(eccezioni)。item(indice).getTextContent());

String str = document.getElementsByTagName(formula)。item(indice).getTextContent();

str = str.replaceAll(0,\\\₀);
str = str.replaceAll(1,\\\₁);
str = str.replaceAll(2,\\\₂);
str = str.replaceAll(3,\\\₃);
str = str.replaceAll(4,\\\₄);
str = str.replaceAll(5,\\\₅);
str = str.replaceAll(6,\\\₆);
str = str.replaceAll(7,\\\₇);
str = str.replaceAll(8,\\\₈);
str = str.replaceAll(9,\\\₉);

final String stringa = str;
formulaConvertita.add(stringa);

items.add(new ListViewItem()
{{
ThumbnailResource = array_image2 [indice];
标题= document.getElementsByTagName(nome)。item indice).getTextContent();
SubTitle = stringa;
}});
}
} catch(IOException e1){
// TODO自动生成的catch块
e1.printStackTrace();
} catch(ParserConfigurationException e){
// TODO自动生成的catch块
e.printStackTrace();
} catch(SAXException e){
// TODO自动生成的catch块
e.printStackTrace();
}
CustomListViewAdapter adapter = new CustomListViewAdapter(this,items);
lv.setAdapter(adapter);

lv.setOnItemClickListener(
new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0,View v,int position,long id)
{
Context context = getBaseContext();
Intent myIntent = new Intent(context,Dettagli.class);

myIntent.putExtra(nome_sostanza,nome。 get(position));
// myIntent.putExtra(formula,formula.get(position));
myIntent.putExtra(iupac,iupac.get(position));
myIntent.putExtra(aspetto,aspetto.get(position));
myIntent.putExtra(appartenenza,appartenenza.get(position));
myIntent.putExtra(dissolve ();
myIntent.putExtra(tempFus,tempFus.get(position));
myIntent.putExtra( tempEboll,tempEboll.get(位置));
myIntent.putExtra(spiegazione,spiegazione.get(position));
myIntent.putExtra(immagine,array_image2 [position]);
myIntent.putExtra(formulaConvertita,formulaConvertita.get(position));
myIntent.putExtra(note,note.get(position));
startActivityForResult(myIntent,0);
}

}
);
}

@Override
public boolean onCreateOptionsMenu(菜单菜单){
getSupportMenuInflater()。inflate(R.menu.activity_main,menu);
返回true;
}

class ListViewItem {
public int ThumbnailResource;
public String Title;
public String SubTitle;
}
}

模拟器上的差异是16秒一分钟和一分钟的AsyncTask一个!

解决方案

我把这个问题标记为重复,但是上次我这样做,评论者投票反对。



无论哪种方式,原因是 AsyncTask doInBackground()运行在背景优先级类中,并且必须与所有其他后台任务(如RSS阅读器等)共享最多10%的CPU时间,无论系统真正处于空闲状态。



有关详细讨论和解决方案,请参阅此处


I'm having a strange behaviour in my code: parsing a local xml file on simulator with asyncTask takes longer than parsing it on main thread.

Here is my code with AsyncTask:

public class MostraTutti extends SherlockActivity {
ListView lv;
final List<ListViewItem> items = new ArrayList<MostraTutti.ListViewItem>();
final ArrayList<String> nome = new ArrayList<String>();
final ArrayList<String> immagine = new ArrayList<String>();
...

final   int array_image2[] ={R.drawable.iodocloroidrossichinolina,R.drawable.acidoacetilsalicilico,
        ...};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.mostra_tutti);
    lv = (ListView) findViewById(R.id.listView);
    getSupportActionBar().setDisplayShowHomeEnabled(false);

    RssFeedTask rssTask = new RssFeedTask();
       rssTask.execute();

}

private class RssFeedTask extends AsyncTask<String, Void, String> {
    private ProgressDialog Dialog;
    String response = "";

    @Override
    protected void onPreExecute() {
        Dialog = new ProgressDialog(MostraTutti.this);
        Dialog.setMessage("Leggo le sostanze...");
        Dialog.show();
    }

        @Override
        protected String doInBackground(String... urls) {
            InputStream xmlFile = getResources().openRawResource(R.raw.sostanze);
            try {

            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            final Document document = documentBuilder.parse(xmlFile);
            document.getDocumentElement().normalize();
            NodeList nodeList = document.getElementsByTagName("sostanza");

            for (int i = 0; i < nodeList.getLength(); i++) {
            final int   indice = i;

            nome.add(document.getElementsByTagName("nome").item(indice).getTextContent());
            iupac.add(document.getElementsByTagName("iupac").item(indice).getTextContent());
            aspetto.add(document.getElementsByTagName("aspetto").item(indice).getTextContent());
            formula.add(document.getElementsByTagName("formula").item(indice).getTextContent());
            immagine.add(document.getElementsByTagName("immagine").item(indice).getTextContent());
            appartenenza.add(document.getElementsByTagName("appartenenza").item(indice).getTextContent());
            spiegazione.add(document.getElementsByTagName("spiegazione").item(indice).getTextContent());
            tempFus.add(document.getElementsByTagName("temperaturaFusione").item(indice).getTextContent());
            tempEboll.add(document.getElementsByTagName("temperaturaEbollizione").item(indice).getTextContent());
            solubilita.add(document.getElementsByTagName("solubilita").item(indice).getTextContent());
            note.add(document.getElementsByTagName("eccezioni").item(indice).getTextContent());

            String str = document.getElementsByTagName("formula").item(indice).getTextContent();

            str = str.replaceAll("0", "\u2080");
            str = str.replaceAll("1", "\u2081");
            str = str.replaceAll("2", "\u2082");
            str = str.replaceAll("3", "\u2083");
            str = str.replaceAll("4", "\u2084");
            str = str.replaceAll("5", "\u2085");
            str = str.replaceAll("6", "\u2086");
            str = str.replaceAll("7", "\u2087");
            str = str.replaceAll("8", "\u2088");
            str = str.replaceAll("9", "\u2089");

            final String stringa = str;
            formulaConvertita.add(stringa);

                    //CustomListViewAdapter adapter = new CustomListViewAdapter(MostraTutti.this,items);
                    //lv.setAdapter(adapter);
                    items.add(new ListViewItem()
                    {{
                        ThumbnailResource = array_image2[indice];
                        Title = document.getElementsByTagName("nome").item(indice).getTextContent();
                        SubTitle = stringa;
                    }});   
            };

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   

        return response;
}
        @Override
        protected void onPostExecute(String result) {
            Dialog.dismiss();
            CustomListViewAdapter adapter = new CustomListViewAdapter(MostraTutti.this,items);
            lv.setAdapter(adapter);

            lv.setOnItemClickListener(
                    new OnItemClickListener()
                    {
                        public void onItemClick(AdapterView<?> arg0, View v, int position, long id)
                        {                           
                            Context context = getBaseContext();
                           Intent myIntent = new Intent(context, Dettagli.class);

                           myIntent.putExtra("nome_sostanza",nome.get(position));
                         //  myIntent.putExtra("formula",formula.get(position));
                           myIntent.putExtra("iupac",iupac.get(position));                  
                           myIntent.putExtra("aspetto",aspetto.get(position));                 
                           myIntent.putExtra("appartenenza",appartenenza.get(position));
                           myIntent.putExtra("solubilita",solubilita.get(position));
                           myIntent.putExtra("tempFus",tempFus.get(position));
                           myIntent.putExtra("tempEboll",tempEboll.get(position));
                           myIntent.putExtra("spiegazione",spiegazione.get(position));
                           myIntent.putExtra("immagine", array_image2[position]);
                           myIntent.putExtra("formulaConvertita", formulaConvertita.get(position));
                           myIntent.putExtra("note", note.get(position));
                           startActivityForResult(myIntent, 0);
                        }

                        }
                 );
        }
        }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getSupportMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

class ListViewItem {
public int ThumbnailResource;
public String Title;
public String SubTitle;
}
}

And here's my code with no AsyncTask:

public class MostraTutti extends SherlockActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.mostra_tutti);
    getSupportActionBar().setDisplayShowHomeEnabled(false);

    final ListView lv = (ListView) findViewById(R.id.listView);
    final List<ListViewItem> items = new ArrayList<MostraTutti.ListViewItem>();
    final ArrayList<String> nome = new ArrayList<String>();
    final ArrayList<String> immagine = new ArrayList<String>();
    ...

    final   int array_image2[] ={R.drawable.iodocloroidrossichinolina,R.drawable.acidoacetilsalicilico,
            ...};

InputStream xmlFile = getResources().openRawResource(R.raw.sostanze);

    try {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        final Document document = documentBuilder.parse(xmlFile);
        document.getDocumentElement().normalize();
        //tagHandler.handleChannelTag(document);
        NodeList nodeList = document.getElementsByTagName("sostanza");

        for (int i = 0; i < nodeList.getLength(); i++) {
        final int   indice = i;

        nome.add(document.getElementsByTagName("nome").item(indice).getTextContent());
        iupac.add(document.getElementsByTagName("iupac").item(indice).getTextContent());
        aspetto.add(document.getElementsByTagName("aspetto").item(indice).getTextContent());
        formula.add(document.getElementsByTagName("formula").item(indice).getTextContent());
        immagine.add(document.getElementsByTagName("immagine").item(indice).getTextContent());
        appartenenza.add(document.getElementsByTagName("appartenenza").item(indice).getTextContent());
        spiegazione.add(document.getElementsByTagName("spiegazione").item(indice).getTextContent());
        tempFus.add(document.getElementsByTagName("temperaturaFusione").item(indice).getTextContent());
        tempEboll.add(document.getElementsByTagName("temperaturaEbollizione").item(indice).getTextContent());
        solubilita.add(document.getElementsByTagName("solubilita").item(indice).getTextContent());
        note.add(document.getElementsByTagName("eccezioni").item(indice).getTextContent());

        String str = document.getElementsByTagName("formula").item(indice).getTextContent();

        str = str.replaceAll("0", "\u2080");
        str = str.replaceAll("1", "\u2081");
        str = str.replaceAll("2", "\u2082");
        str = str.replaceAll("3", "\u2083");
        str = str.replaceAll("4", "\u2084");
        str = str.replaceAll("5", "\u2085");
        str = str.replaceAll("6", "\u2086");
        str = str.replaceAll("7", "\u2087");
        str = str.replaceAll("8", "\u2088");
        str = str.replaceAll("9", "\u2089");

        final String stringa = str;
        formulaConvertita.add(stringa);

        items.add(new ListViewItem()
            {{
                ThumbnailResource = array_image2[indice];
                Title = document.getElementsByTagName("nome").item(indice).getTextContent();
                SubTitle = stringa;
            }});
        }
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }       
    CustomListViewAdapter adapter = new CustomListViewAdapter(this,items);
    lv.setAdapter(adapter);

    lv.setOnItemClickListener(
            new OnItemClickListener()
            {
                public void onItemClick(AdapterView<?> arg0, View v, int position, long id)
                {                           
                    Context context = getBaseContext();
                   Intent myIntent = new Intent(context, Dettagli.class);

                   myIntent.putExtra("nome_sostanza",nome.get(position));
                 //  myIntent.putExtra("formula",formula.get(position));
                   myIntent.putExtra("iupac",iupac.get(position));                  
                   myIntent.putExtra("aspetto",aspetto.get(position));                 
                   myIntent.putExtra("appartenenza",appartenenza.get(position));
                   myIntent.putExtra("solubilita",solubilita.get(position));
                   myIntent.putExtra("tempFus",tempFus.get(position));
                   myIntent.putExtra("tempEboll",tempEboll.get(position));
                   myIntent.putExtra("spiegazione",spiegazione.get(position));
                   myIntent.putExtra("immagine", array_image2[position]);
                   myIntent.putExtra("formulaConvertita", formulaConvertita.get(position));
                   myIntent.putExtra("note", note.get(position));
                   startActivityForResult(myIntent, 0);
                }

                }
         );
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getSupportMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

class ListViewItem {
public int ThumbnailResource;
public String Title;
public String SubTitle;
}
}

The difference on simulator is 16 seconds for the main thread one and 1 minute for the AsyncTask one!

解决方案

I've marked this question as a duplicate but last time I did this, the reviewers voted against it.

Either way, the reason is that AsyncTask's doInBackground() runs in a backgroud priority class and has to share at most 10% of CPU time with all other background tasks, such as your RSS reader's etc -- no matter how idle the system really is.

For a detailed discussion and solution, see here.

这篇关于使用AsyncTask进行Xml解析比在主线程中解析慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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