2012-11-27 26 views
0

我有兩個片段片段A和片段B.在兩個片段Iam中使用asynctask並在後臺運行一些函數。這些函數(用於解析XML和填充列表視圖)。當我啓動兩個片段中的應用函數時都運行在同一時間。所以應用程序變得緩慢。 我需要的是首先在片段A中運行函數。片段B中的函數只有在完成片段B中的函數後才能啓動。。我該如何實現?請提前一些一扶me.Thanks .....如何在Android的碎片背景中運行函數?

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

     } 

    } 

} 
+0

'AsyncTask'不是網絡工作的最佳場所。在隊列中處理網絡背景可以做的一件事是例如使用IntentService並將所有邏輯移動到那裏。使用網絡請求服務是Android的最佳實踐。您可以查看「Google I/O 2010 - Android REST客戶端應用程序」視頻。我認爲它會給你一些想法。 – Evos

回答

1

您可以使用AsyncTask。在doinbackground()方法中,您先爲要執行的函數編寫代碼。您可以使用onPostExecute()方法來完成完成第一個任務後要執行的任務。

+0

謝謝你的幫助。如果我有10個片段,那麼你的方法工作呢? –

+0

是的。你可以非常實現這個只是定義了10個方法。從'doInBackground()'方法調用每個方法,然後你可以調用postExecute方法中的最後一個過程 – NewUser

+0

有沒有什麼辦法讓我們可以把函數放在doinbackground中?我想按特定順序在後臺運行函數。 –