2016-10-25 69 views
0

我有一個名爲HomeFragment.java的片段。這是我的應用程序打開時啓動的第一個片段。在這個片段中,我有一個名爲「onAsyncTaskDoInBackground」的方法,它使用JSON從服務器獲取所有數據。在Android片段保存實例

我想要做的是使用「savedInstanceState」,以便每次重新打開「HomeFragment.java」時不要重新下載所有數據。

例子:

用戶打開應用程序和Homefragment.java推出時,所有的數據被下載。用戶轉到關於我們的頁面並返回到Home頁面(Homefragment,java),所有數據都會再次下載。 (應該有無需重新下載同一應用程序啓動的所有數據)

HomeFragment.java

public class HomeFragment extends Fragment implements OnItemClickListener, OnClickListener, MainActivity.OnLocationListener { 

private View viewInflate; 
DisplayImageOptions options; 
ArrayList<Store> storeList; 
ArrayList<News> newsList; 
private ArrayList<News> arrayData; 
MGAsyncTask task; 
Queries q; 
private Store store; 
Random rand = new Random(); 


public HomeFragment() { } 

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

    viewInflate = inflater.inflate(R.layout.fragment_home, null); 
    return viewInflate; 


} 



@Override 
public void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
} 

@Override 
public void onDestroy() { 
    // TODO Auto-generated method stub 
    super.onDestroy(); 
    if(task != null) 
     task.cancel(true); 
} 



@Override 
public void onViewCreated(View view, Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onViewCreated(view, savedInstanceState); 
    options = new DisplayImageOptions.Builder() 
      .showImageOnLoading(UIConfig.SLIDER_PLACEHOLDER) 
      .showImageForEmptyUri(UIConfig.SLIDER_PLACEHOLDER) 
      .showImageOnFail(UIConfig.SLIDER_PLACEHOLDER) 
      .cacheInMemory(true) 
      .cacheOnDisk(true) 
      .considerExifParams(true) 
      .bitmapConfig(Bitmap.Config.RGB_565) 
      .build(); 

    storeList = new ArrayList<Store>(); 
    newsList = new ArrayList<News>(); 

    MainActivity main = (MainActivity) getActivity(); 

    timer(); 
    main.showSwipeProgress(); 
    main.getDebugKey(); 


    q = main.getQueries(); 
    if(MGUtilities.isLocationEnabled(getActivity())) { 
     if(MainActivity.location == null) { 
      main.setOnLocationListener(this); 
     } 
     else { 
      Handler h = new Handler(); 
      h.postDelayed(new Runnable() { 

       @Override 
       public void run() { 
        getData(); 
        arrayData = q.getNews(); 
       } 
      }, Config.DELAY_SHOW_ANIMATION); 
     } 
    } 
    else { 
     main.setOnLocationListener(this); 
    } 
} 


