片段内的异步任务在打开片段之前开始执行

时间:2014-04-09 09:50:23

标签: android android-fragments android-asynctask

我正在创建一个带有片段和可转换视图标签的应用... 我有xml解析器片段,它在后台的asynctask中工作。 问题是,当我打开另一个片段而不是xml解析器片段时,它会启动asynctask并显示progressbar对话框,让用户等待任务完成!我怎么做它只会在我去那个xmlparser片段时启动异步任务?有人可以帮忙吗?

我的代码:

public class CircularsFragment extends Fragment {
    // All static variables

    public static final String URL = "https://dl.dropboxusercontent.com/7978967896/something.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";
    ProgressDialog dialog;
      // flag for Internet connection status
    Boolean isInternetPresent = false;

    // Connection detector class
    ConnectionDetector cd;
    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;
        }
         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, 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) {

        final View rootView = inflater.inflate(R.layout.fragment_games, container, false);
        setRetainInstance(true);

        //check internet
        cd = new ConnectionDetector(getActivity().getApplicationContext());
        isInternetPresent = cd.isConnectingToInternet();
        //This is the task we use to parse the XML we got back from the getStuffFromUrlTask
        //do only if internet is present

        if (isInternetPresent) {
        final ParseStuffIGotFromSomeWhereTask parseTask = new ParseStuffIGotFromSomeWhereTask() {
            @Override
            protected void onPreExecute(){ 

                   }
            @Override
            public void onPostExecute(Document document) {
                // here you can access the document that is the result of our parse operation
                //  progressDialog.dismiss();
                //document.getElementsByTagName(XYZ)...
                  ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

                NodeList nl = document.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);
                    GetStuffFromUrlTask parser1 = new GetStuffFromUrlTask();
                    // 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);

                    }
                });
            }

        };

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

            protected void onPreExecute(){ 
                 dialog=ProgressDialog.show(getActivity(), "", "Loading...Please wait!");

                }
            @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
                dialog.dismiss();
            }

        };

        getStuffFromUrlTask.execute(URL);
        }
        else{
            Toast.makeText(
                    getActivity().getApplicationContext(),
                    "No INTERNET! Circulars can't be loaded.",
                    Toast.LENGTH_LONG).show();
        }
        return rootView;

    }

    }

0 个答案:

没有答案