在片段持有者中切换片段后,列表视图清空



我的一个片段中有一个列表视图,当我离开该片段时它会清空。

为什么会这样?

那个片段:

public class ListActivity extends ListFragment {
    public void ToastLoadShout(String msg) {
        Toast.makeText(getActivity(), msg.toString(), Toast.LENGTH_LONG).show();
    }
    private static View View;
    HttpClient client;
    HttpPost httppost;
    HttpGet httpget;
    JSONObject json;
    List<List<String>> items;
    List<item> markers = new ArrayList<item>();
    MobileArrayAdapter adapter;
    ListView list;
    ProgressBar listload;
    Button relist;
    Preferences pref;
    String datadata = "";
    String savedlat="0.0";
    String savedlon="0.0";
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_list, container, false);
    }
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true); 

    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setRetainInstance(true); 
        try {
            pref = new Preferences(getActivity());
            list = (ListView) getView().findViewById(android.R.id.list);
            listload = (ProgressBar) getView().findViewById(R.id.listload);
            HashMap<String, String> loc = pref.getData();
            ToastLoadShout(loc.get(Preferences.LAT) + ","
                    + loc.get(Preferences.LON));
            if (loc.get(Preferences.LAT) != "0.0" && loc.get(Preferences.LAT) != null)
            {
                //adapter.deleteList();
                //list.destroyDrawingCache();
                if (loc.get(Preferences.LAT) != savedlat && loc.get(Preferences.LON)!=savedlon){
                new Load().execute();
                savedlat=loc.get(Preferences.LAT);
                savedlon=loc.get(Preferences.LON);
                }
            }
            else
                ToastLoadShout("Get Location First.");
            relist = (Button) getView().findViewById(R.id.relist);
            relist.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    listload.setVisibility(View.INVISIBLE);
                    HashMap<String, String> loc = pref.getData();
                    ToastLoadShout(loc.get(Preferences.LAT) + ","
                            + loc.get(Preferences.LON));
                    if (loc.get(Preferences.LAT) != "0.0" && loc.get(Preferences.LAT) != null){
                        adapter.deleteList();
                        list.destroyDrawingCache();
                        new Load().execute();}
                    else
                        ToastLoadShout("Get Location First.");
                }});
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // get selected items
        //String selectedValue = (String) getListAdapter().getItem(position);
        String selectedValue = markers.get(position).getTitle();
        Toast.makeText(getActivity(), selectedValue, Toast.LENGTH_SHORT).show();
    }
}

以及保存片段的主活动:

public class Fragments extends FragmentActivity {
    Fragment newFragment;
    Button Add;
    public void ToastLoadShout(String msg) {
        Toast.makeText(this, msg.toString(), Toast.LENGTH_SHORT).show();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragments);
        //Set Custom actionBar<
        getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getActionBar().setCustomView(R.layout.titlebar);
        getActionBar().setHomeButtonEnabled(true);
        getActionBar().setDisplayHomeAsUpEnabled(true);
        //Set Custom actionBar>
        ListActivity fragment = new ListActivity();
        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();
        transaction.add(R.id.fragment_place, fragment,"Nearby");
        transaction.commit();
        turnGPSOn();
         Add = (Button)findViewById(R.id.add);
         Add.setOnClickListener(new OnClickListener() {
         public void onClick(View v) {
         Intent Intent = new Intent(Fragments.this,Add.class);
         Bundle bndlanimation =
         ActivityOptions.makeCustomAnimation(getApplicationContext(),
         R.anim.animation,R.anim.animation2).toBundle();
         startActivity(Intent, bndlanimation);
         }
         });
         /* For putting commas in attractin's checkIns
         String number = "1345";
         int amount = Integer.parseInt(number);
         DecimalFormat formatter = new DecimalFormat("#,###");
         ToastLoadShout(formatter.format(amount));*/
    }
    public void onSelectFragment(View view) {
        String fragTag="";
        boolean needNew=false;
         if (view == findViewById(R.id.map)) 
            {
            Fragment f = getSupportFragmentManager().findFragmentByTag("Map");
            if (f==null){
                newFragment = new MainActivity();
                needNew=true;
                fragTag="Map";
            }
            else{
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.fragment_place, f, "Map"); //or whatever other string you want to use
            transaction.addToBackStack(null);
            transaction.commit();
            }
        }
         else if (view == findViewById(R.id.nearby)) 
            {
            Fragment f = getSupportFragmentManager().findFragmentByTag("Nearby");
            if (f==null){
                newFragment = new ListActivity();
                needNew=true;
                fragTag="Nearby";
            }
            else{
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.fragment_place, f, "Nearby"); //or whatever other string you want to use
            transaction.addToBackStack(null);
            transaction.commit();
            }
        }

        if (needNew) {
            FragmentTransaction transaction = getSupportFragmentManager()
                    .beginTransaction();
            transaction.replace(R.id.fragment_place, newFragment, fragTag);
            transaction.addToBackStack(null);
            transaction.commit();
        }
    }
}

已经尝试在OnCreate上加载列表。根本不起作用。

感谢您的帮助。

编辑:

负载类:

class Load extends AsyncTask<String, Integer, Boolean> {
        @Override
        protected void onPreExecute() {
            listload.setVisibility(View.VISIBLE);
        }
        @Override
        protected Boolean doInBackground(String... params) {
            try {
                items = DownloadList();
                if (items != null)
                    return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
            return false;
        }
        @Override
        protected void onPostExecute(Boolean res) {
            // TODO Auto-generated method stub
            if (res) {
                ArrangePutMarkers();
                adapter=new MobileArrayAdapter(getActivity(), markers);
                list.setAdapter(adapter);
            } else {
                ToastLoadShout("Error");
                ToastLoadShout(datadata);
            }
            listload.setVisibility(View.INVISIBLE);
        }
    }

正如我所看到的,每次显示片段时您都会重新创建 loc 对象。它显然会让您分段以重新加载数据。

将适配器作为字段保持在活动中。当你离开碎片时,摧毁它中的所有东西是很正常的事情。 setRetainInstance()仅适用于配置更改,例如屏幕旋转。每次返回片段时重新创建列表(例如,在onActivityCreated()中,就像您知道的那样),并为其提供存储的适配器,其中包含保存的数据。您可以访问片段内的活动,例如,通过强制转换 (MainActivity)getActivity() ,因为在这种情况下传递给此片段的Activity实际上是您的活动。

最新更新