在浏览Viewpager时,Android应用程序卡住了

时间:2012-11-16 06:46:47

标签: android android-viewpager

在我的android应用程序中,我有3个片段.AB和CI正在做一些XML解析和填充listviews。从A到B和B到C的擦除非常流畅。但是当我尝试从C刷到B和B到A,它被卡住了大约10秒。但是,A-> B-> C是平滑的。而且C-> B-> A有问题。它真的很烦人。任何人都可以帮我摆脱这个问题?...提前致谢....

这是我的MainActivity =>

    public class MainActivity extends FragmentActivity {
    private ViewPager mViewPager;
    private ProgressDialog pd;
    Button settings;
    static TextView flashnews;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        SharedPreferences mlmprf = getSharedPreferences("malayalam", MODE_PRIVATE);
        final SharedPreferences.Editor mlmedit = mlmprf.edit();

        if(mlmprf.getBoolean("enable", true))
     {
         A.headflag="malayalam";
     }
     else
     {
         A.headflag="english";
     }

           flashnews=(TextView)findViewById(R.id.flashs);
       flashnews.setSelected(true);
       flashnews.setEllipsize(TruncateAt.MARQUEE);
       flashnews.setHorizontallyScrolling(true);
       flashnews.setSingleLine(true);
       flashnews.setLines(1);

      PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pager_title_strip);
        pagerTabStrip.setDrawFullUnderline(true);
        pagerTabStrip.setTabIndicatorColor(Color.rgb(174, 1, 34));
        mViewPager = (ViewPager) findViewById(R.id.viewpager);
            mViewPager.setAdapter(new MyAdapter(this));
      }

 private class MyAdapter extends FragmentPagerAdapter{

        private Context mContext;
        private String[] frags = {A.class.getName(), B.class.getName(),C.class.getName()};

        public MyAdapter(FragmentActivity activity) {
            super(activity.getSupportFragmentManager());
            mContext = activity;
        }



        @Override
        public Fragment getItem(int pos) {
            return Fragment.instantiate(mContext, frags[pos]);
        }

        @Override
        public int getCount() {
            return frags.length;
        }

        @Override
        public CharSequence getPageTitle(int pos) {

            if(pos==0)
            return "A";

            if(pos==1)
            return "B";

            if(pos==2)
            return "C";

            else
            return null;


        }
    }

}

