如何刷新FragmentPagerAdapter内的listview,并在一个片段中添加数据,列表显示在另一个片段中

时间:2014-10-21 12:04:56

标签: android listview fragmentpageradapter

public class AllQuestions extends Fragment {

     ListView lstQuesions;
     QuestionsAdapter mAdapter;
    List<Question> questions;
     DataBaseHelper dbHelper;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View convertView = inflater.inflate(R.layout.all_questions_layout, container,false);
        lstQuesions = (ListView)convertView.findViewById(R.id.lstQuestions);
        dbHelper = new DataBaseHelper(getActivity());
        questions = dbHelper.getData();
        mAdapter = new QuestionsAdapter(getActivity().getApplicationContext(), R.layout.lst_all_questions, questions);
        lstQuesions.setAdapter(mAdapter);
        return convertView;
    }

    public void setDataToAdapter(){
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        mAdapter.notifyDataSetChanged();
    }


}

此处onResume() mAdapter.notifyDataSetChanged()显示null如果我对此行进行评论,那么它会成功运行并在启动后第一次完美显示列表。但是当我添加另一个输入时这里的数据库列表并不令人耳目一新。

我正在添加新项目

public void onClick(View v) {
    // TODO Auto-generated method stub
    switch(v.getId()){
    case R.id.btnSave :
            if(resetFields()){
                String question = edtQuestion.getText().toString();
                String OptionA = edtOptionA.getText().toString();
                String OptionB = edtOptionB.getText().toString();
                String OptionC = edtOptionC.getText().toString();
                String OptionD = edtOptionD.getText().toString();
                Calendar calender = Calendar.getInstance();
                Date now = calender.getTime();
                Timestamp currentTimeStamp = new Timestamp(now.getTime());
                Question questionObj = new Question();
                questionObj.setUserquestion(question);
                questionObj.setOpta(OptionA);
                questionObj.setOptb(OptionB);
                questionObj.setOptc(OptionC);
                questionObj.setOptd(OptionD);
                questionObj.setCurrentDateTime(currentTimeStamp.toString());
                dbHelper.addData(questionObj);
            }
        break;

2 个答案:

答案 0 :(得分:0)

使用onResume()方法创建适配器,而不是像{/ p>}那样创建onCreateView(...)

@Override
public void onResume() {
  // TODO Auto-generated method stub
  super.onResume();
  dbHelper = new DataBaseHelper(getActivity());
  questions = dbHelper.getData();
  mAdapter = new QuestionsAdapter(getActivity(), R.layout.lst_all_questions, questions);
  lstQuesions.setAdapter(mAdapter);
}

答案 1 :(得分:0)

AllQuestions aq =(AllQuestions)getFragmentManager()。findFragmentByTag(“android:switcher:”+ R.id.pager +“:”+ 2);                     aq.onResume();