0

我不知道为什么会发生强制关闭错误。

我想在我的 XML 布局中显示代码。但是,会发生强制关闭错误。我不确定它有什么问题。

这是我的 logcat 错误。

07-27 15:44:51.030: E/AndroidRuntime(6171): FATAL EXCEPTION: main
07-27 15:44:51.030: E/AndroidRuntime(6171): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fambond/com.example.fambond.MainActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
07-27 15:44:51.030: E/AndroidRuntime(6171):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
07-27 15:44:51.030: E/AndroidRuntime(6171):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
07-27 15:44:51.030: E/AndroidRuntime(6171):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
07-27 15:44:51.030: E/AndroidRuntime(6171):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
07-27 15:44:51.030: E/AndroidRuntime(6171):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-27 15:44:51.030: E/AndroidRuntime(6171):     at android.os.Looper.loop(Looper.java:130)
07-27 15:44:51.030: E/AndroidRuntime(6171):     at android.app.ActivityThread.main(ActivityThread.java:3691)
07-27 15:44:51.030: E/AndroidRuntime(6171):     at java.lang.reflect.Method.invokeNative(Native Method)
07-27 15:44:51.030: E/AndroidRuntime(6171):     at java.lang.reflect.Method.invoke(Method.java:507)
07-27 15:44:51.030: E/AndroidRuntime(6171):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
07-27 15:44:51.030: E/AndroidRuntime(6171):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:670)
07-27 15:44:51.030: E/AndroidRuntime(6171):     at dalvik.system.NativeStart.main(Native Method)
07-27 15:44:51.030: E/AndroidRuntime(6171): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
07-27 15:44:51.030: E/AndroidRuntime(6171):     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
07-27 15:44:51.030: E/AndroidRuntime(6171):     at java.util.ArrayList.get(ArrayList.java:311)
07-27 15:44:51.030: E/AndroidRuntime(6171):     at com.example.fambond.MainActivity.onCreate(MainActivity.java:144)
07-27 15:44:51.030: E/AndroidRuntime(6171):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050)
07-27 15:44:51.030: E/AndroidRuntime(6171):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)

MainActivity.java

public class MainActivity extends Activity {
    ArrayList<String> psi;

      public TextView psi_text;

    TextView weather;
     ImageView image;
     private static Handler mHandler = new Handler();
     class MyWeather{


      String conditiontext;
      String conditiontemp;
      String conditiondate;



      public String forecastToString(){

       return 
         conditiontext + "\n" + "        "  + conditiontemp + "°C"  ;

      } 
     }

     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            weather = (TextView)findViewById(R.id.weather);
            image = (ImageView)findViewById(R.id.image);
            psi = new ArrayList<String>();  


            psi_text = (TextView) findViewById(R.id.psi_text);

            try {

                URL url = new URL(
                        "http://app2.nea.gov.sg/data/rss/nea_psi.xml");
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = db.parse(new InputSource(url.openStream()));
                doc.getDocumentElement().normalize();

                NodeList nodeList = doc.getElementsByTagName("item");
                for (int i = 0; i < nodeList.getLength(); i++) {

                    Node node = nodeList.item(i);       

                    Element fstElmnt = (Element) node;                 

                    NodeList websiteList = fstElmnt.getElementsByTagName("psi");
                    Element websiteElement = (Element) websiteList.item(0);
                    websiteList = websiteElement.getChildNodes();

                    psi.add(""+ ((Node) websiteList.item(0)).getNodeValue());           

                }
            } catch (Exception e) {
                System.out.println("XML Pasing Excpetion = " + e);
            }



            String temp = Html.fromHtml(psi.get(0)).toString(); 
            String a[] = temp.split("\\)");
            psi_text.setText(""+a[0]+")");


            Thread myThread = new Thread(new Runnable(){

                 @Override
                   public void run() {
                    String weatherString = QueryYahooWeather();
                          Document weatherDoc = convertStringToDocument(weatherString);

                          final MyWeather weatherResult = parseWeather(weatherDoc);
                          runOnUiThread(new Runnable(){

                              @Override
                                 public void run() {
                                  weather.setText(weatherResult.forecastToString());
                                 }});

                               }});
                                    myThread.start();
                                }

     private MyWeather parseWeather(Document srcDoc){

         MyWeather myWeather = new MyWeather();

            //<yweather:condition.../>
         Node conditionNode = srcDoc.getElementsByTagName("yweather:condition").item(0);


         String weatherCode = conditionNode.getAttributes()
               .getNamedItem("code")
               .getNodeValue()
               .toString();

         // thunderstorms
         if(weatherCode.equals("4")){

             mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // This gets executed on the UI thread so it can safely modify
                    // Views

                     image.setImageResource(R.drawable.thunderstorm);
                }
            });
         }

         //isolated thunderstorms
         else if ( weatherCode.equals("37")) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {

                            image.setImageResource(R.drawable.thunderstorm);
                        }
                    });
                }


         //scattered thunderstorms
         else if ( weatherCode.equals("38")) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {

                            image.setImageResource(R.drawable.thunderstorm);
                        }
                    });
                }

         //scattered thunderstorms
         else if ( weatherCode.equals("39")) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {

                            image.setImageResource(R.drawable.thunderstorm);
                        }
                    });
                }

         //thundershowers
         else if ( weatherCode.equals("45")) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {

                            image.setImageResource(R.drawable.thunderstorm);
                        }
                    });
                }

         //isolated thundershowers
         else if ( weatherCode.equals("47")) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {

                            image.setImageResource(R.drawable.thunderstorm);
                        }
                    });
                }

         //drizzle
         else if ( weatherCode.equals("9")) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {

                            image.setImageResource(R.drawable.rainy);
                        }
                    });
                }

         //showers
         else if ( weatherCode.equals("11")) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {

                            image.setImageResource(R.drawable.rainy);
                        }
                    });
                }

 //showers
