AsyncTask中的java.lang.NullPointerException

时间:2013-04-25 09:57:12

标签: java android eclipse android-asynctask nullpointerexception

我正在尝试使用AsycTask“优化”我的应用程序代码,但是我收到了java.lang.NullPointerException错误。

你能帮我弄清楚我做错了吗?

package it.vscreazioni.farmachimica;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;

public class MostraTutti extends SherlockActivity {
    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,
                    R.drawable.acidoascorbico,R.drawable.acidobarbiturico,R.drawable.acidobenzoico,...};

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

            setContentView(R.layout.mostra_tutti);
            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...");
                    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);

                                    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) {
                    CustomListViewAdapter adapter = new CustomListViewAdapter(MostraTutti.this,items);
                            lv.setAdapter(adapter);
                    /*
                    _adapter = new CustomListViewAdapter(News.this,Rssparser.items);
                    lv=(ListView)findViewById(R.id.list);
                    lv.setAdapter(_adapter);
                            Dialog.dismiss();
                            lv.setOnItemClickListener(new OnItemClickListener()
                            {
                                    public void onItemClick(AdapterView<?> arg0, View v, int position, long id)
                                    {                       
                                            Context context = getBaseContext();
                                   Intent myIntent = new Intent(context, LeggiArticolo.class);

                                   myIntent.putExtra("testo",Rssparser.testo.get(position));
                                   myIntent.putExtra("titolo",Rssparser.titolo.get(position));
                                   myIntent.putExtra("immagine",Rssparser.immagini.get(position));
                                   myIntent.putExtra("link",Rssparser.indirizzo.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;
}
}

我得到了这个错误:

04-25 11:43:57.872: W/dalvikvm(1663): threadid=1: thread exiting with uncaught exception 
(group=0x40a13300)
04-25 11:43:57.902: E/AndroidRuntime(1663): FATAL EXCEPTION: main
04-25 11:43:57.902: E/AndroidRuntime(1663): java.lang.RuntimeException: Unable to 
instantiate activity   
ComponentInfo{it.vscreazioni.farmachimica/it.vscreazioni.farmachimica.MostraTutti}:   
java.lang.NullPointerException
04-25 11:43:57.902: E/AndroidRuntime(1663):     at 
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at 
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at 
android.app.ActivityThread.access$600(ActivityThread.java:130)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at 
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at 
android.os.Handler.dispatchMessage(Handler.java:99)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at android.os.Looper.loop(Looper.java:137)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at 
android.app.ActivityThread.main(ActivityThread.java:4745)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at 
java.lang.reflect.Method.invokeNative(Native Method)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at 
java.lang.reflect.Method.invoke(Method.java:511)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at 
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at 
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at dalvik.system.NativeStart.main(Native 
Method)
04-25 11:43:57.902: E/AndroidRuntime(1663): Caused by: java.lang.NullPointerException
04-25 11:43:57.902: E/AndroidRuntime(1663):     at 
android.app.Activity.findViewById(Activity.java:1825)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at 
it.vscreazioni.farmachimica.MostraTutti.<init>(MostraTutti.java:25)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at java.lang.Class.newInstanceImpl(Native 
Method)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at 
java.lang.Class.newInstance(Class.java:1319)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at 
android.app.Instrumentation.newActivity(Instrumentation.java:1053)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at 
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
04-25 11:43:57.902: E/AndroidRuntime(1663):     ... 11 more

你能帮帮我吗?

回答后编辑:

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

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

    @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();
                            //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();
                    }       

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

错误消失了!但是有一种奇怪的行为:现在在模拟器中它需要比“正常”方式更长的时间:

非异步时为16秒,异步时为1分钟

2 个答案:

答案 0 :(得分:3)

您正在尝试在活动创建之前获取视图:

final ListView lv = (ListView) findViewById(R.id.listView);

在setContentView之后将此行放在onCreate函数中。

答案 1 :(得分:0)

你不能简单地用这种方式声明一个字段:

final ListView lv = (ListView) findViewById(R.id.listView);
必须在findViewById()电话后调用

setContentView(),否则您将始终获得NullPointerExceptions。如果您尝试最小化与findViewById()相关的代码行数,我建议使用名为roboguice的依赖注入框架。