-1

我也是 Android 和 Java 的新手。我来自 PHP。以下代码摘自一本书(Pro Android 4 App Dev - Reto Meier): 这是我遇到问题的 Android 代码:

文件:EarthquakeListFragment.java

public class EarthquakeListFragment extends ListFragment {

    ArrayAdapter<Quake> aa;
    ArrayList<Quake> earthquakes = new ArrayList<Quake>();

    private static final String TAG = "EARTHQUAKE";
    private Handler handler = new Handler();

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        int layoutID = android.R.layout.simple_list_item_1;
        aa = new ArrayAdapter<Quake>(getActivity(), layoutID, earthquakes);
        setListAdapter(aa);

        Thread t = new Thread(new Runnable() {
            public void run() {
                refreshEarthquakes();
            }
        });
        t.start();

    }

    public void refreshEarthquakes() {

        // Get the XML
        URL url;
        try {
            String quakeFeed = getString(R.string.quake_feed);
            url = new URL(quakeFeed);

            URLConnection connection;
            connection = url.openConnection();

            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            int responseCode = httpConnection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {

                InputStream in = httpConnection.getInputStream();

                DocumentBuilderFactory dbf = DocumentBuilderFactory
                        .newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();

                // Parse the earthquake feed
                Document dom = db.parse(in);
                Element docEle = dom.getDocumentElement();

                // clear the old earthquake
                earthquakes.clear();

                // Get a list of each earthquake entry.
                NodeList nl = docEle.getElementsByTagName("entry");
                if (nl != null && nl.getLength() > 0) {

                    for (int i = 0; i < nl.getLength(); i++) {
                        Element entry = (Element) nl.item(i);
                        Element title = (Element) entry.getElementsByTagName(
                                "title").item(0);
                        Element g = (Element) entry.getElementsByTagName(
                                "georss:point").item(0);
                        Element when = (Element) entry.getElementsByTagName(
                                "updated").item(0);
                        Element link = (Element) entry.getElementsByTagName(
                                "link").item(0);

                        String details = title.getFirstChild().getNodeValue();
                        String hostname = "http://earthquake.usgs.gov";
                        String linkString = hostname
                                + link.getAttribute("href");

                        String point = g.getFirstChild().getNodeValue();
                        String dt = when.getFirstChild().getNodeValue();
                        SimpleDateFormat sdf = new SimpleDateFormat(
                                "yyyy-MM-dd'T'hh:mm:ss'Z'");
                        Date qdate = new GregorianCalendar(0, 0, 0).getTime();

                        try {
                            qdate = sdf.parse(dt);
                        } catch (ParseException e) {
                            Log.d(TAG, "Date parsing exception.", e);
                        }

                        String[] location = point.split(" ");
                        Location l = new Location("dummyGPS");
                        l.setLatitude(Double.parseDouble(location[0]));
                        l.setLongitude(Double.parseDouble(location[1]));

                        String magnitudeString = details.split(" ")[1];
                        int end = magnitudeString.length() - 1;
                        double magnitude = Double.parseDouble(magnitudeString
                                .substring(0, end));

                        details = details.split(",")[1].trim();

                        final Quake quake = new Quake(qdate, details, l,
                                magnitude, linkString);

                        // Process a newly found earthquake
                        handler.post(new Runnable() {
                            public void run() {
                                addNewQuake(quake);
                            }
                        });

                    }

                }
            }
        }
        catch (HttpHostConnectException e) {
            Log.d(TAG, "HttpConnection Error.");
        }

        catch (MalformedURLException e) {
            Log.d(TAG, "MalformedURLException");
        } catch (IOException e) {
            Log.d(TAG, "IOException");
        } catch (ParserConfigurationException e) {
            Log.d(TAG, "Parser Config Exception");
        } catch (SAXException e) {
            Log.d(TAG, "SAX Exception");
        } finally {

        }
    }

    private void addNewQuake(Quake _quake) {
        // add the new quake to our list of earthquake
        earthquakes.add(_quake);

        // Notify the array adapter of a change
        aa.notifyDataSetChanged();

    }

}

这是 LogCat 的一部分,其中显示错误:

09-09 20:03:15.689: W/dalvikvm(1095): threadid=11: 线程以未捕获的异常退出 (group=0x40a71930) 09-09 20:03:15.735: E/AndroidRuntime(1095): 致命异常: 线程-111 09-09 20:03:15.735:E/AndroidRuntime(1095):java.lang.NullPointerException 09-09 20:03:15.735:E/AndroidRuntime(1095):在 com.satyaweblog.earthquake.EarthquakeListFragment.refreshEarthquakes( EarthquakeListFragment.java:106) 09-09 20:03:15.735: E/AndroidRuntime(1095): at com.satyaweblog.earthquake.EarthquakeListFragment$1.run(EarthquakeListFragment.java:50) 09-09 20:03:15.735: E /AndroidRuntime(1095): at java.lang.Thread.run(Thread.java:856) 09-09 20:03:20.015: I/Process(1095): 发送信号。PID:1095 SIG:9

因此,在一处,代码行是:

String point = g.getFirstChild().getNodeValue();

在 PHP 中,我会这样检查: var_dump(g); 如何在 Android + Java 中查看这里?

我认为,第二个错误将是由于第一个错误!

4

2 回答 2

1

在有问题的行

String point = g.getFirstChild().getNodeValue();

这是可能gnull

 Element g = (Element) entry.getElementsByTagName(
                            "georss:point").item(0);

作为NodeList#item(int)

返回集合中的索引项。如果 index 大于或等于列表中的节点数,则返回 null。

也有可能Node#getFirstChild()返回null。它的 javadoc 状态

此节点的第一个子节点。如果没有这样的节点,则返回 null。

查看您检索的 XML。可能没有子节点。

于 2013-09-09T20:23:29.113 回答
0

for (int i = 0; i < nl.getLength(); i++)将代码更改为for (int i = 1; i < nl.getLength(); i++)

当链接上的 xml 代码已过期时,它将起作用。因此,对于第 0 个索引,它会收到已弃用的消息。

for 开始 for 循环 fromi = 1而不是i = 0

于 2014-06-03T18:55:49.513 回答