android 1.6代码在2.3.3上给出了nullpointer

时间:2012-05-05 21:00:55

标签: android

您好我正在编写一个Android应用程序。 我找到了一个用于xml解析的代码片段。我在另一个项目上测试了它,一切正常。所以我想让我们在我的主项目上测试它,但它给了我一个nullpointer:S。

这是我的ParseXMLDemo类:

public class ParseXMLDemo extends ListActivity {

@SuppressWarnings("rawtypes")
private ArrayList vraag;
@SuppressWarnings("rawtypes")
private ArrayList a1;
private ArrayList p1;
private ArrayList a2;
private ArrayList p2;
private ArrayList a3;
private ArrayList p3;

@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

    String xml = ParseXMLMethods.getXML();
    Document doc = ParseXMLMethods.XMLfromString(xml);

    int numResults = ParseXMLMethods.numResults(doc);

    if((numResults <= 0)){
        Toast.makeText(ParseXMLDemo.this, "Er is een fout opgetreden bij het updaten van de vragen. Probeert u het later opnieuw.", Toast.LENGTH_LONG).show();  
        finish();
    }

    NodeList children = doc.getElementsByTagName("os");

    for (int i = 0; i < children.getLength(); i++) {

        HashMap<String, String> map = new HashMap<String, String>();    
        Element e = (Element)children.item(i);
        vraag.add(ParseXMLMethods.getValue(e, "vraag"));
        a1.add(ParseXMLMethods.getValue(e, "a1"));
        p1.add(ParseXMLMethods.getValue(e, "p1"));
        a2.add(ParseXMLMethods.getValue(e, "a2"));
        p2.add(ParseXMLMethods.getValue(e, "p2"));
        a3.add(ParseXMLMethods.getValue(e, "a3"));
        p3.add(ParseXMLMethods.getValue(e, "p3"));
        Toast.makeText(ParseXMLDemo.this, (CharSequence) vraag.get(i)+" "+a1.get(i)+" "+p1.get(i)+" "+a2.get(i)+" "+p2.get(i)+" "+a3.get(i)+" "+p3.get(i), Toast.LENGTH_LONG).show();

        map.put("id", ParseXMLMethods.getValue(e, "id"));
        map.put("vraag", ParseXMLMethods.getValue(e, "vraag"));
        map.put("a1", ParseXMLMethods.getValue(e, "a1"));
        map.put("p1", ParseXMLMethods.getValue(e, "p2"));
        map.put("a2", ParseXMLMethods.getValue(e, "a2"));
        map.put("p2", ParseXMLMethods.getValue(e, "p2"));
        map.put("a3", ParseXMLMethods.getValue(e, "a3"));
        map.put("p3", ParseXMLMethods.getValue(e, "p3"));

        mylist.add(map);            
    }       

    Toast.makeText(ParseXMLDemo.this, "testje"+mylist.get(1), Toast.LENGTH_LONG).show();

   ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.list_layout, 
                  new String[] { "vraag", "a1", "p1", "a2", "p2", "a3", "p3" }, 
                    new int[] { R.id.title, R.id.subtitle, R.id.sub1, R.id.sub11, R.id.sub2, R.id.sub22, R.id.sub3});

    setListAdapter(adapter);

    final ListView lv = getListView();
    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
            @SuppressWarnings("unchecked")
            HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
            Toast.makeText(ParseXMLDemo.this,o.get("vraag"), Toast.LENGTH_LONG).show(); 
        }
    });
}}

这是我的ParseXMLMethods类:

public class ParseXMLMethods {

public final static Document XMLfromString(String xml){

    Document doc = null;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));
        doc = db.parse(is); 

    } catch (ParserConfigurationException e) {
        System.out.println("XML parse error: " + e.getMessage());
        return null;
    } catch (SAXException e) {
        System.out.println("Wrong XML file structure: " + e.getMessage());
        return null;
    } catch (IOException e) {
        System.out.println("I/O exeption: " + e.getMessage());
        return null;
    }
    return doc;
}

 public final static String getElementValue( Node elem ) {
     Node kid;
     if( elem != null){
         if (elem.hasChildNodes()){
             for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                 if( kid.getNodeType() == Node.TEXT_NODE  ){
                     return kid.getNodeValue();
                 }
             }
         }
     }
     return "";
 }

 public static String getXML(){  
        String line = null;

        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://www.oudersvragen.nl/test.xml");

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            line = EntityUtils.toString(httpEntity);

        } catch (Exception e) {
            line = "Internet Connection Error >> " + e.getMessage();
        } 
        return line;
}

