Basim Sherif
Basim Sherif

Reputation: 5440

How to run functions in background of fragments in Android?

I have two fragments fragment A and fragment B.In both fragments Iam using asynctask and running some functions in background.These functions(for parsing XML and populating list view).When I start the app functions in both fragments are running at the same time.So app gets slow. What I need is to run functions in fragment A first.Functions in fragment B should start only after finishing functions in fragment B.How can I achieve this? Please some one help me.Thanks in advance.....

Fragment A=>

    public class A extends 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;
    ListView 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;
    public static NodeList nl;

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

        }

    }

    public void StartProgress() {
        new ProgressAsyncTask().execute();
    }

    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);
            list = (ListView) getActivity().findViewById(R.id.list2);

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

            loading.setVisibility(View.INVISIBLE);

            list.setOnItemClickListener(new OnItemClickListener() {

                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {

                    Intent myintent = new Intent(
                            "com.madhyamam.malayalam2keralapodcast.PODCAST");
                    Bundle mybundle = new Bundle();
                    mybundle.putInt("number", position);
                    myintent.putExtras(mybundle);

                    startActivity(myintent);

                }
            });

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub
            getActivity().finishActivity(5);
            parse();                         //Here is the first function in fragment A
            if (Title != null) {
                populate_listview();    //Second function
            }
            return null;
        }

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

        }

    }

    public void parse() {

                 //parsing done here....

    }

}  

Fragment B=>

public class B extends 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;
    ListView list;
    NationalAdapter adapter;
    ProgressBar loading;
    ArrayList<HashMap<String, String>> newsList;
    public static National 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;
    public static NodeList nl;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflating layout
        View v = inflater.inflate(R.layout.national_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/18/1/rss.xml";

        }

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

        }

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

    }

    public void populate_listview() {

        newsList = new ArrayList<HashMap<String, String>>();
        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);

        }

    }

    public void StartProgress() {
        new ProgressAsyncTask().execute();
    }

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

            list = (ListView) getActivity().findViewById(R.id.list3);

            // Getting adapter by passing xml data ArrayList
            adapter = new NationalAdapter(getActivity(), newsList);
            list.setAdapter(adapter);
            loading.setVisibility(View.INVISIBLE);

            list.setOnItemClickListener(new OnItemClickListener() {

                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {

                    Intent myintent = new Intent(
                            "com.madhyamam.malayalam2nationalpodcast.PODCAST");
                    Bundle mybundle = new Bundle();
                    mybundle.putInt("number", position);
                    myintent.putExtras(mybundle);

                    startActivity(myintent);

                }
            });

        }

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

            parse();               //First function in fragment B
            if (Title != null) {
                populate_listview(); // Second function in fragment B
            }

            return null;
        }

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

        }

    }

    public void parse() {

           //parsing done here....
    }

}

And Main Activity =>

public class MainActivity extends SlidingMenuActivity {

    private LinearLayout MenuList;
    private Button btnToggleMenuList;
    private int screenWidth;
    private boolean isExpanded;

    private ViewPager mViewPager;

    private ProgressDialog pd;
    TextView settings, headlines, kerala, national, international, sports,
            tech, enter, bus, hotwheels, gulf;
    static TextView flashnews;
    public static int stopflag = 0;
    HorizontalScrollView scroll;
    private ListView listView;
    static int currentRotation;
    public PagerTabStrip pagerTabStrip;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Context context = getApplicationContext();



        setLayoutIds(R.layout.slidingtab, R.layout.main);
        setAnimationDuration(300);
        super.onCreate(savedInstanceState);

        btnToggleMenuList = (Button) findViewById(R.id.BtnSlide);

        btnToggleMenuList.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                toggleMenu();
                startanim();
            }

        });

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

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

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

        ;

        settings = (Button) findViewById(R.id.settings);

        headlines = (TextView) findViewById(R.id.headlines);
        kerala = (TextView) findViewById(R.id.kerala);
        national = (TextView) findViewById(R.id.national);
        international = (TextView) findViewById(R.id.international);
        sports = (TextView) findViewById(R.id.sports);
        tech = (TextView) findViewById(R.id.tech);
        gulf = (TextView) findViewById(R.id.gulf);
        enter = (TextView) findViewById(R.id.entertainment);
        bus = (TextView) findViewById(R.id.business);
        hotwheels = (TextView) findViewById(R.id.hotwheels);

        Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/kozuka.otf");

        headlines.setTypeface(tf);
        kerala.setTypeface(tf);
        national.setTypeface(tf);
        international.setTypeface(tf);
        sports.setTypeface(tf);
        tech.setTypeface(tf);
        gulf.setTypeface(tf);
        enter.setTypeface(tf);
        bus.setTypeface(tf);
        hotwheels.setTypeface(tf);



        pagerTabStrip = (PagerTabStrip) findViewById(R.id.pager_title_strip);
        pagerTabStrip.setDrawFullUnderline(true);
        pagerTabStrip.setTabIndicatorColor(Color.rgb(3, 158, 203));

        headlines.setPressed(true);

        // We get UI references
        mViewPager = (ViewPager) findViewById(R.id.viewpager);

        // We set pager adapter
        mViewPager.setAdapter(new MyAdapter(this));
        mViewPager.setOffscreenPageLimit(9);
        // We set receiver button listener




    }

    protected void startanim() {
        // TODO Auto-generated method stub

        RotateAnimation anim = new RotateAnimation(currentRotation,
                currentRotation + 180, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);

        currentRotation = (currentRotation + 180) % 360;
        anim.setInterpolator(new LinearInterpolator());
        anim.setDuration(400);
        anim.setFillEnabled(true);

        anim.setFillAfter(true);

        // Start animating the image

        btnToggleMenuList.startAnimation(anim);

    }

    /**
     * Adapter for ViewPAger that manages background interactions with fragments
     */

    private class MyAdapter extends FragmentPagerAdapter {

        private Context mContext;
        private String[] frags = { A.class.getName(),
                B.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";



            else
                return null;

        }

    }

}

Upvotes: 0

Views: 2369

Answers (1)

NewUser
NewUser

Reputation: 3819

You can use AsyncTask. In doinbackground() method you write the code for the function you want to execute first. The you can use onPostExecute() method to do the tasks you want to do after finishing of your first task.

Upvotes: 1

Related Questions