Обновление списка Android OrmLite при удалении - PullRequest
2 голосов
/ 11 марта 2012

Я пытаюсь обновить свой вид, когда элемент в списке удаляется.В настоящее время я пытаюсь обновить / перезагрузить представление в методе OnPostExecute AsyncTask.Пока что ничего, что я пробовал, не сработало.Казалось бы, это простая задача для выполнения.Мой пользовательский адаптер расширяет BaseAdapter.Я надеюсь, что что-то простое мне не хватает.Может кто-нибудь пролить свет ??

Приветствия.

public class ItemListActivity extends OrmLiteBaseListActivity<DatabaseHelper>  {

    private final String TAG = getClass().getSimpleName();
    private DatabaseHelper dbHelper;
    private ListView itemListView;
    private ItemListAdapter listAdapter;
    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.itemslistactivity);
        registerForContextMenu(getListView());
        itemListView = getListView();     
        itemListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
                MenuInflater inflater = getMenuInflater();
                inflater.inflate(R.menu.listview_context_menu, menu);
            }           
        });
        listAdapter = new ItemListAdapter(getApplicationContext(), new ArrayList<Item>());
        itemListView.setAdapter(listAdapter);

        dbHelper = getHelper();
        new SelectDataTask().execute(dbHelper);

    }

    public void add_OnClick(View v) {
         Intent intent = new Intent();
         intent.setClass(this, AddItemActivity.class);
         startActivity(intent);
    }



    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        Item b = (Item) listAdapter.getItem(info.position);
        try {
            switch (item.getItemId()) {
                case R.id.remove_item:          
                    dbHelper.getItemDao().deleteById(new Integer(b.id));
                    listAdapter.notifyDataSetChanged();
                    return true;
            }
        } catch (SQLException e) {
            //FIXME
            e.printStackTrace();
            Log.e(TAG, e.getMessage());
        }
        return false;
    }

    private class SelectDataTask extends AsyncTask<DatabaseHelper, Void, List<Item>> {
        private final ProgressDialog dialog = new ProgressDialog(
                ItemListActivity.this);

        // can use UI thread here
        protected void onPreExecute() {
            this.dialog.setMessage("Retreiving item data...");
            this.dialog.show();
        }

        @Override
        protected List<Item> doInBackground(DatabaseHelper... params) {
            List<Item> l = null;
            try {
                Dao<Item, Integer> dao = params[0].getItemDao();
                l = dao.queryForAll();
            } catch (SQLException e) {
                //TODO -- cleanup
                e.printStackTrace();
                Log.e(TAG, e.getMessage());
            }
            return l;
        }

        // can use UI thread here
        @Override
        protected void onPostExecute(List<Item> b) {
            listAdapter = new MyListAdapter(getApplicationContext(), b);
            itemListView.setAdapter(listAdapter);
            //TODO -- none of this works
            itemListView.invalidateViews();
            listAdapter.notifyDataSetChanged();
            if (this.dialog.isShowing()) {
                this.dialog.dismiss();
            }

        }
    }

1 Ответ

0 голосов
/ 20 мая 2012

Проверьте мое решение (группа CRUD):

public class GroupsPreferenceActivity extends BaseAppActivity {
    private DatabaseHelper dbHelper;
    private ListView listView;
    private GroupAdapter groupAdapter;
    private DatabaseModel groupModel;
    private OnDeleteListener onDeleteListener;

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

        setContentView(R.layout.group_preference_layout);
        setDbHelper(new DatabaseHelper(getApplicationContext()));
        setGroupModel(new DatabaseModel(getDbHelper(), GroupData.class));
        setListView((ListView) findViewById(R.id.lv_group));
        setGroupAdapter(new GroupAdapter(GroupsPreferenceActivity.this));
        getListView().setAdapter(getGroupAdapter());
        setOnDeleteListener(new OnDeleteListener() {
            @Override
            public void onClick(GroupData group) {
                removeGroup(group);
            }
        });
        getListView().setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapter, View parent,
                    int position, long id) {
                addGroup(getGroupAdapter().getItem(position));
            }
        });
        getGroupAdapter().setOnDeleteListener(getOnDeleteListener());
        doLoadGroups();
    }

    private void doLoadGroups() {
        getGroupAdapter().clear();
        List<?> items = getGroupModel().getAll();
        for (Object group : items) {
            getGroupAdapter().add((GroupData) group);
        }
        getGroupAdapter().notifyDataSetChanged();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getSupportMenuInflater().inflate(R.menu.groups_preference_menu, menu);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        super.onMenuItemSelected(featureId, item);
        switch (item.getItemId()) {
        case R.id.option_item_add_group:
            addGroup();
            break;

        default:
            break;
        }
        return true;
    }

    private void addGroup() {
        addGroup(null);
    }

    private void addGroup(final GroupData groupData) {
        LayoutInflater factory = LayoutInflater
                .from(GroupsPreferenceActivity.this);
        final View textEntryView = factory.inflate(
                R.layout.create_group_dialog_view, null);
        final EditText editName = (EditText) textEntryView
                .findViewById(R.id.tv_group_name);
        String positiveButtonName = getString(R.string.create);
        OnClickListener positiveListener = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                createGroup(editName.getText().toString());
            }
        };
        if (groupData != null) {
            positiveButtonName = getString(R.string.update);
            editName.setText(groupData.getName());
            positiveListener = new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    groupData.setName(editName.getText().toString());
                    updateGroup(groupData);
                }
            };
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(
                GroupsPreferenceActivity.this);
        String title = getString(R.string.preference_add_group);

        builder.setCancelable(true)
                .setTitle(title)
                .setView(textEntryView)
                .setPositiveButton(positiveButtonName, positiveListener)
                .setNegativeButton(getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
        final AlertDialog alert = builder.create();
        alert.show();
        final Button yesButton = alert.getButton(Dialog.BUTTON_POSITIVE);
        yesButton.setEnabled(false);
        editName.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                yesButton.setEnabled(s.length() > 0);
            }
        });
    }

    protected void updateGroup(GroupData groupData) {
        getGroupModel().update(groupData);
        doLoadGroups();
    }

    protected void createGroup(String name) {
        GroupData groupData = new GroupData();
        groupData.setName(name);
        getGroupModel().add(groupData);
        doLoadGroups();
    }

    protected void removeGroup(GroupData group) {
        getGroupModel().remove(group);
        doLoadGroups();
    }

    public DatabaseHelper getDbHelper() {
        return dbHelper;
    }

    public void setDbHelper(DatabaseHelper dbHelper) {
        this.dbHelper = dbHelper;
    }

    public ListView getListView() {
        return listView;
    }

    public void setListView(ListView listView) {
        this.listView = listView;
    }

    public GroupAdapter getGroupAdapter() {
        return groupAdapter;
    }

    public void setGroupAdapter(GroupAdapter groupAdapter) {
        this.groupAdapter = groupAdapter;
    }

    public DatabaseModel getGroupModel() {
        return groupModel;
    }

    public void setGroupModel(DatabaseModel groupModel) {
        this.groupModel = groupModel;
    }

    public OnDeleteListener getOnDeleteListener() {
        return onDeleteListener;
    }

    public void setOnDeleteListener(OnDeleteListener onDeleteListener) {
        this.onDeleteListener = onDeleteListener;
    }
}

Мои помощники по БД расположены: https://github.com/beshkenadze/android-utils/tree/master/src/net/beshkenadze/android/db

...