0

我有两个片段片段 A 和片段 B。在两个片段中,我都使用 asynctask 并在后台运行一些函数。这些函数(用于解析 XML 和填充列表视图)。当我启动两个片段中的应用程序时,两个片段中的函数同时运行.所以应用程序变慢了。我需要的是首先在片段 A 中运行函数。片段 B 中的函数应该仅在完成片段 B 中的函数后启动。我该如何实现?请有人帮助我。在此先感谢......

片段 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....

    }

}  

片段 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....
    }

}

和主要活动=>

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;

        }

    }

}
4

1 回答 1

1

您可以使用AsyncTask. 在doinbackground()方法中,您为要首先执行的函数编写代码。完成第一个任务后,您可以使用onPostExecute()方法来执行您想要执行的任务。

于 2012-11-27T04:38:28.813 回答