在Android片段中保存实例

时间:2016-10-25 13:08:43

标签: android android-asynctask android-savedstate

我有一个名为HomeFragment.java的片段。这是我的应用程序打开时启动的第一个片段。在这个片段中,我有一个名为“onAsyncTaskDoInBackground”的方法,它使用JSON从服务器获取所有数据。

我要做的是使用“savedInstanceState”,这样每次重新打开“HomeFragment.java”时都不会重新下载所有数据。

示例:

用户打开应用程序并启动Homefragment.java,下载所有数据。用户转到about us页面并返回主页(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();
}

}

1 个答案:

答案 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);
}