无法将XMLParser作为片段中的后台线程运行

时间:2014-04-06 14:20:14

标签: java android multithreading android-fragments background-process

这是我的第一个问题,很抱歉,如果我不在话题或出错了! 我正在创建一个Android应用程序,我被困在某个地方.. 我找到了教程并尝试了类似的内容。 方案是我想在我的应用程序中使用XMLParser,并且我使用带有可跳转视图的选项卡。我想在选项卡片段中的列表视图中显示项目。 我已经设法将它们放在listview中,但问题是我无法让它在后台工作。我试过创建新线程,但这不起作用! 我认为主要活动需要显示fragmentview但它无法返回视图,因为线程仍在进行中!我希望你理解我的问题.. 有谁能够帮我? 这是我的应用程序的片段类和xmlparser类

gamesfragment.java

public class GamesFragment extends Fragment {
// All static variables
public static final String URL = "http://api.androidhive.info/pizza/?format=xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";

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

    View rootView = inflater.inflate(R.layout.fragment_games, container, false);
    setRetainInstance(true);
    ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

    XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromUrl(URL); // 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_ID, parser.getValue(e, KEY_ID));
        map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
        map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
        map.put(KEY_DESC, parser.getValue(e, KEY_DESC));

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

    // Adding menuItems to ListView
    ListAdapter adapter = new SimpleAdapter(getActivity(), menuItems,R.layout.list_item,
            new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
                    R.id.name, R.id.desciption, R.id.cost });
    final ListView lview = (ListView) rootView.findViewById(R.id.lview);
    lview.setAdapter(adapter);

    // selecting single ListView item
    //ListView lv = getListView();

    lview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
            String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
            String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();

            // Starting new intent
            Intent in = new Intent(getActivity().getApplicationContext(), SingleMenuItemActivity.class);
            in.putExtra(KEY_NAME, name);
            in.putExtra(KEY_COST, cost);
            in.putExtra(KEY_DESC, description);
            startActivity(in);

        }
    });
    return rootView;
}
}
//xmlparser.java


public class XMLParser {

// constructor
public XMLParser() {

}

/**
 * Getting XML from URL making HTTP request
 * @param url string
 * */
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;
}

/**
 * Getting XML DOM element
 * @param XML string
 * */
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;
        }

        return doc;
}

/** Getting node value
  * @param elem element
  */
 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 "";
 }

 /**
  * Getting node value
  * @param Element node
  * @param key string
  * */
 public String getValue(Element item, String str) {     
        NodeList n = item.getElementsByTagName(str);        
        return this.getElementValue(n.item(0));
    }
}

我试图从asynctask扩展我的类并将do请求放在doInBackground中,如下所示

public class GamesFragment extends Fragment {

    // All static variables
    public static final String URL = "http://api.androidhive.info/pizza/?format=xml";
    // XML node keys
    static final String KEY_ITEM = "item"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_NAME = "name";
    static final String KEY_COST = "cost";
    static final String KEY_DESC = "description";

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

        View rootView = inflater.inflate(R.layout.fragment_games, container, false);
        setRetainInstance(true);
        ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

        GetStuffFromUrlTask parser1 = new GetStuffFromUrlTask();

    //  XMLParser parser = new XMLParser();
        String xml = parser1.doInBackground(URL); // getting XML
        Document doc = parser1.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_ID, parser1.getValue(e, KEY_ID));
            map.put(KEY_NAME, parser1.getValue(e, KEY_NAME));
            map.put(KEY_COST, "Rs." + parser1.getValue(e, KEY_COST));
            map.put(KEY_DESC, parser1.getValue(e, KEY_DESC));

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

        // Adding menuItems to ListView
        ListAdapter adapter = new SimpleAdapter(getActivity(), menuItems,R.layout.list_item,
                new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
                        R.id.name, R.id.desciption, R.id.cost });
        final ListView lview = (ListView) rootView.findViewById(R.id.lview);
        lview.setAdapter(adapter);

        // selecting single ListView item
        //ListView lv = getListView();

        lview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
                String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
                String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();

                // Starting new intent
                Intent in = new Intent(getActivity().getApplicationContext(), SingleMenuItemActivity.class);
                in.putExtra(KEY_NAME, name);
                in.putExtra(KEY_COST, cost);
                in.putExtra(KEY_DESC, description);
                startActivity(in);

            }
        });
        return rootView;
    }

private static class GetStuffFromUrlTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        String url = params[0];
        String xml = "";
        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;
    }
    /**
     * Getting XML DOM element
     * @param XML string
     * */
    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;
            }

            return doc;
    }

    /** Getting node value
      * @param elem element
      */
     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 "";
     }

     /**
      * Getting node value
      * @param Element node
      * @param key string
      * */
     public String getValue(Element item, String str) {     
            NodeList n = item.getElementsByTagName(str);        
            return this.getElementValue(n.item(0));
        }
}

private static class ParseStuffIGotFromSomeWhereTask extends AsyncTask<String, Void, Boolean> {

    @Override
    protected Boolean doInBackground(String... params) {

        String stringToParse = params[0];
        boolean result = new XMLParser().parse(stringToParse);

        return result;
    }

}

private static class XMLParser {

    public boolean parse(String string) {
        return true;
    }

}

public GamesFragment() {

    new GetStuffFromUrlTask() {

        @Override
        public void onPostExecute(String resultIGotFromTheTask) {

            new ParseStuffIGotFromSomeWhereTask() {

                @Override
                public void onPostExecute(Boolean resultOfTheParseTask) {

                    Log.i("Parse successful?", resultOfTheParseTask.toString());

                }

            }.execute(resultIGotFromTheTask);


        }

    }.execute(URL);

}