public static int numResults(Document doc){     
    Node results = doc.getDocumentElement();
    int res = -1;
    try{
        res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
    }catch(Exception e ){
        res = -1;
    }
    return res;
}

public static String getValue(Element item, String str) {       
    NodeList n = item.getElementsByTagName(str);        
    return ParseXMLMethods.getElementValue(n.item(0));
}

}

有人可以告诉我为什么它在android 2.3.3项目中给了我一个nullpointer异常,为什么一切都按照它在Android 1.6项目上的假设? (仅供参考。我在同一个android 4.0 vm上运行该项目)

Logcat输出:

05-05 20:50:33.561: E/AndroidRuntime(3705): FATAL EXCEPTION: main 
05-05 20:50:33.561: E/AndroidRuntime(3705): java.lang.RuntimeException: Unable to start     activity ComponentInfo{com.hgs.database/com.hgs.database.ParseXMLDemo}:     java.lang.NullPointerException
05-05 20:50:33.561: E/AndroidRuntime(3705):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
05-05 20:50:33.561: E/AndroidRuntime(3705):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
05-05 20:50:33.561: E/AndroidRuntime(3705):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
05-05 20:50:33.561: E/AndroidRuntime(3705):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
05-05 20:50:33.561: E/AndroidRuntime(3705):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-05 20:50:33.561: E/AndroidRuntime(3705):     at android.os.Looper.loop(Looper.java:137)
05-05 20:50:33.561: E/AndroidRuntime(3705):     at    android.app.ActivityThread.main(ActivityThread.java:4424) 
05-05 20:50:33.561: E/AndroidRuntime(3705):     at java.lang.reflect.Method.invokeNative(Native Method)
05-05 20:50:33.561: E/AndroidRuntime(3705):     at java.lang.reflect.Method.invoke(Method.java:511)
05-05 20:50:33.561: E/AndroidRuntime(3705):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-05 20:50:33.561: E/AndroidRuntime(3705):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-05 20:50:33.561: E/AndroidRuntime(3705):     at dalvik.system.NativeStart.main(Native Method)
05-05 20:50:33.561: E/AndroidRuntime(3705): Caused by: java.lang.NullPointerException
05-05 20:50:33.561: E/AndroidRuntime(3705):     at com.hgs.database.ParseXMLDemo.onCreate(ParseXMLDemo.java:57)
05-05 20:50:33.561: E/AndroidRuntime(3705):     at android.app.Activity.performCreate(Activity.java:4465)
05-05 20:50:33.561: E/AndroidRuntime(3705):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
05-05 20:50:33.561: E/AndroidRuntime(3705):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)

1 个答案:

答案 0 :(得分:0)

我刚刚意识到你提出了一个完整的程序(不包括布局),所以我运行了它。这是我发现的:

当我忘记包含互联网权限时,我发现调用finish()不会退出onCreate()。所以我添加了一个返回命令:

if(numResults <= 0){
    Toast.makeText(Example.this, "Er is een fout opgetreden bij het updaten van de vragen. Probeert u het later opnieuw.", Toast.LENGTH_LONG).show();  
    finish();
    return;
}

在包含互联网权限后,我注意到你没有初始化你的数组,所以:

@SuppressWarnings("rawtypes")
private ArrayList vraag = new ArrayList();
@SuppressWarnings("rawtypes")
private ArrayList a1 = new ArrayList();
private ArrayList p1 = new ArrayList();
private ArrayList a2 = new ArrayList();
private ArrayList p2 = new ArrayList();
private ArrayList a3 = new ArrayList();
private ArrayList p3 = new ArrayList();

它现在在我的2.3.3模拟器上运行。