Search code examples
javaandroidmultithreadingandroid-fragmentsbackground-process

Cant run XMLParser as a background thread in fragment


This is my first question, so sorry if I am off topic or something is wrong! I am creating an android application and i am stuck at somewhere.. I have found tutorials and tried something like following. The scenario is that I want to use XMLParser in my application and I am using tabs with swipable views. I want to display the items in a listview inside a tab fragment. I have managed to get them in listview but the problem is that I cant get it to work in background. I have tried creating new thread but that doesn't work! I think the main activity needs the fragmentview to display but it cant return a view because thread is still in progress! I hope you understand my problem.. Can anybody help me? Here is the fragment class and xmlparser class of my application

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

i have tried to extend my class from asynctask and put the http request from inside the doInBackground like below

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

I still get the error like below!

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

please help!


Solution

  • The parser is not responsible for getting something from somewhere, the parser just parses the stuff you feed to him. So create something dedicated like an AsyncTask (runs in background) which gets the stuff for you, then an AsyncTask to parse the stuff. You really should check out AsyncTask. See my example ... (it should work, I didn't actually test it ... :) And you should probably have a look at the Google Volley library, easier HTTP stuff.

    Update :

    I included the fragment, (check the onCreateView, although you should maybe look for a better place than onCreateView to start your task), how the xml handler can be used to get the document and some comments how you can access the document...(again, it should work, I didn't test this and it is only to show you how to do it...)

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