在自定义适配器中更改DB时刷新列表和适配器

时间:2014-08-14 07:38:10

标签: android-fragments

我的项目是todo 我有4个选项卡,4个片段和4个列表(操作栏导航包含4个选项卡和ViewPager)。 4 list(tab)使用相同的db表,但每个都使用categoryID检索不同的数据。 我为所有这些使用Asynctask,读取数据并将适配器设置为列表。

public class AsyncTaskDB extends AsyncTask<Void, Void, listAdapter> {

Context act;
int Categoryid;
ArrayList<memo> arraymemo;
listAdapter myadapter;
ListView list;
listAdapter listAdp;



public AsyncTaskDB(Context acti, int categoryID) {
    this.act = acti;
    this.Categoryid = categoryID;

}

@Override
protected listAdapter doInBackground(Void... params) {
    MemoDBHelper helper = new MemoDBHelper(act);

    // getAllDataByCategoryID
    if (Categoryid != CategoryID.Done_ID)
        arraymemo = helper.getAllTaskByCategory(Categoryid);
    else
        arraymemo = (ArrayList<memo>) helper.gatDoneMemo();



    myadapter = new listAdapter(act, arraymemo);
    if (myadapter == null) {
        Toast.makeText(act, "no data", Toast.LENGTH_SHORT).show();
        cancel(true);
    }
    return myadapter;

}

@Override
protected void onPostExecute(listAdapter result) {

    switch (Categoryid) {
    case CategoryID.Urgent_Imprtant_ID:
        list = (ListView) ((Activity) act)
                .findViewById(R.id.Urgent_Important_list);

                    break;

    case CategoryID.Urgent_Less_Imprtant_ID:
        list = (ListView) ((Activity) act)
                .findViewById(R.id.Urgent_Less_Important_list);

        break;
    case CategoryID.Less_Urgent_Imprtant_ID:
        list = (ListView) ((Activity) act)
                .findViewById(R.id.Less_Urgent_Imprtant_list);

        break;

    case CategoryID.Neither_Urgent_Or_Imprtant_ID:
        list = (ListView) ((Activity) act)
                .findViewById(R.id.Neither_Urgent_Imprtant_list);

        break;
    case CategoryID.Done_ID:

        list = (ListView) ((Activity) act).findViewById(R.id.ArchiveList);
        break;
    }
    list.setAdapter(result);
    this.listAdp = result;

}

public listAdapter getlistAdapter() {
    return this.listAdp;
}

}

列表中的每个备忘录都有D​​one CheckBox。当用户检查并取消选中它时,自动备忘录更新db。(在自定义适配器中)

 ----------------------------
|   --                      |
|  |  |          memotitle  |
|   --                      |
----------------------------  



public class listAdapter extends BaseAdapter implements OnCheckedChangeListener { Context act;
ArrayList<memo> MemoArray;
SparseBooleanArray mcheck;
int pos;
MemoDBHelper helper;

public listAdapter(Context activity, ArrayList<memo> memoarray) {
    this.act = activity;
    this.MemoArray = memoarray;
    mcheck = new SparseBooleanArray(memoarray.size());
    helper = new MemoDBHelper(act);
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return MemoArray.size();
}

@Override
public memo getItem(int position) {
    // TODO Auto-generated method stub
    return MemoArray.get(position);
}

@Override
public long getItemId(int arg0) {
    // TODO Auto-generated method stub
    return 0;
}

public class viewHolder {
    TextView title;
    // TextView description;
    CheckBox chkstatus;
}

viewHolder it;

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    pos = position;
    LayoutInflater in = ((Activity) act).getLayoutInflater();
    if (convertView == null) {
        convertView = in.inflate(R.layout.list_item, null);

        it = new viewHolder();
        it.title = (TextView) convertView.findViewById(R.id.txt_list_title);
        it.chkstatus = (CheckBox) convertView
                .findViewById(R.id.chkStatusid);

        convertView.setTag(it);
    } else {
        it = (viewHolder) convertView.getTag();

    }

    it.title.setText(MemoArray.get(position).GetTitle());
    it.chkstatus.setChecked(MemoArray.get(position).GetSattus());
    it.chkstatus.setOnCheckedChangeListener(this);
    it.chkstatus.setTag(String.valueOf(MemoArray.get(position).GetID()));
    return convertView;
}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    mcheck.put(Integer.valueOf((String) buttonView.getTag()), isChecked);
    helper.updateStatusByID(Integer.valueOf((String) buttonView.getTag()),
            (isChecked));
    helper.close();
   //after db updatedt ,call method in fragment to notifydatsetchanged!
    UrgentImportant_frg.notifyAdapter();


}

}

适配器必须通知已更改的数据,并且列表不显示已完成的备忘录。我不知道如何操作! 我的第一个片段:

public class UrgentImportant_frg extends Fragment {
static listAdapter myadp;
ListView list;
// memo selectedmemo;
long[] checkid;
AsyncTaskDB asyn;
ArrayList<memo> selectedMemoArray;
final static int RQS_MoveTo = 10;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootview = inflater.inflate(R.layout.urgentimportant_layout,
            container, false);
    return rootview;
}


