2014-02-07 98 views
0

我已經創建了action barviewpager,我有三個fragment。每個fragment I parsed json並且可以顯示每個listview。我的問題是:如果我clickfragment,然後我回去(click冷杉fragmet),當我去到下一個fragment,然後如果我去前面fragment在這種情況下,從server加載信息中出現了兩次,我用AsyncTask類從server加載信息。Android json viewpager操作欄fragmentpageadapter

下面是我的代碼:

public class TabsPagerAdapter extends FragmentPagerAdapter { 

public TabsPagerAdapter(FragmentManager fm) { 
    super(fm); 
} 

@Override 
public Fragment getItem(int index) { 

    switch (index) { 
    case 0: 

     return new SendItemsFragment(); 
    case 1: 

     return new RecivedItemsFragment(); 
    case 2: 

     return new FavoriteItemsFragment(); 

    } 

    return null; 
} 

@Override 
public int getCount() { 

    return 3; 
} 

public class MainActivity extends FragmentActivity implements TabListener { 

private ViewPager viewPager; 
private TabsPagerAdapter mAdapter; 
private ActionBar actionBar; 
private String[] tabs = { "test1", "test2", "test3" }; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    actionBar = getActionBar(); 
    actionBar.setHomeButtonEnabled(false); 
    actionBar.setDisplayHomeAsUpEnabled(true); 
    actionBar.setDisplayShowHomeEnabled(false); 
    actionBar.setDisplayShowTitleEnabled(false); 
    actionBar.setIcon(R.color.white); 
    actionBar.setDisplayShowTitleEnabled(true); 
    Drawable d = getResources().getDrawable(R.drawable.acttitle); 
    getActionBar().setBackgroundDrawable(d); 

    mAdapter = new TabsPagerAdapter(getSupportFragmentManager()); 

    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM 
      | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE); 

    viewPager = (ViewPager) findViewById(R.id.vp_main); 
    viewPager.setAdapter(mAdapter); 

    getActionBar().setCustomView(R.layout.menu_example); 
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM 
      | ActionBar.DISPLAY_SHOW_HOME); 
    for (String tab_name : tabs) { 
     actionBar.addTab(actionBar.newTab().setText(tab_name) 
       .setTabListener(this)); 
    } 

    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { 

     @Override 
     public void onPageSelected(int position) { 

      actionBar.setSelectedNavigationItem(position); 
     } 

     @Override 
     public void onPageScrolled(int arg0, float arg1, int arg2) { 
     } 

     @Override 
     public void onPageScrollStateChanged(int arg0) { 
     } 
    }); 

    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 

    // actionBar.setStackedBackgroundDrawable(getResources().getDrawable(
    // R.drawable.background)); background viewpager 

} 

@Override 
public void onTabReselected(Tab tab, FragmentTransaction ft) { 
} 

@Override 
public void onTabSelected(Tab tab, FragmentTransaction ft) { 

    viewPager.setCurrentItem(tab.getPosition()); 
} 

@Override 
public void onTabUnselected(Tab tab, FragmentTransaction ft) { 
} 
    } 

這是 - 片段的代碼之一。類似於他們三人。唯一的區別是來自服務器的數據加載,並且還使用AsyncTask類,每個類都有不同。

public class SendItemsFragment extends Fragment { 
private String URL = "*******************************************"; 

public static String KEY_title = "title"; 
public static String KEY_description = "description"; 
public static String KEY_image = "image"; 
public static String KEY_journal = "journal"; 
public static String KEY_JournalID = "JournalID"; 
public static String KEY_pubDate = "pubDate"; 
public static String KEY_statID = "statID"; 
public JSONArray jsonarray; 
public ListView list; 
public TransparentProgressDialog pd; 
public JSONParser jsonparser; 
static DealBoxAdapter adapter; 
ProgressDialog pDialog, pDialog1; 
static String fontPath2 = "font.ttf"; 
public static Typeface tf2; 
ArrayList<HashMap<String, String>> itemList = new ArrayList<HashMap<String, String>>(); 
public ImageLoader imageLoader; 
static final int DIALOG_ERROR_CONNECTION = 1; 
private int screenSize; 
private LoadDataAllChanelsToServer loader; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 

    View rootView = inflater.inflate(R.layout.send_items, container, false); 
    list = (ListView) rootView.findViewById(R.id.listView1); 
    pd = new TransparentProgressDialog(getActivity(), R.drawable.loader); 
    screenSize = getResources().getConfiguration().screenLayout 
      & Configuration.SCREENLAYOUT_SIZE_MASK; 
    loader=new LoadDataAllChanelsToServer(); 

    loader.execute(); 
    return rootView; 
} 

private class LoadDataAllChanelsToServer extends 
     AsyncTask<String, Integer, String> { 

    @Override 
    protected void onPreExecute() { 

     pd.show(); 
    } 

    @Override 
    protected String doInBackground(String... urls) { 

     jsonparser = new JSONParser(); 

     JSONObject jsonobject = jsonparser.getJSONfromURL(URL); 
     try { 

      jsonarray = jsonobject.getJSONArray("data"); 

      for (int i = 0; i < jsonarray.length(); i++) { 
       jsonobject = jsonarray.getJSONObject(i); 

       HashMap<String, String> map = new HashMap<String, String>(); 

       map.put("journal", jsonobject.getString(KEY_journal)); 
       map.put("image", jsonobject.getString(KEY_image)); 
       map.put("title", jsonobject.getString(KEY_title)); 
       map.put("description", 
         jsonobject.getString(KEY_description)); 
       map.put("JournalID", jsonobject.getString(KEY_JournalID)); 
       map.put("pubDate", jsonobject.getString(KEY_pubDate)); 
       map.put("statID", jsonobject.getString(KEY_statID)); 

       itemList.add(map); 

      } 

     } catch (JSONException e) { 
      Log.e("Error", e.getMessage()); 
      e.printStackTrace(); 
     } 

     return itemList.toString(); 

    } 

    @Override 
    protected void onPostExecute(String result) { 
     try { 
      if (pd != null) { 
       pd.dismiss(); 

      } 
     } catch (Exception e) { 

     } 

     try { 
      adapter = new DealBoxAdapter(getActivity(), itemList, 
        screenSize); 
      list.setAdapter(adapter); 

     } catch (NullPointerException e) { 
      e.printStackTrace(); 
     } 

    } 

} 
    } 

這是所有:) 如果有人知道的解決方案,請幫助我 謝謝

回答

0

您應該取消異步任務時,你Fragment被破壞。

private LoadDataAllChanelsToServer mLoader; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
    Bundle savedInstanceState) { 
    ... 
    mLoader = new LoadDataAllChanelsToServer(); 
    mLoader.execute(); 
    ... 
} 

@Overide 
public onDestroy() { 
    super.onDestroy(); 

    if(mLoader != null) { 
     mLoader.cancel(true); 
     mLoader = null; 
} 

這樣,當片段被銷燬AsyncTask將被取消。您也可以設置ViewPager.setOffscreenPageLimit(2)。這樣,由於您只有3 Fragments,因此不會破壞Fragments,因此您的onViewCreated只會被調用一次。

+0

我加了這個onDestroy方法,但是我只有第一個片段有問題 – user3272799

+0

我的不好。我的答案的第一部分應該解決'postExecute'中不必要的'try cache'塊。你嘗試過'ViewPager.setOffscreenPageLimit(2)'。如果我正確理解你的問題,這應該是解決方案。 – Blaz

+0

我不明白你我添加onDestroy方法只與try catch,我不明白是什麼意思ViewPager.setOffscreenPageLimit(2)。這意味着我可以添加此? – user3272799