2013-04-25 100 views
0

我試圖使用AsycTask「優化」我的應用程序的代碼,但我收到java.lang.NullPointerException錯誤。AsyncTask中的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分鐘......

回答

3

您正試圖獲得活動前視圖創建:

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

將此行放在setContentView之後的onCreate函數中。

+0

好的!請看看我的編輯 – Enzoses 2013-04-25 10:53:55

0

你不能簡單地聲明一個字段是這樣的:

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

findViewById()必須setContentView()調用之後被調用,否則你會得到NullPointerExceptions所有的時間。如果您想盡量減少與findViewById()相關的代碼行數,我建議使用稱爲roboguice的依賴注入框架。

+0

好的!請看看我的編輯 – Enzoses 2013-04-25 10:54:38

+1

關於Stackoverflow的問題等於一個問題,如果您有另一個問題,您需要創建一個新問題並提供問題的正確描述。 – Egor 2013-04-25 10:58:35

+0

對不起,我剛剛做到了。請看看,如果你可以:http://stackoverflow.com/questions/16213118/xml-parsing-with-asynctask-slower-than-parsing-in-main-thread – Enzoses 2013-04-25 11:08:12