@Override
public void onActivityCreated(Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);
    list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    selectedMemoArray = new ArrayList<memo>();
    list.setMultiChoiceModeListener(new MultiChoiceModeListener() {

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {

            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {

            // list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);

        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {

            mode.getMenuInflater().inflate(R.menu.list_select_menu, menu);
            /*
             * MenuInflater inflater = getActivity().getMenuInflater();
             * inflater.inflate(R.menu.list_select_menu, menu);
             */

            mode.setTitle("Select Items");
            return true;
        }

        @Override
        public boolean onActionItemClicked(final ActionMode mode,
                MenuItem item) {

            switch (item.getItemId()) {
            case R.id.deletemenu:

                final int[] myitemsid = getSelectedID();
                final MemoDBHelper helper = new MemoDBHelper(getActivity());
                AlertDialog.Builder myAlert = new AlertDialog.Builder(
                        getActivity());
                myAlert.setMessage(
                        "Are you sure to delete " + myitemsid.length
                                + " memo ?")
                        .setPositiveButton("yes", new OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {

                                for (int j = 0; j < myitemsid.length; j++) {
                                    helper.deleteRow(myitemsid[j]);
                                    /*
                                     * if (j == myitemsid.length - 1) {
                                     * strid[j] = String
                                     * .valueOf(myitemsid[j]); } else {
                                     * strid[j] = String
                                     * .valueOf(myitemsid[j]) + ","; }
                                     */
                                }

                                mode.finish();
                                onResume();
                            }
                        }).setNegativeButton("no", new OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                mode.finish();

                            }
                        });
                AlertDialog alert = myAlert.create();
                alert.show();
                // mode.finish();

                break;
            case R.id.MoveTomenu:

                // myadp.getItem(position);
                Intent i = new Intent(getActivity(),
                        MoveToCategory_act.class);
                i.putExtra("categoryid", CategoryID.Urgent_Imprtant_ID);
                startActivityForResult(i, RQS_MoveTo);
                mode.finish();
                break;
            }
            return true;
        }

        // get selected id to delete and move category

        @Override
        public void onItemCheckedStateChanged(ActionMode mode,
                int position, long id, boolean checked) {
            if (myadp == null) {
                myadp = asyn.getlistAdapter();
            }

            int p = ifMemoSelectedBefore(myadp.getItem(position));
            if (p != -1) {

                selectedMemoArray.remove(p);

            } else if (checked) {
                selectedMemoArray.add(myadp.getItem(position));

            }
            final int checkedCount = list.getCheckedItemCount();
            switch (checkedCount) {
            case 0:
                mode.setSubtitle(null);
                break;

            case 1:
                mode.setSubtitle("One Item Selected");
                break;
            default:
                mode.setSubtitle(checkedCount + " Item Selected");
                break;
            }
        }
    });

    getActivity().getActionBar().setSubtitle("subtitle");
}

public int ifMemoSelectedBefore(memo m) {
    return selectedMemoArray.indexOf(m);

}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onViewCreated(view, savedInstanceState);

    list = (ListView) view.findViewById(R.id.Urgent_Important_list);

    // -------------click item
    list.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            if (myadp == null) {
                myadp = asyn.getlistAdapter();
            }
            // Log.d("tag", myadp.getItem(position).GetTitle() + "");
            Intent nextintent = new Intent(getActivity(),
                    EditMemo_act.class);
            memo g = myadp.getItem(position);
            /*
             * MemoDBHelper helper = new MemoDBHelper(getActivity());
             * helper.updateStatusByID(g.GetID(), true);
             */
            nextintent.putExtra("editmemo", g);
            startActivity(nextintent);

        }
    });

}

@Override
public void onResume() {
    asyn = new AsyncTaskDB(getActivity(), CategoryID.Urgent_Imprtant_ID);
    asyn.execute();
    super.onResume();
}

public int[] getSelectedID() {
    int[] SelectedArray_ID = new int[selectedMemoArray.size()];
    for (int j = 0; j < selectedMemoArray.size(); j++) {

        SelectedArray_ID[j] = selectedMemoArray.get(j).GetID();
        // Log.d("id", selectedMemoArray.get(j).GetID() + "");

    }
    return SelectedArray_ID;
}

// -------------一个通知myadpter的方法     public static void notifyAdapter(){         if(myadp!= null){             myadp.notifyDataSetChanged();             Log.d(&#34; notify&#34;,&#34; here&#34;);         }

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RQS_MoveTo) {
        if (resultCode == Result.RESULT_OK) {

            int id = data.getExtras().getInt("NEWCategoryID");
            MemoDBHelper helper = new MemoDBHelper(getActivity());
            final int[] myitemsid = getSelectedID();
            for (int j = 0; j < myitemsid.length; j++) {
                helper.updateCategory(myitemsid[j], id);

            }

            onResume();

        }
    }
}

}

在适配器更改后是否有片段中的任何方法运行?或者在myadapter中,db更新后我调用片段中的方法来通知数据已更改?我认为第二种解决方案并非正确&gt; _&lt;

p.s:notifyAdapter()不起作用,是因为我的适配器填写了asyntask吗?

1 个答案:

答案 0 :(得分:1)

当适配器发生变化时,请尝试调用以下方法。

使用FragmentPagerAdapter或ListView后,当您更改数据时,应该调用它。

notifyDataSetChanged();

了解它:notifyDataSetChanged