0

The objective of below snippet is used for parsing the xml. In that AsynchTask is used for internet connection, However I am getting NullPointerException on the line before the for loop.. here is a snippet and stacktrace..

    public class MainActivity extends Activity {


        static final String KEY_ITEM    = "photo"; // parent node
        String xml;
        Document    doc;
        NodeList    nl;
        DefaultHttpClient   httpClient;
        HttpPost            httpPost;
        HttpResponse        httpRes;
        HttpEntity          httpEnt;

    String xmlurl       = "http://url.xml";

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ArrayList<String> photoLink = new ArrayList<String>();
        new FileFromURL().execute(xmlurl);
        nl  = doc.getElementsByTagName("photo"); /////// line 62
        for(int i=0; i < nl.getLength(); i++){
                   Node node = nl.item(i);
                   Element fstElmnt = (Element) node;
                   photoLink.add(fstElmnt.getAttribute("link"));
        }

        for(int i=0;i<photoLink.size();i++){
            Log.d("Photo link --- " + i,photoLink.get(i));
        }

    }

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


    class FileFromURL extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... xmlur) {
            // TODO Auto-generated method stub

            try {
                httpClient  =   new DefaultHttpClient();
                httpPost    =   new HttpPost(xmlurl);

                httpRes     =   httpClient.execute(httpPost);
                httpEnt     =   httpRes.getEntity();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            try{
                xml                             =   EntityUtils.toString(httpEnt);

                DocumentBuilderFactory  dbf =   DocumentBuilderFactory.newInstance();
                DocumentBuilder db  = dbf.newDocumentBuilder();
                InputSource     is  = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc                 = db.parse(is);

            }catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());

            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());

            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            super.onPostExecute(result);
        }

    }
}

StackTrace :

12-05 11:01:34.128: E/AndroidRuntime(11990): FATAL EXCEPTION: main
12-05 11:01:34.128: E/AndroidRuntime(11990): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gallery.parsing.madhuri/com.example.gallery.parsing.madhuri.MainActivity}: java.lang.NullPointerException
12-05 11:01:34.128: E/AndroidRuntime(11990):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
12-05 11:01:34.128: E/AndroidRuntime(11990):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
12-05 11:01:34.128: E/AndroidRuntime(11990):    at android.app.ActivityThread.access$600(ActivityThread.java:123)
12-05 11:01:34.128: E/AndroidRuntime(11990):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
12-05 11:01:34.128: E/AndroidRuntime(11990):    at android.os.Handler.dispatchMessage(Handler.java:99)
12-05 11:01:34.128: E/AndroidRuntime(11990):    at android.os.Looper.loop(Looper.java:137)
12-05 11:01:34.128: E/AndroidRuntime(11990):    at android.app.ActivityThread.main(ActivityThread.java:4424)
12-05 11:01:34.128: E/AndroidRuntime(11990):    at java.lang.reflect.Method.invokeNative(Native Method)
12-05 11:01:34.128: E/AndroidRuntime(11990):    at java.lang.reflect.Method.invoke(Method.java:511)
12-05 11:01:34.128: E/AndroidRuntime(11990):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
12-05 11:01:34.128: E/AndroidRuntime(11990):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
12-05 11:01:34.128: E/AndroidRuntime(11990):    at dalvik.system.NativeStart.main(Native Method)
12-05 11:01:34.128: E/AndroidRuntime(11990): Caused by: java.lang.NullPointerException
12-05 11:01:34.128: E/AndroidRuntime(11990):    at com.example.gallery.parsing.madhuri.MainActivity.onCreate(MainActivity.java:62)
12-05 11:01:34.128: E/AndroidRuntime(11990):    at android.app.Activity.performCreate(Activity.java:4465)
12-05 11:01:34.128: E/AndroidRuntime(11990):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
12-05 11:01:34.128: E/AndroidRuntime(11990):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
12-05 11:01:34.128: E/AndroidRuntime(11990):    ... 11 more
Nitin Bathija
  • 800
  • 3
  • 12
  • 24

2 Answers2

0

