一旦完成,将片段添加到pageviwer?

时间:2014-08-28 17:55:56

标签: android listview networking asynchronous

我目前正在创建一个RSS阅读应用程序,它使用页面查看器....这样用户就可以在应用程序中的不同视图/提要之间滑动。

问题是,一旦我刷到第二个视图,应用程序就会冻结......因为它试图同时加载太多数据。

所以我想问一下,加载前一个视图后是否有添加每个视图的方法;或任何真正使应用程序加载数据而不冻结的东西,并使其加载更顺畅。

任何帮助都会很棒!感谢。

此代码是我添加视图的方式:

        package com.example.directrssread;

    import java.util.List;
    import java.util.Vector;

    import android.support.v4.app.Fragment;
    import android.os.Bundle;
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.view.PagerAdapter;
    import android.support.v4.view.ViewPager;

    public class ViewPagerFragmentActivity extends FragmentActivity{

           /** maintains the pager adapter*/
        private PagerAdapter mPagerAdapter;
        /* (non-Javadoc)
         * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
         */
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            super.setContentView(R.layout.viewpager);
            //initialsie the pager
            this.initialisePaging();
        }

        /**
         * Initialise the fragments to be paged
         */
        private void initialisePaging() {

            List<Fragment> fragments = new Vector<Fragment>();
            fragments.add(Fragment.instantiate(this, Feed1.class.getName()));

            fragments.add(Fragment.instantiate(this, Feed2.class.getName()));
            fragments.add(Fragment.instantiate(this, Feed3.class.getName()));
            //fragments.add(Fragment.instantiate(this, Feed4.class.getName()));
           // fragments.add(Fragment.instantiate(this, Tab3Fragment.class.getName()));
            this.mPagerAdapter  = new PagerAdapter1(super.getSupportFragmentManager(), fragments);
            //
            ViewPager pager = (ViewPager)super.findViewById(R.id.viewpager);
            pager.setAdapter(this.mPagerAdapter);
        }

    }

This code is from one of my views (they all have the same code, and there are 4 of them)

    package com.example.directrssread;


