刷卡时只加载当前页面 - 使用android pageviewer

时间:2014-08-30 09:51:04

标签: java android rss

我目前正在创建一个RSS提要阅读应用程序,使用Android附带的页面查看器控件。我有四个页面使用片段加载,问题是,当在每个页面之间滑动时...通常应用程序会在实际滑动到下一个片段之前冻结几秒钟。

我发现,其原因是页面查看器不仅加载了它所在的当前片段;还有列表中的下一个片段;并且假设每个片段都有可能在listView中有50多个项目,这些项目由RSS源的数据连接填充,这意味着它正在尝试使用大量数据一次加载两个listView。因此,使应用程序冻结。

我的问题是,根据我的下面的代码,我将如何使这个运行更顺畅。有没有办法只加载你当前的片段,而不是下一个片段,然后当你滑动到下一个片段时...新的片段加载等?

任何建议都会有所帮助,如果有人愿意,我可以粘贴更多代码。

谢谢!

将片段添加到pageViewer的代码:

    package com.example.directrssread;

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

import android.support.v4.app.Fragment;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.app.ActionBar.Tab;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;

public class ViewPagerFragmentActivity extends FragmentActivity{

    //boolean addFirstPage = true;

       /** 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() {

        boolean addFirstPage = ((GlobalVariables) this.getApplication()).getSomeVariable();

         final ActionBar actionBar = getActionBar();// getActionBar();
         actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
         final ViewPager mViewPager;
         mViewPager = (ViewPager) findViewById(R.id.viewpager);

         // Create a tab listener that is called when the user changes tabs.
            ActionBar.TabListener tabListener = new ActionBar.TabListener() {



                @Override
                public void onTabReselected(Tab tab, FragmentTransaction ft) {
                    // TODO Auto-generated method stub

                }
                @Override
                  public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
                        // When the tab is selected, switch to the
                        // corresponding page in the ViewPager.
                        mViewPager.setCurrentItem(tab.getPosition());

                }

                @Override
                public void onTabUnselected(Tab tab, FragmentTransaction ft) {
                    // TODO Auto-generated method stub

                }

            };

            for (int i = 0; i < 4; i++) {
                //int curr = mViewPager.get
                String currTab = "";
                if (i == 0)
                {
                    currTab = "EPL";
                }

                if (i == 1)
                {
                    currTab = "Champ";
                }

                if (i == 2)
                {
                    currTab = "League One";
                }

                if (i == 3)
                {
                    currTab = "League Two";
                }
                actionBar.addTab(
                        actionBar.newTab()

                                .setText(currTab)
                                .setTabListener(tabListener));

            }

            mViewPager.setOnPageChangeListener(
                    new ViewPager.SimpleOnPageChangeListener() {
                        @Override
                        public void onPageSelected(int position) {
                            // When swiping between pages, select the
                            // corresponding tab.
                            getActionBar().setSelectedNavigationItem(position);
                        }
                    });


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

    }

}

我的listView页面之一:

   package com.example.directrssread;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.AsyncTask;
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 = "";
    View mView;

    ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
    //Map<Date, ArrayList> menuItems = new TreeMap<Date, ArrayList>();
    Map<Date, ArrayList> sortedMap = null;
    //ProgressDialog.Builder builder;
    // final ProgressDialog mDialog = new ProgressDialog((ViewPagerFragmentActivity)getActivity());
    // 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";
    static final String KEY_PUBTIME = "pubDate";


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

         StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
         StrictMode.setThreadPolicy(policy);
         Log.e("Feed1", "Feed1");

         mView = inflater.inflate(R.layout.feed1, container, false);
            return inflater.inflate(R.layout.feed1, container, false);

        }

     public void onActivityCreated(Bundle savedInstanceState) {
         menuItems.removeAll(menuItems);
         count = 0;     
          rssRun(); 
          Log.e("Count", String.valueOf(menuItems.size()));     
         super.onActivityCreated(savedInstanceState);

         }

     public void rssRun()
     {

         Log.e("FEED1", "Running feed1");
         boolean runSubstring = true;
            //URL[0] = "http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/teams/a/arsenal/rss.xml";
            URL[0] = "http://www.football365.com/premier-league/rss";
            URL[1] = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
            //URL[2] = "http://www.skysports.com/rss/0,20514,11661,00.xml";

            //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("HERE", "HERE");
            //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 = "SkySports";
                }

                //map.remove(map);

                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());
                String pubDateFormat = "";
                pubTime = pubTime.substring(0, 5);
                map.put(KEY_PUBDATE, pubTime);  

                pubDateFormat = pubDate.substring(0, 22);
                pubDate = pubDate.substring(0, 16);

                pubDate = pubDate + " " + pubTime;


                SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm");
                Date date = dateFormatter.parse(pubDateFormat);
                dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
                //Log.e("DATE", dateFormatter.format(date));
                //Calendar c = Calendar.getInstance(); 
                //String currDate
                SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                String currDate = sdf.format(new Date());
                //Log.e("CURRENT DATE", currDate);
                //System.out.println(dateFormatter.format(date));
                //System.out.println(sdf2.format(date));

                //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
                //10
                //if (dateFormatter.format(date) == currDate)
//              if (dateFormatter.format(date).substring(0, 10) == currDate.substring(0, 10))
                //String  input = EditTextinput.getText().toString();
                //input = input.replace(" ", "");
                currDate = currDate.replace(" ", "");
                String rssDate = dateFormatter.format(date).replace(" ", "");
                Date dt1 = dateFormatter.parse(currDate);
                Date dt2 = dateFormatter.parse(rssDate);
                //Log.e("TRIM CURR", currDate);
                //Log.e("RSSDATE", rssDate);
                //if (rssDate == currDate)
                if (dt1.compareTo(dt2)==0)//== currDate)
                {
                    menuItems.add(map);
                    Collections.sort(menuItems, new MapComparator(KEY_PUBTIME));
                    Collections.reverse(menuItems);
                    //sortedMap = new TreeMap<Date, ArrayList>(menuItems);
                    //Log.e("SAME", "THE SAME");
                }
                //Log.e("TRIM CURR1", currDate);
                //Log.e("RSSDATE1", rssDate);
                //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 txt = getTextView();

            //TextView firstName = (TextView) V.findViewById(R.id.textView1);

//          TextView firstName = (TextView) findViewById(R.id.textView1);
            //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);

                }
            });
        }


        // mDialog.dismiss();
         Log.e("RUN", "RSSRUN");
     }

     class LongOperation extends AsyncTask<String, Void, String> {
           // private Main longOperationContext = null;

           // public LongOperation(Main context) {

           // }


            protected String doInBackground(String... params) {
                Log.e("FEED1", "Running feed1");
                 boolean runSubstring = true;
                    //URL[0] = "http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/teams/a/arsenal/rss.xml";
                    URL[0] = "http://www.football365.com/premier-league/rss";
                    URL[1] = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
                    //URL[2] = "http://www.skysports.com/rss/0,20514,11661,00.xml";

                    //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("HERE", "HERE");
                    //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 = "SkySports";
                        }

                        //map.remove(map);

                        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());
                        String pubDateFormat = "";
                        pubTime = pubTime.substring(0, 5);
                        map.put(KEY_PUBDATE, pubTime);  

                        pubDateFormat = pubDate.substring(0, 22);
                        pubDate = pubDate.substring(0, 16);

                        pubDate = pubDate + " " + pubTime;


                        SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm");
                        Date date = dateFormatter.parse(pubDateFormat);
                        dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
                        //Log.e("DATE", dateFormatter.format(date));
                        //Calendar c = Calendar.getInstance(); 
                        //String currDate
                        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                        String currDate = sdf.format(new Date());
                        //Log.e("CURRENT DATE", currDate);
                        //System.out.println(dateFormatter.format(date));
                        //System.out.println(sdf2.format(date));

                        //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
                        //10
                        //if (dateFormatter.format(date) == currDate)
//                      if (dateFormatter.format(date).substring(0, 10) == currDate.substring(0, 10))
                        //String  input = EditTextinput.getText().toString();
                        //input = input.replace(" ", "");
                        currDate = currDate.replace(" ", "");
                        String rssDate = dateFormatter.format(date).replace(" ", "");
                        Date dt1 = dateFormatter.parse(currDate);
                        Date dt2 = dateFormatter.parse(rssDate);
                        //Log.e("TRIM CURR", currDate);
                        //Log.e("RSSDATE", rssDate);
                        //if (rssDate == currDate)
                        if (dt1.compareTo(dt2)==0)//== currDate)
                        {
                            menuItems.add(map);
                            Collections.sort(menuItems, new MapComparator(KEY_PUBTIME));
                            Collections.reverse(menuItems);
                            //sortedMap = new TreeMap<Date, ArrayList>(menuItems);
                            //Log.e("SAME", "THE SAME");
                        }
                        //Log.e("TRIM CURR1", currDate);
                        //Log.e("RSSDATE1", rssDate);
                        //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);

                        //setListAdapter(adapter);
                    //}

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

                    //TextView txt = getTextView();

                    //TextView firstName = (TextView) V.findViewById(R.id.textView1);

//                  TextView firstName = (TextView) findViewById(R.id.textView1);
                    //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);

                        }
                    });
                }
                return currURL;

            }


            protected void onPostExecute(String result) {


            }
            protected void onPreExecute() {
            }


            protected void onProgressUpdate(Void... values) {

            }    

        }


     class MapComparator implements Comparator<Map<String, String>>
     {
         private final String key;

         public MapComparator(String key)
         {
             this.key = key;
         }

         public int compare(Map<String, String> first,
                            Map<String, String> second)
         {
             // TODO: Null checking, both for maps and values
             String firstValue = first.get(key);
             String secondValue = second.get(key);
             return ((String) first.get(key)).compareTo((String) second.get(key));
            // return firstValue.compareTo(secondValue);
         }
     }


}

1 个答案:

答案 0 :(得分:0)

正如评论中已经说过的那样:我建议您使用AsyncTask来加载内容。遵循你需要改变的东西。 (只是原始概述)

以下是您的 AsyncTask 基本上应该是这样的:

class LongOperation extends AsyncTask<String, Void, Void> {

    protected Void doInBackground(String... params) {
        for (int f= 0;f < params.length;f++)
        {

            try{
                XMLParser parser = new XMLParser();
                String xml = parser.getXmlFromUrl(params[f]); // getting XML
                // Parse xml, add to your Map etc.
            }
            catch(Exception e)
            {
               // Handle exception
            }
        }
        return null;
    }


    protected void onPostExecute(Void aVoid) {
        setupListView();
    }
}

请注意: 我已经更改了AsyncTask的参数。此外,URL是通过参数访问的,而不是通过你已经定义的数组访问。

setupListView中,不应该是AsyncTask的一部分,您可以创建和设置适配器以及onItemClickListener。请勿在{{1​​}}的{​​{1}}方法中执行此操作。

doInBackground

为了运行AsyncTask,您只需调用以下行,包括您不想加载的所有URL:

AsyncTask

并回答你的问题:“有没有办法阻止加载private void setupListView(){ 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}); setListAdapter(adapter); ListView lv = getListView(); lv.setOnItemClickListener(new OnItemClickListener() { // ... }; } 中的下一个 new LongOperation().execute( "http://www.football365.com/premier-league/rss", "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk", "http://www.skysports.com/rss/0,20514,11661,00.xml"); ?” - 不,至少就此而言我知道。那是因为需要在滑动手势之前加载下一个片段。 (否则什么都看不见)