Because you execute your asyncTask but then you try to create nodeList from doc, which may not be initialized yet. You should get nodeList into your asyncTask as well.

Try to do it like this:

public class MainActivity extends Activity {


    static final String KEY_ITEM    = "photo"; // parent node
    String xml;
    Document    doc;
    NodeList    nl;
    DefaultHttpClient   httpClient;
    HttpPost            httpPost;
    HttpResponse        httpRes;
    HttpEntity          httpEnt;

String xmlurl       = "http://url.xml";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayList<String> photoLink = new ArrayList<String>();
    new FileFromURL().execute(xmlurl);

}

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


class FileFromURL extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... xmlur) {
        // TODO Auto-generated method stub

        try {
            httpClient  =   new DefaultHttpClient();
            httpPost    =   new HttpPost(xmlurl);

            httpRes     =   httpClient.execute(httpPost);
            httpEnt     =   httpRes.getEntity();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

        try{
            xml                             =   EntityUtils.toString(httpEnt);

            DocumentBuilderFactory  dbf =   DocumentBuilderFactory.newInstance();
            DocumentBuilder db  = dbf.newDocumentBuilder();
            InputSource     is  = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc                 = db.parse(is);

        }catch (ParserConfigurationException e) {
            Log.e("Error: ", e.getMessage());

        } catch (SAXException e) {
            Log.e("Error: ", e.getMessage());

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

        if(doc != null) {
           nl  = doc.getElementsByTagName("photo"); /////// line 62
           for(int i=0; i < nl.getLength(); i++){
                  Node node = nl.item(i);
                  Element fstElmnt = (Element) node;
                  photoLink.add(fstElmnt.getAttribute("link"));
           }

           for(int i=0;i<photoLink.size();i++){
                Log.d("Photo link --- " + i,photoLink.get(i));
           }
        }


    }

}
}
yahya
  • 4,810
  • 3
  • 41
  • 58
  • I have done as u suggested and not getting the null pointer exception but now its giving this exception-- java.lang.IllegalArgumentException: HTTP entity may not be null – Nitin Bathija Dec 05 '12 at 06:20
0

AsyncTask class allows to perform background operations.

See AsyncTask

public class MainActivity extends Activity {


    static final String KEY_ITEM    = "photo"; // parent node
    String xml;
    Document    doc;
    NodeList    nl;
    DefaultHttpClient   httpClient;
    HttpPost            httpPost;
    HttpResponse        httpRes;
    HttpEntity          httpEnt;

    String xmlurl       = "http://url.xml";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new FileFromURL().execute(xmlurl);
}

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


class FileFromURL extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... xmlur) {
        // TODO Auto-generated method stub

        try {
            httpClient  =   new DefaultHttpClient();
            httpPost    =   new HttpPost(xmlurl);

            httpRes     =   httpClient.execute(httpPost);
            httpEnt     =   httpRes.getEntity();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        try{
            xml                             =   EntityUtils.toString(httpEnt);

            DocumentBuilderFactory  dbf =   DocumentBuilderFactory.newInstance();
            DocumentBuilder db  = dbf.newDocumentBuilder();
            InputSource     is  = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc                 = db.parse(is);

            ArrayList<String> photoLink = new ArrayList<String>();
            nl  = doc.getElementsByTagName("photo"); /////// line 62
            for(int i=0; i < nl.getLength(); i++){
                Node node = nl.item(i);
                Element fstElmnt = (Element) node;
                photoLink.add(fstElmnt.getAttribute("link"));
            }

            for(int i=0;i<photoLink.size();i++){
                Log.d("Photo link --- " + i,photoLink.get(i));
            }


        }catch (ParserConfigurationException e) {
            Log.e("Error: ", e.getMessage());

        } catch (SAXException e) {
            Log.e("Error: ", e.getMessage());

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        super.onPostExecute(result);
    }

}
}
Seung-hyup Lee
  • 397
  • 2
  • 8
  • I have done as u suggested and not getting the null pointer exception but now its giving this exception-- java.lang.IllegalArgumentException: HTTP entity may not be null – Nitin Bathija Dec 05 '12 at 06:20