else if ( weatherCode.equals("12")) {
    mHandler.post(new Runnable() {
        @Override
        public void run() {

            image.setImageResource(R.drawable.rainy);
        }
    });
}

         //scattered showers
else if ( weatherCode.equals("40")) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {

                image.setImageResource(R.drawable.rainy);
            }
        });
    }

         //hail
else if ( weatherCode.equals("17")) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {

                image.setImageResource(R.drawable.hail);
            }
        });
    }


         //mixed rain and hail
else if ( weatherCode.equals("35")) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {

                image.setImageResource(R.drawable.hail);
            }
        });
    }

         //foggy
else if ( weatherCode.equals("20")) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {

                image.setImageResource(R.drawable.foggy);
            }
        });
    }

         //haze
else if ( weatherCode.equals("21")) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {

                image.setImageResource(R.drawable.foggy);
            }
        });
    }

         //smoky
else if ( weatherCode.equals("22")) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {

                image.setImageResource(R.drawable.foggy);
            }
        });
    }

         //windy
else if ( weatherCode.equals("24")) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {

                image.setImageResource(R.drawable.windy);
            }
        });
    }

         //cloudy
else if ( weatherCode.equals("26")) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {

                image.setImageResource(R.drawable.cloudy);
            }
        });
    }

         //fair (night)
else if ( weatherCode.equals("33")) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {

                image.setImageResource(R.drawable.cloudy);
            }
        });
    }

         //fair (day)
else if ( weatherCode.equals("34")) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {

                image.setImageResource(R.drawable.cloudy);
            }
        });
    }

         //partly cloudy
else if ( weatherCode.equals("44")) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {

                image.setImageResource(R.drawable.cloudy);
            }
        });
    }

         //mostly cloudy (night)
else if ( weatherCode.equals("27")) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {

                image.setImageResource(R.drawable.night_cloudy);
            }
        });
    }

         //partly cloudy (night)
else if ( weatherCode.equals("29")) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {

                image.setImageResource(R.drawable.night_cloudy);
            }
        });
    }

         //mostly cloudy (day)
