无法从主UI * ANDROID *启动listview活动

时间:2012-03-06 06:10:10

标签: android xml listview android-activity

好。我有一个带按钮的主UI。当用户单击其中一个按钮时,它应显示由单独活动创建的列表视图。当我自己运行这个活动时,就像它自己的应用程序一样,它运行得很好,但是当我尝试将它用作更大的应用程序的组件时,它会关闭应用程序。这是我要调用的活动的代码:

table.java

public class Table extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_table);
    ListView lv= (ListView)findViewById(R.id.listview);

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


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

    int numResults = XMLfunctions.numResults(doc);

    if((numResults <= 0)){
        Toast.makeText(Table.this, "Nothing to show.", Toast.LENGTH_LONG).show();  
        finish();
    }

    NodeList nodes = doc.getElementsByTagName("team");

    for (int i = 0; i < nodes.getLength(); i++) {                           
        HashMap<String, String> map = new HashMap<String, String>();    

        Element e = (Element)nodes.item(i);
        map.put("rowid", XMLfunctions.getValue(e, "id"));           
        map.put("name", XMLfunctions.getValue(e, "name"));
        map.put("w",  XMLfunctions.getValue(e, "w"));
        map.put("d",  XMLfunctions.getValue(e, "d"));
        map.put("l",  XMLfunctions.getValue(e, "l"));
        map.put("gd",  XMLfunctions.getValue(e, "gd"));
        map.put("pts", XMLfunctions.getValue(e, "pts"));
        mylist.add(map);            
    }       


    //Make a new listadapter
    ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.grid_item,
                    new String[] { "rowid", "name", "w" , "d", "l", "gd", "pts"},
                    new int[] {R.id.item1, R.id.item2, R.id.item3, R.id.item4, R.id.item5, R.id.item6, R.id.item7 });

       lv.setAdapter(adapter);


}

table.java活动解析此类提取的xml数据:

XMLfunctions.java

public class XMLfunctions {

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;

}

/** Returns element value
  * @param elem element (it is XML tag)
  * @return Element value otherwise empty String
  */
 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://adasoccerclub.org/get_json.php");

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

        } catch (UnsupportedEncodingException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
        } catch (MalformedURLException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
        } catch (IOException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
        }

        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 XMLfunctions.getElementValue(n.item(0));
}

最后,这是调试中的LogCat:

  

03-05 23:43:54.858:E / AndroidRuntime(9190):致命异常:主

     

03-05 23:43:54.858:E / AndroidRuntime(9190):java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.club/com.example.club.Table}:android.os。 NetworkOnMainThreadException

     

03-05 23:43:54.858:E / AndroidRuntime(9190):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):在android.app.ActivityThread.access $ 600(ActivityThread.java:122)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1146)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):在android.os.Handler.dispatchMessage(Handler.java:99)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):在android.os.Looper.loop(Looper.java:137)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):在android.app.ActivityThread.main(ActivityThread.java:4340)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):at java.lang.reflect.Method.invokeNative(Native Method)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):at java.lang.reflect.Method.invoke(Method.java:511)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:784)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):at dalvik.system.NativeStart.main(Native Method)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):引起:android.os.NetworkOnMainThreadException

     

03-05 23:43:54.858:E / AndroidRuntime(9190):在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):at java.net.InetAddress.lookupHostByName(InetAddress.java:391)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):at java.net.InetAddress.getAllByName(InetAddress.java:220)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):at com.example.club.ClubActivity $ XMLfunctions.getXML(ClubActivity.java:205)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):at com.example.club.MainTable.onCreate(Table.java:30)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):在android.app.Activity.performCreate(Activity.java:4465)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)

     

03-05 23:43:54.858:E / AndroidRuntime(9190):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

NetworkOnMainThreadException -

  

应用程序尝试执行时抛出的异常   在其主线程上进行网络操作。

在主UI线程上没有的后台线程上使用网络操作。

答案 1 :(得分:0)

您的应用程序正在尝试在主线程(UI)上进行网络调用,这违反了android规则。

请使用Asynctask或线程进行网络呼叫等长时间运行。

答案 2 :(得分:0)

如果你看到你的logcat,它本身在NetworkOnMainThreadException显示com.example.club.ClubActivity$XMLfunctions.getXML(ClubActivity.java:205)。在getXML中,您正在进行网络操作,这在本质上是繁重的操作。你只能想到它就像你在getXML Activity中调用的onCreate花了这么多时间从服务器加载/获取数据一样,它会停止Activity进入完全可见的状态你肯定会得到着名的ANR(应用程序无响应)对话框。所以为了避免这种情况,android doc建议在后台线程中执行繁重的操作(如网络操作),以便UI在指定的时间内呈现。

因此,在AsyncTask的帮助下,使用Handler或新线程更改逻辑和获取网络数据会更好。