0

I'm trying to "optimize" my app's code using AsycTask, but I receive the java.lang.NullPointerException error.

Can you please help me to figure it out where I'm doing it wrong?

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

And I get this Error:

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

Can you please help me?

EDIT AFTER ANSWER:

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

And the error's gone! But there's a strange behaviour: now in simulator it take's longer than the "normal" way:

16 seconds with the not Async and 1 minute with Async...

Enzoses
  • 115
  • 14

2 Answers2

3

You are trying to get a view before activity create:

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

put this line in the onCreate function after setContentView.

cy3er
  • 1,699
  • 11
  • 14
0

You can't simply declare a field this way:

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

findViewById() must be called after the setContentView() call, otherwise you'll be getting NullPointerExceptions all the time. If you're trying to minimize the number of lines of code related to findViewById(), I'd recommend using a dependency injection framework called roboguice.

Egor
  • 39,695
  • 10
  • 113
  • 130
  • 1
    A question on Stackoverflow equals to one issue, if you have another you will need to create a new question and provide a proper description of your problem. – Egor Apr 25 '13 at 10:58
  • I'm sorry, I just did it. Please take a look, if you can: http://stackoverflow.com/questions/16213118/xml-parsing-with-asynctask-slower-than-parsing-in-main-thread – Enzoses Apr 25 '13 at 11:08