else if ( weatherCode.equals("28")) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {

                image.setImageResource(R.drawable.day_cloudy);
            }
        });
    }


         //partly cloudy (day)
    else if ( weatherCode.equals("30")) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {

                    image.setImageResource(R.drawable.day_cloudy);
                }
            });
        }




         //clear(night)
    else if ( weatherCode.equals("31")) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {

                    image.setImageResource(R.drawable.moon);
                }
            });
        }


         //sunny
    else {
            mHandler.post(new Runnable() {
                @Override
                public void run() {

                    image.setImageResource(R.drawable.sunny);
                }
            });
        }




         myWeather.conditiontext = conditionNode.getAttributes()
       .getNamedItem("text")
       .getNodeValue()
       .toString();

         myWeather.conditiontemp = conditionNode.getAttributes()
                   .getNamedItem("temp")
                   .getNodeValue()
                   .toString();




     return myWeather; 
    }

    private Document convertStringToDocument(String src){

     Document dest = null;
     DocumentBuilderFactory dbFactory =
       DocumentBuilderFactory.newInstance();
     DocumentBuilder parser;

     try {
      parser = dbFactory.newDocumentBuilder();
      dest = parser.parse(new ByteArrayInputStream(src.getBytes())); 
     } catch (ParserConfigurationException e1) {
      e1.printStackTrace();
      Toast.makeText(MainActivity.this,
        e1.toString(), Toast.LENGTH_LONG).show(); 
     } catch (SAXException e) {
      e.printStackTrace();
      Toast.makeText(MainActivity.this,
        e.toString(), Toast.LENGTH_LONG).show(); 
     } catch (IOException e) {
      e.printStackTrace();
      Toast.makeText(MainActivity.this,
        e.toString(), Toast.LENGTH_LONG).show(); 
     }

     return dest; 
    }

    private String QueryYahooWeather(){

     String qResult = "";
     String queryString = "http://weather.yahooapis.com/forecastrss?w=1062617&u=c";

     HttpClient httpClient = new DefaultHttpClient();
     HttpGet httpGet = new HttpGet(queryString);

     try {
      HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();

      if (httpEntity != null){
       InputStream inputStream = httpEntity.getContent();
       Reader in = new InputStreamReader(inputStream);
       BufferedReader bufferedreader = new BufferedReader(in);
       StringBuilder stringBuilder = new StringBuilder();

       String stringReadLine = null;

       while ((stringReadLine = bufferedreader.readLine()) != null) {
        stringBuilder.append(stringReadLine + "\n"); 
       }

       qResult = stringBuilder.toString(); 
      } 
     } catch (ClientProtocolException e) {
      e.printStackTrace();
      Toast.makeText(MainActivity.this,
        e.toString(), Toast.LENGTH_LONG).show(); 
     } catch (IOException e) {
      e.printStackTrace();
      Toast.makeText(MainActivity.this,
        e.toString(), Toast.LENGTH_LONG).show(); 
     }

     return qResult; 
    }



}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/checkBox6"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:text="Recommended" />

    <CheckBox
        android:id="@+id/checkBox6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/checkBox3"
        android:layout_alignBottom="@+id/checkBox3"
        android:layout_alignParentRight="true"
        android:text="Neighbourhood" />

    <CheckBox
        android:id="@+id/checkBox4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/checkBox1"
        android:layout_alignBottom="@+id/checkBox1"
        android:layout_alignLeft="@+id/checkBox5"
        android:text="Museum" />

    <CheckBox
        android:id="@+id/checkBox3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button1"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="54dp"
        android:text="Sports" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="182dp"
        android:layout_height="wrap_content"
        android:layout_above="@+id/checkBox4"
        android:layout_alignLeft="@+id/checkBox1"
        android:layout_marginBottom="22dp"
        android:ems="10" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="78dp"
        android:layout_height="wrap_content"
        android:layout_above="@+id/editText1"
        android:layout_alignLeft="@+id/editText1"
        android:text="Location:" />

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/checkBox2"
        android:layout_alignLeft="@+id/checkBox2"
        android:layout_marginBottom="20dp"
        android:text="Education" />

    <CheckBox
        android:id="@+id/checkBox2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/checkBox3"
        android:layout_alignLeft="@+id/checkBox3"
        android:layout_marginBottom="18dp"
        android:text="Festival" />

    <CheckBox
        android:id="@+id/checkBox5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/checkBox6"
        android:layout_below="@+id/checkBox1"
        android:text="Performing Arts" />

    <Button
        android:id="@+id/button2"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button1"
        android:layout_alignLeft="@+id/checkBox3"
        android:layout_alignRight="@+id/imageView1"
        android:text="By Month" />


    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView4"
        android:layout_alignLeft="@+id/textView1"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/checkBox1"
        android:layout_marginRight="16dp"
        android:src="@drawable/logo" />

  <ImageView
        android:id="@+id/image"
        android:layout_width="60dp"
        android:layout_height="60dp"
              android:layout_alignParentRight="true"
              android:layout_above="@+id/weather"
               android:layout_marginLeft="235dp"              
              />

        <TextView
            android:id="@+id/weather"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/imageView1"
            android:layout_alignRight="@+id/checkBox5"
            android:layout_marginLeft="29dp"
            android:layout_toRightOf="@+id/editText1"
            android:textColor="#000000" />

        <TextView
            android:id="@+id/psi_text"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignRight="@+id/weather"
            android:layout_marginLeft="26dp"
            android:layout_toRightOf="@+id/editText1"
            android:textColor="#000000" />

</RelativeLayout>
4

4 回答 4

0

java.lang.IndexOutOfBoundsException:索引 0 无效,大小为 0

这是数组边界,并且在您的代码下进行了很好的检查。

于 2013-07-27T08:07:10.643 回答
0

我认为它在这里崩溃了

String temp = Html.fromHtml(psi.get(0)).toString();

您需要确保以下for循环正确执行

for (int i = 0; i < nodeList.getLength(); i++) {
    Node node = nodeList.item(i);       
    Element fstElmnt = (Element) node;                 

    NodeList websiteList = fstElmnt.getElementsByTagName("psi");
    Element websiteElement = (Element) websiteList.item(0);
    websiteList = websiteElement.getChildNodes();

    psi.add(""+ ((Node) websiteList.item(0)).getNodeValue());           
}

如果此for循环甚至没有执行一次,那么您psi的数组将具有 0 大小,因此您无法访问0th index您尝试执行的操作。

于 2013-07-27T07:57:24.853 回答
0

Logcat 告诉我们:

Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

您的数组列表 psi 不包含任何项目,您正试图从中获取项目。因此强制关闭。

此行导致问题: String temp = Html.fromHtml(psi.get(0)).toString();

确保在尝试获取数据之前,检查其大小是否大于 0。

于 2013-07-27T07:55:17.640 回答
0

在 Android 清单中添加 Internet 权限。

于 2013-07-28T07:03:13.343 回答