FragmentA =>

    public class A extends Fragment{


    public static String urls;
    // XML node keys
    static final String KEY_HEAD = "item"; // parent node
    //static final String KEY_TITLE = "title";
    static final String KEY_DATE = "pubDate";
    public static String headflag="english";
    public static String[] Title;
    public static String[] Description;
    public static String[] Tit;
    public static String[] Tit2;
    public static String[] Desc;
    public static String[] Desc2;
    public static String[] image;
    int f=0;
    GridView list;
    HeadlinesAdapter adapter;
    private TextView mMessageView;
    private Button mClearButton;
    public ArrayList<HashMap<String, String>> newsList; 


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflating layout
        View v = inflater.inflate(R.layout.headlines_fragment, container, false);
        // We obtain layout references

        return v;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // We set clear listener


        if(Headlines.headflag=="malayalam")
        {
            urls="http://www.abc.com/rssfeeds/19_18_17_25/1/rss.xml";


        }

        if(Headlines.headflag=="english")
        {
            urls="http://www.abc.com/en/rssfeeds/1_2_3_5/latest/rss.xml";


        }



    parse();
        populate_listview();    
    }


     public void populate_listview()
     {


        newsList = new ArrayList<HashMap<String, String>>();

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(urls); // getting XML from URL
        Document doc = parser.getDomElement(xml); // getting DOM element

        NodeList nl = doc.getElementsByTagName(KEY_HEAD);
        // looping through all song nodes <song>
        NodeList itemLst = doc.getElementsByTagName("item");
        String MarqueeStr="";

        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);
            newsList.add(map);
            //MarqueeStr = MarqueeStr +" *** "+ Title[i];


     }

        list=(GridView)getActivity().findViewById(R.id.grid);

        // Getting adapter by passing xml data ArrayList
                 adapter=new HeadlinesAdapter(getActivity(), newsList);        
                 list.setAdapter(adapter);



    }

  public void parse()
     {

            URL url;

            try {

                url = new URL(urls);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                if((conn.getResponseCode() == HttpURLConnection.HTTP_OK)){
                      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                      DocumentBuilder db = dbf.newDocumentBuilder();
                      Document doc;
                      doc = db.parse(url.openStream());
                      doc.getDocumentElement().normalize();

                      NodeList itemLst = doc.getElementsByTagName("item");
                      Description = new String[itemLst.getLength()];//........
                      Title = new String[itemLst.getLength()];
                      Tit=new String[itemLst.getLength()];
                      Tit2=new String[itemLst.getLength()];
                      Desc=new String[itemLst.getLength()];
                      Desc2=new String[itemLst.getLength()];
                      image= new String[itemLst.getLength()];

                      for(int i=0; i < itemLst.getLength(); i++){

                            Node item = itemLst.item(i);
                            if(item.getNodeType() == Node.ELEMENT_NODE){
                                  Element ielem = (Element)item;
                                  NodeList title = ielem.getElementsByTagName("title");
                                  NodeList date = ielem.getElementsByTagName("pubDate");
                                  NodeList description = ielem.getElementsByTagName("description");
                                  Tit[i]= title.item(0).getChildNodes().item(0).getNodeValue();
                                  Desc[i]= description.item(0).getChildNodes().item(0).getNodeValue();
                                  Tit2[i]=Translate.title(Tit[i]);
                                  Desc2[i]=Translate.description(Desc[i]);
                                  if(Headlines.headflag=="malayalam")
                                    {
                                      Desc2[i]=Desc2[i].replace("read more","IqSpXÂ");
                                    }
                                  Title[i] =Tit2[i];
                                  if (Desc2[i].contains("<img ")){
                                      String img  = Desc2[i].substring(Desc2[i].indexOf("<img "));
                                      String cleanUp = img.substring(0, img.indexOf(">")+1);
                                      img = img.substring(img.indexOf("src=") + 5);
                                      int indexOf = img.indexOf("'");
                                      if (indexOf==-1){
                                          indexOf = img.indexOf("\"");
                                        }
                                      img = img.substring(0, indexOf);

                                //setImgLink(img);
                                    if(Headlines.headflag=="malayalam")
                                    {
                                        String img2=img.replace("files","files/imagecache/android_320");
                                        Description[i]=Desc2[i].replace(img,img2);
                                        image[i]=img2;
                                    }

                                else
                                {
                                    String img2=img.replace("files","files/imagecache/android_1_img");
                                    Description[i]=Desc2[i].replace(img,img2);
                                    image[i]=img2;
                                }
                                  }
                                else
                                {
                                    Description[i] =Desc2[i];
                                }



                            }

                          }

                        }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (DOMException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
     }





}

片段B =&gt;

public class B Fragment{



    static String urls;
    // XML node keys
    static final String KEY_HEAD = "item"; // parent node
    //static final String KEY_TITLE = "title";
    static final String KEY_DATE = "pubDate";
    public static String headflag="";
    int f=0;
    GridView list;
    KeralaAdapter adapter;
    ProgressBar loading;
    ArrayList<HashMap<String, String>> newsList;
    public static Kerala classnam;

        public static String[] Title;
        public static String[] Description;
        public static String[] Tit;
        public static String[] Tit2;
        public static String[] Desc;
        public static String[] Desc2;
        public static String[] image;
        public static String[] Date;
        public static String[] Flash;
        public static String[] Fl;
        public static String[] Fl2;




    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflating layout
        View v = inflater.inflate(R.layout.kerala_fragment, container, false);
        // We obtain layout references

        return v;

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // We set clear listener

        if(Headlines.headflag=="malayalam")
        {
            urls="http://www.abc.com/rssfeeds/17/1/rss.xml";


        }

        if(Headlines.headflag=="english")
        {
            urls="http://www.abc.com/en/rssfeeds/1/latest/rss.xml";


        }


        loading=(ProgressBar)getActivity().findViewById(R.id.loading);
        new ProgressAsyncTask().execute();

          }


     public void populate_listview()
     {

                newsList = new ArrayList<HashMap<String, String>>();

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(urls); // getting XML from URL
        Document doc = parser.getDomElement(xml); // getting DOM element

        NodeList nl = doc.getElementsByTagName(KEY_HEAD);
        // looping through all song nodes <song>
        NodeList itemLst = doc.getElementsByTagName("item");
        String MarqueeStr="";

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

            //map.put(KEY_DATE, parser.getValue(e, KEY_DATE));

            newsList.add(map);


     }


        list=(GridView)getActivity().findViewById(R.id.grid2);


}

                  public class ProgressAsyncTask extends 
            AsyncTask<Void, Integer, Void> {

            int myProgress;

            @Override
            protected void onPreExecute() {
                // TODO Auto-generated method stub
                super.onPreExecute();
                                myProgress = 0;
                       }

            @Override
            protected void onPostExecute(Void result) {
                // TODO Auto-generated method stub
                super.onPostExecute(result);
                            adapter=new NationalAdapter(getActivity(), newsList);        
                    list.setAdapter(adapter);

                       }

            @Override
            protected Void doInBackground(Void... arg0) {
                // TODO Auto-generated method stub

                parse();
                populate_listview();
                                return null;
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                // TODO Auto-generated method stub
                       }

        }


        public void parse()
        {
            URL url;

            try {
                      url = new URL(urls);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                if((conn.getResponseCode() == HttpURLConnection.HTTP_OK)){
                      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                      DocumentBuilder db = dbf.newDocumentBuilder();
                      Document doc;
                      doc = db.parse(url.openStream());
                      doc.getDocumentElement().normalize();

                      NodeList itemLst = doc.getElementsByTagName("item");
                      Description = new String[itemLst.getLength()];//........
                      Title = new String[itemLst.getLength()];
                      Tit=new String[itemLst.getLength()];
                      Tit2=new String[itemLst.getLength()];
                      Desc=new String[itemLst.getLength()];
                      Desc2=new String[itemLst.getLength()];
                      image= new String[itemLst.getLength()];

                      for(int i=0; i < itemLst.getLength(); i++){

                            Node item = itemLst.item(i);
                            if(item.getNodeType() == Node.ELEMENT_NODE){
                                  Element ielem = (Element)item;
                                  NodeList title = ielem.getElementsByTagName("title");
                                  NodeList date = ielem.getElementsByTagName("pubDate");
                                  NodeList description = ielem.getElementsByTagName("description");
                                  Tit[i]= title.item(0).getChildNodes().item(0).getNodeValue();
                                  Desc[i]= description.item(0).getChildNodes().item(0).getNodeValue();
                                  Tit2[i]=Translate.title(Tit[i]);
                                  Desc2[i]=Translate.description(Desc[i]);
                                  if(Headlines.headflag=="malayalam")
                                    {
                                      Desc2[i]=Desc2[i].replace("read more","IqSpXÂ");
                                    }
                                  Title[i] =Tit2[i];
                                  if (Desc2[i].contains("<img ")){
                                      String img  = Desc2[i].substring(Desc2[i].indexOf("<img "));
                                      String cleanUp = img.substring(0, img.indexOf(">")+1);
                                      img = img.substring(img.indexOf("src=") + 5);
                                      int indexOf = img.indexOf("'");
                                      if (indexOf==-1){
                                          indexOf = img.indexOf("\"");
                                        }
                                      img = img.substring(0, indexOf);

                                //setImgLink(img);
                                    if(Headlines.headflag=="malayalam")
                                    {
                                        String img2=img.replace("files","files/imagecache/android_320");
                                        Description[i]=Desc2[i].replace(img,img2);
                                        image[i]=img2;
                                    }

                                else
                                {
                                    String img2=img.replace("files","files/imagecache/android_1_img");
                                    Description[i]=Desc2[i].replace(img,img2);
                                    image[i]=img2;
                                }
                                  }
                                else
                                {
                                    Description[i] =Desc2[i];
                                }



                            }

                          }

                        }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (DOMException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



        }


}

片段C实际上是一个空白片段。

4 个答案:

答案 0 :(得分:5)

一些可以帮助您的解决方案:

1 - 在代码中添加日志记录,以查看是否多次调用onCreateView和onViewCreated。

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
       View v = inflater.inflate(R.layout.kerala_fragment, container, false);

       **Log.i("Tag", "onCreateView");**        

        return v;
}

