回到片段时重新加载ListView

时间:2015-03-25 20:02:46

标签: android listview android-fragments

我的应用主要活动是带有TabHost的FragmentActivity。第一个选项卡有一个片段,列表视图中填充了Parse中的对象。从列表中选择项目时,将加载新活动以及该项目的详细信息,并且用户可以将项目标记为已完成。当他们通过点击后退按钮返回列表视图时,我希望重新加载数据。我怎么能这样做?

MainActivity:

public class MainActivity extends FragmentActivity {
    private FragmentTabHost mTabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        mTabHost.addTab(mTabHost.newTabSpec("Unassigned").setIndicator("", getResources().getDrawable(R.drawable.unassigned)), UnassignedJobsFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("Assigned").setIndicator("", getResources().getDrawable(R.drawable.assigned)), AssignedJobsFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("Completed").setIndicator("", getResources().getDrawable(R.drawable.completed)), CompletedJobsFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("My Jobs").setIndicator("", getResources().getDrawable(R.drawable.myjobs)), MyJobsFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("Users").setIndicator("", getResources().getDrawable(R.drawable.users)), Users.class, null);
    }
}

列表片段:

public class UnassignedJobsFragment extends Fragment {
    private ImageButton mAddJobButton;
    ProgressBar mUnassignedProgress;
    ListView listView;
    List<ParseObject> object;
    List<String> objectIds;
    ArrayAdapter<String> adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_unassigned, container, false);
        mAddJobButton = (ImageButton)v.findViewById(R.id.addJobButton);
        mUnassignedProgress = (ProgressBar)v.findViewById(R.id.unassignedProgress);
        listView = (ListView)v.findViewById(R.id.unassignedList);
        adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), R.layout.job_list_item);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ParseObject selectedObject = object.get(position);
                String objectId = objectIds.get(position);
                String jobTitle = selectedObject.getString("job");
                String worker = selectedObject.getString("worker");
                String details = selectedObject.getString("details");

                Date jobDate = selectedObject.getDate("date");
                SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy hh:mm");
                String dateString = dateFormat.format(jobDate);

                Boolean accessedFromMyJobs = false;

                Intent intent = new Intent(getActivity(), DetailActivity.class);
                intent.putExtra("OBJECT_ID", objectId);
                intent.putExtra("JOB_TITLE", jobTitle);
                intent.putExtra("WORKER", worker);
                intent.putExtra("DETAILS", details);
                intent.putExtra("DATE", dateString);
                intent.putExtra("FROM_MY_JOBS", accessedFromMyJobs);
                startActivity(intent);
            }
        });

        ParseUser currentUser = ParseUser.getCurrentUser();
        String fullName = currentUser.get("Name").toString();
        if (fullName.equals("Cory Pollard") || fullName.equals("Richie Ray")) {
            mAddJobButton.setVisibility(View.VISIBLE);
        }
        else {
            mAddJobButton.setVisibility(View.GONE);
        }

        getJobs();

        return v;
    }

    public void getJobs() {
        mUnassignedProgress.setVisibility(View.VISIBLE);

        ParseQuery<ParseObject> query = ParseQuery.getQuery("Jobs");
        query.setLimit(1000);
        query.whereEqualTo("assigned", "no");
        query.findInBackground(new FindCallback<ParseObject>() {
            @Override
            public void done(List<ParseObject> parseObjects, ParseException e) {
                if (e == null) {
                    object = new ArrayList<ParseObject>();
                    objectIds = new ArrayList<String>();

                    mUnassignedProgress.setVisibility(View.GONE);

                    for (ParseObject job : parseObjects) {
                        object.add(job);
                        objectIds.add(job.getObjectId().toString());
                    }

                    for (ParseObject job : object) {
                        adapter.add((String) job.getString("job"));
                    }

                    adapter.notifyDataSetChanged();
                }
                else {
                    mUnassignedProgress.setVisibility(View.GONE);
                    String exception = e.getMessage().toString();
                    Toast.makeText(getActivity().getApplicationContext(), exception, Toast.LENGTH_LONG);
                }
            }
        });
    }
}

3 个答案:

答案 0 :(得分:1)

实现onSaveInstanceState并保存任何或所有需要恢复的对象,然后你可以在你的oncreate中获取这些对象,在你的情况下它是oncreateview。

这是一个如何完成的例子,

@Override
  protected void onSaveInstanceState(Bundle bundle) 
  {
    super.onSaveInstanceState(bundle);
    bundle.putStringArrayList("My List" , listArray);
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

  if(savedInstanceState!=null)
  {
    listArray = savedInstanceState.getStringArrayList("My List");
  }

答案 1 :(得分:1)

我通过使用@krishna建议的onResume()来解决这个问题。我在这里设置适配器而不是onCreate()。

public void onResume() {
        super.onResume();
        object = null;
        objectIds = null;
        adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), R.layout.job_list_item);
        listView.setAdapter(adapter);
        getJobs();
    }

答案 2 :(得分:0)

SharedPreferences是最佳实现。

第二次活动

//after entry has been successfully made 
SharedPreferences sharedpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()):
SharedPreferences.Editor editor = SharedPreferences. edit();
editor. putBoolean("refresh_fragment_listview", true); 
editor. commit();

在片段中

@Override
public void onResume() {
    super.onResume();

    SharedPreferences sharedpref = PreferenceManager.getDefaultSharedPreferences(getActivity()):
    String refreshValue sharedpref.getBoolean("refresh_fragment_listview", false) :
    if (refreshValue.equals("true") {
        //reset the value to false to prevent refresh each time
        //fragment is resumed
        SharedPreferences.Editor editor = SharedPreferences. edit();
        editor. putBoolean("refresh_fragment_listview", true); 
        editor. commit();

        //add methods to refresh the listview below
    }
}