Basim Sherif
Basim Sherif

Reputation: 5440

Android application getting stuck when swiping through Viewpager

In my android application I have 3 fragments.A B and C.I am doing some XML parsing and populating listviews.Swiping from A to B and B to C is very smooth.But when I try to swipe from C to B and B to A , it get stucked for about 10 seconds.ie, A->B->C is smooth.And C->B->A is having problem.Its really annoying.Can anyone help me get rid of this problem?...Thanks in advance....

Here is my 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();
            }
     }





}

Fragment B=>

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



        }


}

And Fragment C is actually a blank fragment.

Upvotes: 0

Views: 5464

Answers (4)

Dany&#39;s
Dany&#39;s

Reputation: 928

populateListView must be done in onPostExecute() method of async task....

Upvotes: 1

Praful Bhatnagar
Praful Bhatnagar

Reputation: 7435

As a general rule you should always do long lasting task like network connection in background thread. In activity you can always use AsyncTask. Second thing why are you loading the feed every time user change the view pager page. You should just do it once initially and refresh it after a fix interval in the background...

EDIT1:

One way to achieve keep a global data structure that is accessible from each fragment, You may use the custom Application object,and store the data for each language in that data structure.

Each time user go to you page checks if the data is available in the global object if it is available then show the data or show loading.

From your activity launch the AsyncTask that loads the data from server for each language, parse and store it in the global data structure. After each successful download notify the fragment that the data has been updated In the global object and they update their view accordingly..

Upvotes: 1

StackOverflower
StackOverflower

Reputation: 410

Some solutions that will help you:

1 - Add logging in your code to see if onCreateView and onViewCreated is getting called multiple times.

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- Dont make your network calls or any long running code on the Main UI thread. For example, you are calling parse() which is making a network call on your UI thread. That is why your app has delays, especially in fragment A. Use an AsyncTask/Thread/Future

3 - If you have 3 fragments only set this option in for your viewPager: viewPager.setOffscreenPageLimit(3). It seems like your fragments are being recreated each time. This causes your viewCreated to be called, thus calling your parse().

4 - You can pass data from the doInBackground() to the onPostExecute. You dont need populate_listview.

Let me know if you need any more explanation.

Upvotes: 7

Kumar Bibek
Kumar Bibek

Reputation: 9117

You need to fetch data and parse it in a background thread, else your Fragment's lifecycle methods will pause for a longer time, and thus you see it getting stuck.

Use either Aysnctasks or background threads for doing operations that take a long time to complete.

Upvotes: 1

Related Questions