为什么getElementsByTag会抛出NullPointerException?

时间:2013-07-30 14:19:44

标签: java android xml xml-parsing android-sdcard

我正在尝试解析此网址中的xml数据:http://cloud.tfl.gov.uk/TrackerNet/LineStatus但我在行上看到了NullPointerException

NodeList nl = doc.getElementsByTagName(KEY_ITEM);

在我展示代码之前,我想说的是什么。首先,我将XML文件下载到SDCard中

saveToSdCard();

然后我用

检索它
getDataFromSDcard();

这是我的代码: 主要活动:

public class DashboardFragment extends SherlockFragment {
private CardUI mCardView;

String TUBE_STATUS_URL;
String KEY_ITEM = "LineStatus";
String KEY_LINE = "Line";
String KEY_NAME = "name";
String KEY_STATUS_DETAILS = "StatusDetails";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    setHasOptionsMenu(true);

    View rootView = inflater.inflate(R.layout.activity_dashboard,
            container, false);

    // Get the URL's
    TUBE_STATUS_URL = "http://cloud.tfl.gov.uk/TrackerNet/LineStatus";

    // Find the cards in inflated layout
    CardUI cardGroup = (CardUI) rootView.findViewById(R.id.cardsview);
    fillCards(cardGroup);

    DownloadFeedsTask task = new DownloadFeedsTask();
    task.execute(new String[] { "" });

    return rootView;
}

private void fillCards(CardUI cardGroup) {
    // Fill cards with data
    // init CardView
    mCardView = cardGroup;
    mCardView.setSwipeable(true);

    // create a stack
    CardStack delayStack = new CardStack();
    delayStack.setTitle("Tube Lines with delays");

    // add cards to stack
    delayStack.add(new MyCard("Jubilee Line", MyCard.LINE_UNAVAILABLE));
    delayStack.add(new MyCard("Victoria Line", MyCard.LINE_AVAILABLE));
    delayStack
            .add(new MyCard("Piccadilly Line", MyCard.LINE_IN_MAINTENANCE));
    delayStack.add(new MyCard("Northern", MyCard.LINE_AVAILABLE));

    // create a stack
    CardStack activeStack = new CardStack();
    activeStack.setTitle("Active Tube Lines");

    // add cards to stack
    activeStack.add(new MyCard("Jubilee Line", MyCard.LINE_HIDE_STATUS));
    activeStack.add(new MyCard("Victoria Line", MyCard.LINE_HIDE_STATUS));

    // add stack to cardView
    mCardView.addStack(delayStack);
    mCardView.addStack(activeStack);

    // draw cards
    mCardView.refresh();

}

@Override
public boolean onOptionsItemSelected(
        com.actionbarsherlock.view.MenuItem item) {

    return super.onOptionsItemSelected(item);
}

private class DownloadFeedsTask extends AsyncTask<String, Void, String> {
    ArrayList<HashMap<String, String>> menuItems;

    @Override
    protected String doInBackground(String... urls) {
        try {
            saveToSdCard();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        String response = "";

        XMLParser parser = new XMLParser();
        String xml = getDataFromSDcard(); // getting XML
        Document doc = parser.getDomElement(xml); // getting DOM element

        NodeList nl = doc.getElementsByTagName(KEY_ITEM);
        // looping through all item nodes <item>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            map.put(KEY_NAME, e.getAttribute(KEY_NAME));

            // adding HashList to ArrayList
            menuItems.add(map);
        }

        // Adding menuItems to ListView
        // adapter = new SimpleAdapter(
        // mCtx,
        // menuItems,
        // R.layout.list_item,
        // new String[] { KEY_ADVERT, KEY_CONTACT, KEY_DATE },
        // new int[] { R.id.textView1, R.id.textView2, R.id.textView3 });

        return response;
    }

    private String getDataFromSDcard() {
        // Get data from SDCard
        // Find the directory for the SD Card using the API
        // *Don't* hardcode "/sdcard"
        File sdcard = Environment.getExternalStorageDirectory();

        // Get the text file
        File file = new File(sdcard, "Folder/test.xml");

        // Read text from file
        StringBuilder text = new StringBuilder();

        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;

            while ((line = br.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }
        } catch (IOException e) {
            // You'll need to add proper error handling here
        }
        return text.toString();
    }

    private void saveToSdCard() throws IOException {
        try {
            URL url = new URL(TUBE_STATUS_URL);
            URLConnection conexion = url.openConnection();
            conexion.connect();
            int lenghtOfFile = conexion.getContentLength();
            InputStream is = url.openStream();
            File testDirectory = new File(
                    Environment.getExternalStorageDirectory() + "/Folder");
            if (!testDirectory.exists()) {
                testDirectory.mkdir();
            }
            FileOutputStream fos = new FileOutputStream(testDirectory
                    + "/test.xml");
            byte data[] = new byte[1024];
            int count = 0;
            long total = 0;
            int progress = 0;
            while ((count = is.read(data)) != -1) {
                total += count;
                int progress_temp = (int) total * 100 / lenghtOfFile;
                if (progress_temp % 10 == 0 && progress != progress_temp) {
                    progress = progress_temp;
                }
                fos.write(data, 0, count);
            }
            is.close();
            fos.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @Override
    protected void onPostExecute(String result) {
        // Toast.makeText(getActivity(), String.valueOf(menuItems.size()),
        // Toast.LENGTH_LONG).show();
        // Log.d("Commuter+", String.valueOf(menuItems.size()));
    }
}
   }

我的XMLParser类:

public class XMLParser {

public String getXmlFromUrl(String url) {
    String xml = null;

    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

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

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // return XML
    return xml;
}
public Document getDomElement(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) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (SAXException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (IOException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        }

    Log.d("Commuter+", String.valueOf(doc.toString().length()));
            // return DOM
        return doc;
}
public String getValue(Element item, String str) {      
    NodeList n = item.getElementsByTagName(str);        
    return this.getElementValue(n.item(0));
}

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

我尝试通过使用其他具有XML数据的网址测试代码来解决这个问题,但是当我使用此网址时似乎存在问题。

0 个答案:

没有答案