/**
 * Getting XML DOM element
 * @param XML string
 * */
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;
        }

        return doc;
}

/** Getting node value
  * @param elem element
  */
 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 "";
 }

 /**
  * Getting node value
  * @param Element node
  * @param key string
  * */
 public String getValue(Element item, String str) {     
        NodeList n = item.getElementsByTagName(str);        
        return this.getElementValue(n.item(0));
    }
}    

我仍然得到如下错误!

04-07 18:23:37.234: E/AndroidRuntime(19673): FATAL EXCEPTION: main
04-07 18:23:37.234: E/AndroidRuntime(19673): android.os.NetworkOnMainThreadException
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at java.net.InetAddress.lookupHostByName(InetAddress.java:414)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:249)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at java.net.InetAddress.getAllByName(InetAddress.java:227)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at com.android.mygit.GamesFragment$GetStuffFromUrlTask.doInBackground(GamesFragment.java:125)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at com.android.mygit.GamesFragment.onCreateView(GamesFragment.java:63)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1478)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.View.measure(View.java:15349)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4950)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:315)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.View.measure(View.java:15349)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.widget.LinearLayout.measureVertical(LinearLayout.java:850)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:579)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.View.measure(View.java:15349)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4950)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:315)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2152)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.View.measure(View.java:15349)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1851)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1101)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1274)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:999)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4217)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.Choreographer.doCallbacks(Choreographer.java:555)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.Choreographer.doFrame(Choreographer.java:525)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.os.Handler.handleCallback(Handler.java:615)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.os.Looper.loop(Looper.java:137)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.app.ActivityThread.main(ActivityThread.java:4802)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at java.lang.reflect.Method.invokeNative(Native Method)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at java.lang.reflect.Method.invoke(Method.java:511)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:813)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:580)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:115)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at dalvik.system.NativeStart.main(Native Method)
04-07 18:23:37.234: E/AndroidRuntime(19673): FATAL EXCEPTION: main
04-07 18:23:37.234: E/AndroidRuntime(19673): android.os.NetworkOnMainThreadException
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at java.net.InetAddress.lookupHostByName(InetAddress.java:414)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:249)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at java.net.InetAddress.getAllByName(InetAddress.java:227)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at com.android.mygit.GamesFragment$GetStuffFromUrlTask.doInBackground(GamesFragment.java:125)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at com.android.mygit.GamesFragment.onCreateView(GamesFragment.java:63)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1478)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.View.measure(View.java:15349)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4950)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:315)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.View.measure(View.java:15349)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.widget.LinearLayout.measureVertical(LinearLayout.java:850)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:579)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.View.measure(View.java:15349)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4950)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:315)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2152)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.View.measure(View.java:15349)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1851)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1101)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1274)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:999)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4217)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.Choreographer.doCallbacks(Choreographer.java:555)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.Choreographer.doFrame(Choreographer.java:525)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.os.Handler.handleCallback(Handler.java:615)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.os.Looper.loop(Looper.java:137)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at android.app.ActivityThread.main(ActivityThread.java:4802)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at java.lang.reflect.Method.invokeNative(Native Method)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at java.lang.reflect.Method.invoke(Method.java:511)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:813)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:580)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:115)
04-07 18:23:37.234: E/AndroidRuntime(19673):    at dalvik.system.NativeStart.main(Native Method)
04-07 18:23:38.114: D/-heap(19673): GC_CONCURRENT freed 306K, 8% free 10130K/10951K, paused 17ms+2ms, total 64ms

请帮忙!

1 个答案:

答案 0 :(得分:0)

解析器不负责从某处获取某些内容,解析器只会解析您提供给他的内容。因此,创建一些专门的东西,如AsyncTask(在后台运行),为您获取的东西,然后是AsyncTask来解析东西。你真的应该看看AsyncTask。看看我的例子......(它应该工作,我实际上没有测试它...... :) 你可能应该看一下Google Volley库,更简单的HTTP内容。

更新:

我包含了片段,(检查onCreateView,虽然您应该寻找比onCreateView更好的地方来启动任务),如何使用xml处理程序获取文档以及如何访问文档的一些注释...(再次,它应该工作,我没有测试这个,它只是告诉你如何做到这一点......)

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class GameFragment extends Fragment {

// All static variables
public static final String URL = "http://api.androidhive.info/pizza/?format=xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";

private static class GetStuffFromUrlTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        String url = params[0];
        String xml = "";
        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;
    }

}

private static class ParseStuffIGotFromSomeWhereTask extends AsyncTask<String, Void, Document> {

    @Override
    protected Document doInBackground(String... params) {

        String stringToParse = params[0];
        Document document = new XMLParser().getDomElement(stringToParse);

        return document;
    }

}

private static class XMLParser {

    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;
        }

        return doc;
    }

}

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

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

    //This is the task we use to parse the XML we got back from the getStuffFromUrlTask
    final ParseStuffIGotFromSomeWhereTask parseTask = new ParseStuffIGotFromSomeWhereTask() {

        @Override
        public void onPostExecute(Document document) {
            // here you can access the document that is the result of our parse operation

            //document.getElementsByTagName(XYZ)...

        }

    };

    //This is the task we use to get stuff from the URL
    GetStuffFromUrlTask getStuffFromUrlTask = new GetStuffFromUrlTask() {

        @Override
        public void onPostExecute(String result) {
            //The task has completed, the string result contains the XML data we got from the URL
            parseTask.execute(result); //Now we start the task to parse the xml
        }

    };

    getStuffFromUrlTask.execute(URL);

    return rootView;
}

}