import java.util.ArrayList;
import java.util.HashMap;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class Feed1 extends ListFragment{

    String[] URL = new String[3];
    int count = 0;
    String currURL = "";
    ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
    // 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_TITLE = "title";
    static final String KEY_COST = "cost";
    static final String KEY_DESC = "description";
    static final String KEY_LINK = "link";
    static final String KEY_PUBDATE = "pubDate";

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

         StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
         StrictMode.setThreadPolicy(policy);
            return inflater.inflate(R.layout.feed1, container, false);

        }

     public void onActivityCreated(Bundle savedInstanceState) {
        // rssRun();

         boolean runSubstring = true;
            //URL[0] = "http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/teams/a/arsenal/rss.xml";
            URL[0] = "http://talksport.com/rss/football/premier-league/feed";
            URL[1] = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
            URL[2] = "http://talksport.com/rss/football/premier-league/feed";

            //URL[3] = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
            for (int f= 0;f < URL.length;f++)
            {

            try{
                 //Log.e("TEst1", "TEst");

            XMLParser parser = new XMLParser();
            String xml = parser.getXmlFromUrl(URL[f]); // getting XML
            Document doc = parser.getDomElement(xml); // getting DOM element
            //Log.e("XML", xml);

            NodeList nl = doc.getElementsByTagName(KEY_ITEM);
            //Log.e("NODELIST", nl.toString());
            // looping through all item nodes <item>

            for (int i = 0; i < nl.getLength(); i++) {
                // creating new HashMap
                if (doc!=null)
                {
                HashMap<String, String> map = new HashMap<String, String>();
                Element e = (Element) nl.item(i);
                // adding each child node to HashMap key => value
                if (count == 0)
                {
                    currURL = "Football365";
                }
                if (count == 1)
                {
                    currURL = "BBC Sport";
                }
                if (count == 2)
                {
                    currURL = "TalkSport";
                }


                map.put(KEY_ID, parser.getValue(e, KEY_ID));
                //Get the title of the article.
                map.put(KEY_NAME, parser.getValue(e, KEY_TITLE));
                //Get the description of the article.
                map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
                //Get the source e.g ' Football365'.
                //String pubDate = parser.getValue(e, KEY_PUBDATE);
                String pubDate = parser.getValue(e, KEY_PUBDATE);
                //Parse the date and time from the main strings.
                //Chop off the un-wanted parts.
                //Bring them back together in one string.
                String pubTime = pubDate.substring(17, pubDate.length());
                pubTime = pubTime.substring(0, 5);
                pubDate = pubDate.substring(0, 16);         
                pubDate = pubDate + " " + pubTime;
                //Log.e("TITLE", )      
                map.put(KEY_TITLE, currURL + " - " + pubDate);          
                //Add the link.
                map.put(KEY_LINK, parser.getValue(e, KEY_LINK));
                //Get the publish date.
                //map.put(KEY_PUBDATE, parser.getValue(e, KEY_PUBDATE));
                // adding HashList to ArrayList
                menuItems.add(map);
                Log.e("TEst", "TEst");
                for (int q = 0;q < map.size();q++)
                {
                    Log.e("mene", map.get(KEY_TITLE));
                }


                }

            }
            count+=1;
            }
            catch(Exception e)
            {
                Log.e("ERROR", e.toString());
            }

            // Adding menuItems to ListView
            ListAdapter adapter = new SimpleAdapter(getActivity(), menuItems,
                    R.layout.list_item,
                    new String[] { KEY_NAME, KEY_DESC,KEY_LINK, KEY_TITLE }, new int[] {
                            R.id.name, R.id.desciption, R.id.link, R.id.source});
            //if (count==3)
            //{
                setListAdapter(adapter);
            //}

            // selecting single ListView item
            ListView lv = getListView();
            //TextView firstName = (TextView) V.findViewById(R.id.textView1);
            //EditText firstName = (EditText) findViewById(R.id.display_name);
            //ListView lv = (ListView) findViewById(R.id.l)
            //ListView lv = ((ListView) findViewbyId(R.id)

            lv.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 link = ((TextView) view.findViewById(R.id.link)).getText().toString();
                    String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();

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

                }
            });
        }



         Log.e("RUN", "RSSRUN");
          super.onActivityCreated(savedInstanceState);

         }



     public void rssRun()
        {
            boolean runSubstring = true;
            //URL[0] = "http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/teams/a/arsenal/rss.xml";
            URL[0] = "http://talksport.com/rss/football/premier-league/feed";
            URL[1] = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
            URL[2] = "http://talksport.com/rss/football/premier-league/feed";

            //URL[3] = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
            for (int f= 0;f < URL.length;f++)
            {

            try{

            XMLParser parser = new XMLParser();
            String xml = parser.getXmlFromUrl(URL[f]); // getting XML
            Document doc = parser.getDomElement(xml); // getting DOM element
            //Log.e("XML", xml);

            NodeList nl = doc.getElementsByTagName(KEY_ITEM);
            //Log.e("NODELIST", nl.toString());
            // looping through all item nodes <item>

            for (int i = 0; i < nl.getLength(); i++) {
                // creating new HashMap
                if (doc!=null)
                {
                HashMap<String, String> map = new HashMap<String, String>();
                Element e = (Element) nl.item(i);
                // adding each child node to HashMap key => value
                if (count == 0)
                {
                    currURL = "Football365";
                }
                if (count == 1)
                {
                    currURL = "BBC Sport";
                }
                if (count == 2)
                {
                    currURL = "TalkSport";
                }


                map.put(KEY_ID, parser.getValue(e, KEY_ID));
                //Get the title of the article.
                map.put(KEY_NAME, parser.getValue(e, KEY_TITLE));
                //Get the description of the article.
                map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
                //Get the source e.g ' Football365'.
                //String pubDate = parser.getValue(e, KEY_PUBDATE);
                String pubDate = parser.getValue(e, KEY_PUBDATE);
                //Parse the date and time from the main strings.
                //Chop off the un-wanted parts.
                //Bring them back together in one string.
                String pubTime = pubDate.substring(17, pubDate.length());
                pubTime = pubTime.substring(0, 5);
                pubDate = pubDate.substring(0, 16);         
                pubDate = pubDate + " " + pubTime;
                //Log.e("TITLE", )      
                map.put(KEY_TITLE, currURL + " - " + pubDate);          
                //Add the link.
                map.put(KEY_LINK, parser.getValue(e, KEY_LINK));
                //Get the publish date.
                //map.put(KEY_PUBDATE, parser.getValue(e, KEY_PUBDATE));
                // adding HashList to ArrayList
                menuItems.add(map);
                for (int q = 0;q < map.size();q++)
                {
                    Log.e("mene", map.get(KEY_TITLE));
                }


                }

            }
            count+=1;
            }
            catch(Exception e)
            {

            }

            // Adding menuItems to ListView
            final ListAdapter adapter = new SimpleAdapter(getActivity(), menuItems,
                    R.layout.list_item,
                    new String[] { KEY_NAME, KEY_DESC,KEY_LINK, KEY_TITLE }, new int[] {
                            R.id.name, R.id.desciption, R.id.link, R.id.source});
            //if (count==3)
            //{

            new Thread(new Runnable() {
                public void run() {

                new Thread(new Runnable() {
                    public void run() {
                        setListAdapter(adapter);
                    }
                  });
                }
              }).start();


                //setListAdapter(adapter);
            //}

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

            lv.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 link = ((TextView) view.findViewById(R.id.link)).getText().toString();
                    String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();

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

                }
            });
        }
        }


    /*protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.feed1);
           ////initialsie the pager
           //this.initialisePaging();
       }*/

}

1 个答案:

答案 0 :(得分:0)

在活动生命周期方法中执行耗时的任务并不是一种好习惯。相反,你应该使用加载器和你的碎片。加载程序可以在后台加载数据,同时您可以显示进度对话框。在加载程序中完成加载后,您可以在片段中显示数据。 这将使UI响应。 从这里了解更多关于装载机的信息

http://developer.android.com/guide/components/loaders.html http://developer.android.com/reference/android/content/Loader.html