public void getData() { 
    task = new MGAsyncTask(getActivity()); 

    task.setMGAsyncTaskListener(new OnMGAsyncTaskListener() { 

     @Override 
     public void onAsyncTaskProgressUpdate(MGAsyncTask asyncTask) { 

     } 

     @Override 
     public void onAsyncTaskPreExecute(MGAsyncTask asyncTask) { 
      asyncTask.dialog.hide(); 

     } 

     @Override 
     public void onAsyncTaskPostExecute(MGAsyncTask asyncTask) { 
      // TODO Auto-generated method stub 

      arrayData = q.getNews(); 
      if(!MGUtilities.hasConnection(getActivity())) { 
       ArrayList<Store> stores = q.getStoresFeatured(); 
       ArrayList<News> news = q.getNews(); 
       if (Config.HOME_STORE_FEATURED_COUNT != -1 && Config.RANK_STORES_ACCORDING_TO_NEARBY) { 
        Log.v("myApp", "STORE SLIDER THING - STORE SLIDER THING - STORE SLIDER THING - STORE SLIDER THING - STORE SLIDER THING - STORE SLIDER THING - "); 

        int storeCount = stores.size() < Config.HOME_STORE_FEATURED_COUNT ? 
          stores.size() : Config.HOME_STORE_FEATURED_COUNT; 

        if (MainActivity.location != null) { 
         for (Store store : stores) { 
          Location locStore = new Location("Store"); 
          locStore.setLatitude(store.getLat()); 
          locStore.setLongitude(store.getLon()); 
          double userDistanceFromStore = MainActivity.location.distanceTo(locStore)/1000; 
          store.setDistance(userDistanceFromStore); 
         } 

         Collections.sort(stores, new Comparator<Store>() { 
          @Override 
          public int compare(Store store, Store t1) { 
           if (store.getDistance() < t1.getDistance()) 
            return -1; 
           if (store.getDistance() > t1.getDistance()) 
            return 1; 
           return 0; 
          } 
         }); 
        } 
        storeList = new ArrayList<Store>(); 
        for (int x = 0; x < storeCount; x++) { 

         storeList.add(stores.get(x)); 

        } 
       } else { 
        storeList = stores; 
       } 

       if (Config.HOME_NEWS_COUNT != -1 && Config.RANK_STORES_ACCORDING_TO_NEARBY) { 
        Log.v("myApp", "NEWS SLIDER THING - NEWS SLIDER THING - NEWS SLIDER THING - NEWS SLIDER THING - NEWS SLIDER THING - NEWS SLIDER THING - "); 

        int newsCount = news.size() < Config.HOME_NEWS_COUNT ? news.size() : Config.HOME_NEWS_COUNT; 
        newsList = new ArrayList<News>(); 
        for (int x = 0; x < newsCount; x++) { 
         newsList.add(news.get(x)); 
        } 
       } else { 
        newsList = news; 
       } 
      } 

      MainActivity main = (MainActivity) getActivity(); 
      main.hideSwipeProgress(); 
     } 

     @Override 
     public void onAsyncTaskDoInBackground(MGAsyncTask asyncTask) { 
      // TODO Auto-generated method stub 


      if(MGUtilities.hasConnection(getActivity()) && MainActivity.location != null) { 
       try { 
        UserAccessSession accessSession = UserAccessSession.getInstance(getActivity()); 
        String strUrl = ""; 

        if(accessSession.getFilterDistance() == 0) { 
         Log.v("myApp", "STRURL - STRURL - STRURL - STRURL - STRURL - STRURL - STRURL - STRURL - STRURL - STRURL - "); 
         if(MGUtilities.hasConnection(getActivity())) { 

          try { 

           strUrl = String.format("%s?api_key=%s", 
             Config.GET_CATEGORIES_JSON_URL, 
             Config.API_KEY); 

           DataParser parser = new DataParser(); 
           Data data = parser.getData(strUrl); 

           MainActivity main = (MainActivity) getActivity(); 
           if (main == null) 
            return; 

           Queries q = main.getQueries(); 
           if (data == null) 
            return; 

           q.deleteTable("categories"); 
           if (data.getCategories() != null && data.getCategories().size() > 0) { 
            Log.v("myApp", "CATEGORYS - CATEGORYS - CATEGORYS - CATEGORYS - CATEGORYS - CATEGORYS - CATEGORYS - CATEGORYS - "); 

            for (Category cat : data.getCategories()) { 
             q.insertCategory(cat); 
            } 
           } 

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

         strUrl = String.format("%s?api_key=%s&lat=%f&lon=%f&radius=%f&news_count=%d&featured_count=%d&default_store_count_to_find_distance=%d", 
           Config.GET_HOME_STORES_NEWS_JSON_URL, 
           Config.API_KEY, 
           MainActivity.location.getLatitude(), 
           MainActivity.location.getLongitude(), 
           accessSession.getFilterDistance(), 
           Config.HOME_NEWS_COUNT, 
           Config.HOME_FEATURED_COUNT, 
           Config.DEFAULT_STORE_COUNT_TO_FIND_DISTANCE); 
        } 
        else { 

         strUrl = String.format("%s?api_key=%s&lat=%f&lon=%f&radius=%f&news_count=%d&default_store_count_to_find_distance=%d", 
           Config.GET_HOME_STORES_NEWS_JSON_URL, 
           Config.API_KEY, 
           MainActivity.location.getLatitude(), 
           MainActivity.location.getLongitude(), 
           accessSession.getFilterDistance(), 
           Config.HOME_NEWS_COUNT, 
           Config.DEFAULT_STORE_COUNT_TO_FIND_DISTANCE); 
        } 

        DataParser parser = new DataParser(); 
        Data data = parser.getData(strUrl); 
        MainActivity main = (MainActivity) getActivity(); 
        if (main == null) 
         return; 

        Queries q = main.getQueries(); 
        if (data == null) 
         return; 

        if(Config.AUTO_ADJUST_DISTANCE) { 
         if(data.getMax_distance() > 0) { 
          UserAccessSession.getInstance(getActivity()).setFilterDistanceMax(data.getMax_distance()); 
         } 

         if(UserAccessSession.getInstance(getActivity()).getFilterDistance() == 0) { 
          UserAccessSession.getInstance(getActivity()).setFilterDistance(data.getDefault_distance()); 
         } 
        } 



        if (data.getStores() != null && data.getStores().size() > 0) { 
         Log.v("myApp", "ENTERED THE IF - ENTERED THE IF - ENTERED THE IF - ENTERED THE IF - ENTERED THE IF"); 

         int storeCount = data.getStores().size() < Config.HOME_STORE_FEATURED_COUNT ? 
           data.getStores().size() : Config.HOME_STORE_FEATURED_COUNT; 

         int x = 0; 
         for (Store store : data.getStores()) { 
          Location locStore = new Location("Store"); 
          locStore.setLatitude(store.getLat()); 
          locStore.setLongitude(store.getLon()); 
          double userDistanceFromStore = MainActivity.location.distanceTo(locStore)/1000; 
          store.setDistance(userDistanceFromStore); 
          if (userDistanceFromStore < 50){ 
           Log.v("myApp", "STORE - STORE - STORE - STORE - STORE - STORE - STORE - STORE - STORE - STORE - STORE- STORE"); 
           q.deleteStore(store.getStore_id()); 
           q.insertStore(store); 


           if(x < storeCount) { 
            Log.v("myApp", "if(x < storeCount) - if(x < storeCount)- if(x < storeCount)- if(x < storeCount)- if(x < storeCount)- if(x < storeCount)"); 

            if (store.getFeatured() == 3) { 
             storeList.add(store); 
             x += 1; 

            } 


           } 

           if (store.getPhotos() != null && store.getPhotos().size() > 0) { 
            Log.v("myApp", "PHOTOS - PHOTOS - PHOTOS - PHOTOS - PHOTOS - PHOTOS - PHOTOS - PHOTOS - PHOTOS - PHOTOS - PHOTOS - PHOTOS - PHOTOS"); 
            for (Photo photo : store.getPhotos()) { 
             q.deletePhoto(photo.getPhoto_id()); 
             q.insertPhoto(photo); 
            } 
           } 
          }} 


         if (data.getNews() != null && data.getNews().size() > 0) { 
          Log.v("myApp", "NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS"); 
          int newsCount = data.getNews().size() < Config.HOME_NEWS_COUNT 
            ? data.getNews().size() : Config.HOME_NEWS_COUNT; 

          x = 0; 
          for (News news : data.getNews()) { 
           q.deleteNews(news.getNews_id()); 
           q.insertNews(news); 

           if(x < newsCount) { 
            newsList.add(news); 
            x += 1; 
           } 
          } 
         }} 

        try { 
         strUrl = ""; 
         strUrl = String.format("%s?api_key=%s", 
           Config.GET_NEWS_JSON_URL, 
           Config.API_KEY); 
         Log.v("myApp", "NEWS UPDATE - NEWS UPDATE - NEWS UPDATE - NEWS UPDATE - NEWS UPDATE - NEWS UPDATE - NEWS UPDATE "); 

         parser = new DataParser(); 
         data = parser.getData(strUrl); 
         main = (MainActivity) getActivity(); 
         if (main == null) 
          return; 


         if (data == null) 
          return; 

         q.deleteTable("news"); 
         if (data.getNews() != null && data.getNews().size() > 0) { 
          for (News news : data.getNews()) { 
           q.insertNews(news); 
          } 
         } 

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

       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    }); 
    task.execute(); 
} 

@Override 
public void onDestroyView() { 
    super.onDestroyView(); 
    if (viewInflate != null) { 
     ViewGroup parentViewGroup = (ViewGroup) viewInflate.getParent(); 
     if (parentViewGroup != null) { 
      MGSlider slider = (MGSlider) viewInflate.findViewById(R.id.slider); 
      slider.pauseSliderAnimation(); 
      parentViewGroup.removeAllViews(); 
     } 
    } 

    handler.removeCallbacks(runnable); 
    if(task != null) 
     task.cancel(true); 
} 
Handler handler = new Handler(); 
int apple = 0; 

Runnable runnable = new Runnable() { 
    public void run() { 
     if(apple < 5) { 
      timer(); 
     } 
    } 
}; 

@Override 
public void onClick(View v) { 
    // TODO Auto-generated method stub 
    MGSlider slider = (MGSlider) viewInflate.findViewById(R.id.slider); 
    slider.stopSliderAnimation(); 
    switch(v.getId()) { } 
} 

@Override 
public void onResume() { 
    // TODO Auto-generated method stub 
    super.onResume(); 
    MGSlider slider = (MGSlider) viewInflate.findViewById(R.id.slider); 
    slider.resumeSliderAnimation(); 
} 

@Override 
public void onPause() { 
    // TODO Auto-generated method stub 
    super.onPause(); 
    MGSlider slider = (MGSlider) viewInflate.findViewById(R.id.slider); 
    slider.pauseSliderAnimation(); 
} 

@Override 
public void onLocationChanged(Location prevLoc, Location currentLoc) { 
    MainActivity main = (MainActivity) getActivity(); 
    main.setOnLocationListener(null); 
    getData(); 
} 

} 
+0

每次你的onViewCreated被調用它開始加載數據。所以,你可以使用一個簡單的布爾標誌爲它,並防止未來的數據加載 – Sayem

+0

謝謝,但不工作,它顯示主屏幕上沒有內容 –

回答

0

你可以這樣做以下。

private View viewFragment; 
private ArrayList<MyClass> list = new ArrayList<>(); 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    viewFragment = inflater.inflate(R.layout.fragment_layout, container, false); 
    initIds(); 

    if (savedInstanceState == null) { 
     // get all data and saved in list. 
    } else { 
     // use saved list or other data here... 
     list = savedInstanceState.getParcelableArrayList("arraylist"); 
     setListAdapter(list); 
    } 

    return viewFragment; 
} 

@Override 
public void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    outState.putParcelableArrayList("arraylist", list); 
} 
+0

我試圖添加此代碼,但不斷收到多個錯誤。 –

+0

getParcelableArrayList不適用於我 –

+0

@QuickyApp使'MyClass實現Parcelable'它將工作 –