简体   繁体   English

从 Activity 按下返回后,在 Fragment 中重新加载 ListView

[英]Reload a ListView inside a Fragment after press back from Activity

i have a Fragment that load a ListView from a database and it is a Favorite list which user choosed before, when you click on the list item it starts an Activity and user will be able to see the detail and unfavorite the item the problem is when the user unfavorite an item and press back to back to fragment of fave list the view is still shows the first lodaded listview not the updated one.我有一个从数据库加载 ListView 的片段,它是用户之前选择的收藏夹列表,当您单击列表项时,它会启动一个活动,用户将能够看到详细信息并取消收藏该项目的问题是什么时候用户不喜欢一个项目,然后按背靠背回到收藏列表的片段,视图仍然显示第一个加载的列表视图而不是更新的列表视图。 i want to know how the life cycle of fragment will work when you start an activity and come back again to know where to implement my我想知道当你开始一个活动时片段的生命周期将如何工作并再次回来知道在哪里实现我的

adapter.notifyDataSetChanged()

Im using GoogleApiClient to get the location of user so i use to load the database in my onConnected methode:我使用 GoogleApiClient 来获取用户的位置,所以我用来在我的 onConnected 方法中加载数据库:

    @Override
public void onConnected(@Nullable Bundle bundle) {

    LocationServices.FusedLocationApi.requestLocationUpdates(
            mLocationClient, mLocationRequest, this);

    if (    ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // You need to ask the user to enable the permissions
    } else {
        LocationTracker tracker = new LocationTracker(getContext()) {
            @Override
            public void onLocationFound(@NonNull Location location) {
                currentLocation = location;
            }
            @Override
            public void onTimeout() {
            }
        };
        tracker.startListening();
    }
    if (currentLocation ==null) {
        currentLocation = LocationServices.FusedLocationApi.getLastLocation(mLocationClient);
    }

    if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
                PERMISSION_ACCESS_COARSE_LOCATION);
    }
    if (currentLocation != null) {
        //Loading LAT LOng of //arkers on map
        for(int i=0; i<storedfavoritesitem.size(); i++) {
            FavoriteModel Faveitem = storedfavoritesitem.get(i);
            String locality = Faveitem.name;
            int id = Faveitem.id;
            double lat = Faveitem.lat;
            double lon =  Faveitem.lon;
            Location location = new Location("Beach");
            location.setLatitude(lat);
            location.setLongitude(lon);
            float distance = currentLocation.distanceTo(location);
            mResualt.add(new SearchResualtClass(id, distance / 1000, locality));
        }
        Comparator<SearchResualtClass > comperator = new Comparator<SearchResualtClass>()
        {
            @Override
            public int compare(SearchResualtClass  object1, SearchResualtClass  object2) {
                float First = object1.getDistance();
                float Second = object2.getDistance();
                return (First < Second ? -1 : (First == Second ? 0 : 1));
            }
        };
        Collections.sort(mResualt, comperator);
        adapter = new CustomAdapterSearch(getActivity().getApplicationContext(),mResualt);
        exList.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    exList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            Intent intent = new Intent(view.getContext(), FragmentBeach.class);
            intent.putExtra("array", jsonArray.toString());
            SearchResualtClass item = (SearchResualtClass) parent.getItemAtPosition(position);
            intent.putExtra("id", item.getId());
            startActivity(intent);
        }
    });
}

Move your code that loaded the datalist and feed it to adapter from onCreate() to onResume()移动加载数据列表的代码并将其提供给适配器从onCreate()onResume()

This will ensure your list will be reloaded whenever your fragment goes through pause-resume phase.这将确保您的列表在您的片段经历暂停-恢复阶段时重新加载。

And as far as lifecycle is concerned, do read [Fragment Lifecycles][**1]就生命周期而言,请阅读 [Fragment Lifecycles][**1]

Update : You will have to update storedfavoritesitem then run following piece of code更新:您必须更新storedfavoritesitem然后运行以下代码

if (currentLocation != null) {
        //Loading LAT LOng of //arkers on map
        for(int i=0; i<storedfavoritesitem.size(); i++) {
            FavoriteModel Faveitem = storedfavoritesitem.get(i);
            String locality = Faveitem.name;
            int id = Faveitem.id;
            double lat = Faveitem.lat;
            double lon =  Faveitem.lon;
            Location location = new Location("Beach");
            location.setLatitude(lat);
            location.setLongitude(lon);
            float distance = currentLocation.distanceTo(location);
            mResualt.add(new SearchResualtClass(id, distance / 1000, locality));
        }
        Comparator<SearchResualtClass > comperator = new Comparator<SearchResualtClass>()
        {
            @Override
            public int compare(SearchResualtClass  object1, SearchResualtClass  object2) {
                float First = object1.getDistance();
                float Second = object2.getDistance();
                return (First < Second ? -1 : (First == Second ? 0 : 1));
            }
        };
        Collections.sort(mResualt, comperator);
     if(adapter == null){
        adapter = new CustomAdapterSearch(getActivity().getApplicationContext(),mResualt);
        exList.setAdapter(adapter);
    }else{
        adapter.notifyDataSetChanged();
    }

adapter.notifyDataSetChanged() will surely work. adapter.notifyDataSetChanged() 肯定会工作。 You have to call activity using startActivityForResult method and pass resultCode before your called activity is finished.您必须使用 startActivityForResult 方法调用活动并在被调用的活动完成之前传递 resultCode。 Based on this resultCode, you can call adapter.notifyDataSetChanged().根据这个resultCode,你可以调用adapter.notifyDataSetChanged()。 Here is sample code.这是示例代码。 Pls replace accordingly.请相应更换。

startActivityForResult(intent, requestCode);

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == 1) {
        adapter.notifyDataSetChanged();
    }
}

Ok i solved it, i was notifyDataSetChanged but actually everything was loading from database so after i made change i should reload the list again from database and send the change notify so i implement the follwing code inside OnResume好的,我解决了,我是notifyDataSetChanged但实际上所有内容都是从数据库加载的,所以在我进行更改后,我应该再次从数据库重新加载列表并发送更改通知,以便我在OnResume实现以下代码

 @Override
public void onResume() {
    super.onResume();
    storedfavoritesitem = FavoriteModel.getAllFavorites();
    if (adapter!=null && currentLocation!=null) {
        mResualt.clear();
        for (int i = 0; i < storedfavoritesitem.size(); i++) {
            FavoriteModel Faveitem = storedfavoritesitem.get(i);
            String locality = Faveitem.name;
            int id = Faveitem.id;
            double lat = Faveitem.lat;
            double lon = Faveitem.lon;
            Location location = new Location("Beach");
            location.setLatitude(lat);
            location.setLongitude(lon);
            float distance = currentLocation.distanceTo(location);
            mResualt.add(new SearchResualtClass(id, distance / 1000, locality));
        }
        adapter.notifyDataSetChanged();
    }
  }
}

and it works fine now thanks every one现在一切正常,谢谢大家

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM