A
A
AndroidDev20152015-04-14 00:40:50
Android
AndroidDev2015, 2015-04-14 00:40:50

How to update ListView on clicking CheckBox which is in Custom SimpleCursorAdapter?

I want to update the listview in the activity every time the checkbox is clicked, but when the updateTodo() method is called from the checkbox listener, the application does not work.
MainActivity

public class MainActivity extends ListActivity {


    private TodoDatabase dbHelper;
    //private static final int ACTIVITY_CREATE = 0;
    private static final int ACTIVITY_EDIT = 1;
    private static final int DELETE_ID = Menu.FIRST + 1;
    private Cursor cursor;
    private EditText mEditText;
    private Long RowId;

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

        this.getListView().setDividerHeight(2);
        dbHelper = new TodoDatabase(this);

        fillData();
        registerForContextMenu(getListView());

        mEditText = (EditText)findViewById(R.id.editTextNewTask);

        RowId = null;
        Bundle extras = getIntent().getExtras();

        RowId = (savedInstanceState == null) ? null
                : (Long) savedInstanceState
                .getSerializable(TodoDatabase.COLUMN_ID);
        if (extras != null) {
            RowId = extras.getLong(TodoDatabase.COLUMN_ID);
        }

        startService(new Intent(this, TimeService.class));
    }
    .........
    .........
        public void updateTodo(){
        fillData();
    }


    private void fillData() {
        cursor = dbHelper.getAllTodosListView();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        startManagingCursor(cursor);
        }

        String[] from = new String[] {TodoDatabase.COLUMN_ACHIEVED, TodoDatabase.COLUMN_SUMMARY,
                                        TodoDatabase.COLUMN_TIMESECONDS};
        int[] to = new int[] {R.id.checkBoxLabel, R.id.textViewLabel };

        // Теперь создадим адаптер массива и установим его для отображения наших
        // данных
        SimpleCursorAdapter notes = new MySimpleCursorAdapter(getApplicationContext(),
                R.layout.list_item, cursor, from, to, 0);

        notes.changeCursor(cursor);
        notes.notifyDataSetChanged();

        setListAdapter(notes);
    }

SimpleCursorAdapter
public class MySimpleCursorAdapter extends SimpleCursorAdapter {

    private Context context;
    private LayoutInflater mInflater;
    private CheckBox mCheckBox;
    private long xId;


    public MySimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
        super(context, layout, c, from, to, flags);
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        final View view = mInflater.inflate(R.layout.list_item, parent, false);
        return view;

    }

    @Override
    public void bindView(View view, final Context context, final Cursor cursor) {
        final TodoDatabase mDbHelper = new TodoDatabase(context);

        final TextView textView = (TextView)view.findViewById(R.id.textViewLabel);
        mCheckBox = (CheckBox)view.findViewById(R.id.checkBoxLabel);

        xId = Long.parseLong(cursor.getString(cursor.getColumnIndex(TodoDatabase.COLUMN_ID)));

textView.setText(cursor.getString(cursor.getColumnIndex(TodoDatabase.COLUMN_SUMMARY)));
        if (cursor.getString(cursor.getColumnIndex(TodoDatabase.COLUMN_TIMESECONDS)) != null) {
            if (cursor.getLong(cursor.getColumnIndex(TodoDatabase.COLUMN_TIMESECONDS)) > 0) {
                if (cursor.getLong(cursor.getColumnIndex(TodoDatabase.COLUMN_TIMESECONDS)) >
                        System.currentTimeMillis()) {
                } else if (cursor.getInt(cursor.getColumnIndex(TodoDatabase.COLUMN_ACHIEVED)) != 1){
                    textView.setTextColor(Color.parseColor("#FF0000"));
                }
            }
        }

        if (cursor.getInt(cursor.getColumnIndex(TodoDatabase.COLUMN_ACHIEVED)) == 1) {
            mCheckBox.setChecked(true);
            textView.setPaintFlags(textView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            final Long mRowId = xId;

            mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    Long mXRowId = mRowId;
                    if (mCheckBox.isChecked()) {

                        TodoDatabase mDbHelper = new TodoDatabase(context);
                        mDbHelper.updateTodoAchieved(mXRowId, "1");

                        MainActivity ma = new MainActivity();
                        ma.updateTodo(); // Ошибка

                    } else if (!mCheckBox.isChecked()) {

                        TodoDatabase mDbHelper = new TodoDatabase(context);
                        mDbHelper.updateTodoAchieved(mXRowId, "0");

                        MainActivity ma = new MainActivity();
                        ma.updateTodo(); // Ошибка

                    }
                }
            });

        } else {
            mCheckBox.setChecked(false);
            textView.setPaintFlags(textView.getPaintFlags() & (~ Paint.STRIKE_THRU_TEXT_FLAG));
            final Long mRowId = xId;

            mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                Long mXRowId = mRowId;
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (mCheckBox.isChecked()){

                        TodoDatabase mDbHelper = new TodoDatabase(context);
                        mDbHelper.updateTodoAchieved(mXRowId, "1");

                        MainActivity ma = new MainActivity();
                        ma.updateTodo(); // Ошибка

                    } else if (!mCheckBox.isChecked()){

                        TodoDatabase mDbHelper = new TodoDatabase(context);
                        mDbHelper.updateTodoAchieved(mXRowId, "0");

                        MainActivity ma = new MainActivity();
                        ma.updateTodo(); // Ошибка

                    }
                }
            });
        }
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem Gapchenko, 2015-04-23
@artemgapchenko

Your mistake probably lies in the fact that NullPointerException is thrown when accessing dbHelper, which at the time of accessing it is not initialized, since it is initialized in onCreate(), which will not be called, since for some reason you are creating a new instance of the MainActivity class.
First. Never create an Activity or other components of an Android application through constructors. There is an intent mechanism for creating components .
Second. The adapter has a nice method notifyDataSetChanged()that notifies the AdapterView working with this adapter that the data has been updated and it would be nice to redraw itself. Throw out

MainActivity ma = new MainActivity();
ma.updateTodo(); // Ошибка

and write there
PS You have a little mess in your head. I advise you to read something on the topic of Android applications. You can start from the site of Alexander Klimov or from the book "Programming for Android. For Professionals" by Brian Hardy and Bill Phillips (don't let the title bother you, everything is written there in detail). If you have English at the level of reading technical literature (and you should be, after all, you are a programmer), I advise you to read Hardy-Phillips in the original, and periodically look at the official documentation , sections "API Guides" and "Training".

R
Rustem Saitkulov, 2015-04-23
@atetc

Isn't it time to switch to RecyclerView?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question