2-不要在主UI线程上进行网络调用或任何长时间运行的代码。例如,您正在调用在您的UI线程上进行网络调用的parse()。这就是为什么你的应用程序有延迟,特别是在片段A中。使用AsyncTask / Thread / Future

3 - 如果你有3个片段,只为viewPager设置此选项:viewPager.setOffscreenPageLimit(3)。看起来你的片段每次都在被重建。这会导致调用viewCreated,从而调用您的parse()。

4 - 您可以将数据从doInBackground()传递到onPostExecute。你不需要populate_listview。

如果您需要更多解释,请与我们联系。

答案 1 :(得分:1)

您需要获取数据并在后台线程中解析它,否则您的Fragment的生命周期方法将暂停一段时间,因此您会看到它被卡住了。

使用Aysnctasks或后台线程执行需要很长时间才能完成的操作。

答案 2 :(得分:1)

作为一般规则,您应该始终执行长期任务,例如后台线程中的网络连接。在活动中,您始终可以使用AsyncTask。第二件事为什么每次用户更改视图寻呼机页面时都会加载Feed。你最初应该这样做,并在后台修复间隔后刷新它......

EDIT1:

实现保持可从每个片段访问的全局数据结构的一种方法,您可以使用自定义Application对象,并将每种语言的数据存储在该数据结构中。

每次用户转到您页面检查数据是否在全局对象中可用(如果可用),则显示数据或显示加载。

从您的活动中启动AsyncTask,为每种语言从服务器加载数据,解析并将其存储在全局数据结构中。每次成功下载后,通知片段数据已更新在全局对象中,并相应地更新其视图..

答案 3 :(得分:1)

populateListView必须在异步任务的onPostExecute()方法中完成....