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 함수에 넣습니다. 그렇지 않으면 당신은 NullPointerExceptions 모든 시간을 받고있을거야,

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

findViewById()setContentView() 호출 후에 호출해야합니다

+0

제 편집을보세요 – Enzoses

0

당신은 단순히 필드 이런 식으로 선언 할 수 없습니다. findViewById()과 관련된 코드 줄을 최소화하려는 경우 roboguice이라는 종속성 주입 프레임 워크를 사용하는 것이 좋습니다.

+0

Ok! 내 편집 좀 봐주세요. – Enzoses

+1

Stackoverflow에 관한 한 질문과 동일한 문제가 있습니다. 다른 질문이있는 경우 새로운 질문을 작성하고 문제에 대한 적절한 설명을 제공해야합니다. – Egor

+0

죄송합니다, 방금했습니다. 가능한 경우 다음을 참조하십시오. http://stackoverflow.com/questions/16213118/xml-parsing-with-asynctask-slower-than-parsing-in-main-thread – Enzoses