从数据库中删除项目后,更新Fragment中的Listview

时间:2015-09-11 22:57:43

标签: android database listview

删除项目后,我无法更新ListView中的Fragment。 我可以添加条目并通过

更新Listview
@Override
public void onResume(){
    super.onResume();
    getActivity().getSupportLoaderManager().getLoader(0).forceLoad();
}

但删除后,我需要滚动Fragments到远程内容丢失:

public boolean onContextItemSelected(MenuItem item) {
    if (item.getItemId() == 1) {
        // получаем из пункта контекстного меню данные по пункту списка
        AdapterView.AdapterContextMenuInfo acmi = (AdapterView.AdapterContextMenuInfo) item
                .getMenuInfo();
        db.deleteRow(acmi.id);
        getActivity().getSupportLoaderManager().getLoader(0).forceLoad();
        scAdapter.notifyDataSetChanged();
        return true;
    }
    return super.onContextItemSelected(item);
}

这里是所有代码

import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.*;
import android.view.*;
import android.widget.*;

import comzaqxs.vk.com.fucktheorientation.*;

public class MonthFragment extends Fragment implements LoaderCallbacks<Cursor> {

    public static final String[] months = { "Январь", "Февраль", "Март", "Апрель", "Май",
            "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь" };
    public static final String[] years = { "2015", "2016", "2017", "2018", "2019", "2020",
            "2021", "2022", "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030" };
    private static final int CM_DELETE_ID = 1;
    ListView lvMonth;
    DBAdapter db;
    SimpleCursorAdapter scAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.month_item, container, false);

        db = new DBAdapter(getActivity());
        db.open();
        String[] fromFieldNames = new String[] { DBAdapter.KEY_DATE, DBAdapter.KEY_AREA,
                DBAdapter.KEY_PASSENGER };
        int[] toViewsID = new int[] { R.id.tvItemDate, R.id.tvItemArea, R.id.tvItemPassenger };
        scAdapter = new SimpleCursorAdapter(getActivity(), R.layout.item, null,
                fromFieldNames, toViewsID, 0);

        lvMonth = (ListView) v.findViewById(R.id.lvMonth);
        lvMonth.setAdapter(scAdapter);
        lvMonth.setBackgroundColor(0xffFFFFFF);
        registerForContextMenu(lvMonth);
        getActivity().getSupportLoaderManager().initLoader(0, null, this);

        Spinner monthsSpinner = (Spinner) v.findViewById(R.id.monthSpinner);
        monthsSpinner.setBackgroundColor(0xffF44336);
        ArrayAdapter<String> monthsAdapter = new ArrayAdapter<>(getActivity(),
                R.layout.my_spinner_gravity_center, months);
        monthsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        monthsSpinner.setAdapter(monthsAdapter);

        monthsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // показываем позиция нажатого элемента МЕСЯЦ
                // Toast.makeText(getBaseContext(), "Position = " + position,
                // Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });

        Spinner yearSpinner = (Spinner) v.findViewById(R.id.yearSpinner);
        yearSpinner.setBackgroundColor(0xffF44336);
        ArrayAdapter<String> yearAdapter = new ArrayAdapter<>(getActivity(),
                R.layout.my_spinner_gravity_center, years);
        yearAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        yearSpinner.setAdapter(yearAdapter);

        yearSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // показываем позиция нажатого элемента МЕСЯЦ
                // Toast.makeText(getBaseContext(), "Position = " + position,
                // Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });

        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
        getActivity().getSupportLoaderManager().getLoader(0).forceLoad();
    }

    public void onDestroy() {
        super.onDestroy();
        db.close();
    }

    public static MonthFragment newInstance() {

        return new MonthFragment();
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle bndl) {
        return new MyCursorLoader(getActivity(), db);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        scAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
    }

    static class MyCursorLoader extends CursorLoader {

        DBAdapter db;

        public MyCursorLoader(Context context, DBAdapter db) {
            super(context);
            this.db = db;
        }

        @Override
        public Cursor loadInBackground() {
            return db.getMonthRows();
        }

    }

    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, CM_DELETE_ID, 0, R.string.delete_record);
    }

    public boolean onContextItemSelected(MenuItem item) {
        if (item.getItemId() == CM_DELETE_ID) {
            // получаем из пункта контекстного меню данные по пункту списка
            AdapterView.AdapterContextMenuInfo acmi = (AdapterView.AdapterContextMenuInfo) item
                    .getMenuInfo();
            // извлекаем id записи и удаляем соответствующую запись в БД
            db.deleteRow(acmi.id);
            // получаем новый курсор с данными
            getActivity().getSupportLoaderManager().getLoader(0).forceLoad();
            scAdapter.notifyDataSetChanged();
            return true;
        }
        return super.onContextItemSelected(item);
    }
}

1 个答案:

答案 0 :(得分:0)

我认为问题出在Array上,因为你无法从Array中删除元素。 我建议您尝试ArrayList,并在从适配器或数据库中删除它时从列表中删除该元素。然后调用adapter.notifyDataSetChanged();