Android:列表视图中的复选框在我们从一个活动转到另一个活动时更改其状态并返回

时间:2013-10-07 07:42:40

标签: android checkbox

我是初学者,使用复选框创建列表视图。当我检查一些复选框并返回时,然后当我回到相同的活动时,复选框将取消选中。意味着他们失去了国家。所以我试图将他们的状态保存在数据库中。但我得到异常作为ClassCastException。那怎么实现呢?请帮忙,我的代码是,

public View getView(final int position, View convertView,
                ViewGroup parent) {
            // Event to display
            final Even eventzz = (Even) this.getItem(position);

            // The child views in each row.
            final CheckBox checkBox;
            TextView textView;

            // Create a new row view
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.eventsinfo, null);

                // Find the child views.
                textView = (TextView) convertView
                        .findViewById(R.id.rowTextView);
                checkBox = (CheckBox) convertView.findViewById(R.id.CheckBox01);
                checkBox.setBackgroundColor(Color.TRANSPARENT);
                // Optimization: Tag the row with it's child views, so we don't
                // have to call findViewById() later when we reuse the row.
                convertView.setTag(new EventViewHolder(textView, checkBox));

                 checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                        @Override
                        public void onCheckedChanged(CompoundButton buttonView,
                                boolean isChecked) {
                            int realPosition = (Integer) buttonView.getTag();
                            if (isChecked) {
                                itemChecked.set(realPosition, true);
                                // update the database to store the new checked item:
                                ContentValues cv = new ContentValues();
                                cv.put("list_position", realPosition);
                                statusDb.insert("status", null, cv);
                            } else {
                                itemChecked.set(realPosition, false);
                                // delete this position from the database because it was
                                // unchecked
                                statusDb.delete("status", "list_position = "
                                        + realPosition, null);
                            }
                        }
                    });
                 checkBox.setChecked(itemChecked.get(position));

                // If CheckBox is toggled, update the event it is tagged with.
                checkBox.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        int realPosition = (Integer) checkBox.getTag();
                        CheckBox cb = (CheckBox) v;
                        Even eventz = (Even) cb.getTag();
                        eventz.setChecked(cb.isChecked());
else {
                // Because we use a ViewHolder, we avoid having to call
                // findViewById().
                EventViewHolder viewHolder = (EventViewHolder) convertView
                        .getTag();
                checkBox = viewHolder.getCheckBox();
                textView = viewHolder.getTextView();
            }

             checkBox.setTag(new Integer(position));
    checkBox.setChecked(itemChecked.get(position));

            // Tag the CheckBox with the Event it is displaying, so that we can
            // access the event in onClick() when the CheckBox is toggled.
            checkBox.setTag(eventzz);

            // Display events data
            checkBox.setChecked(eventzz.isChecked());
            textView.setText(eventzz.getName());

            return convertView;
        }

Helper.java

 class Helper extends SQLiteOpenHelper {

    public Helper(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // the list_position will hold the position from the list that are
        // currently checked
        String sql = "CREATE TABLE status (list_position INTEGER);";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Just for interface
    }

}

MainActivity.java

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.eventstoremindlist);

        // Find the ListView resource.
        mainListView = (ListView) findViewById(R.id.mainListView);
        checkBox = (CheckBox) findViewById(R.id.CheckBox01);
    ArrayList<Even> eventList = new ArrayList<Even>();
    eventList.addAll(Arrays.asList(events));
    // Set our custom array adapter as the ListView's adapter.

    listAdapter = new EventArrayAdapter(this, eventList, null);

    // Retrieve the list of position that are checked(if any) from the
    // database
    statusDb = mHelper.getWritableDatabase();
    Cursor statusCursor = statusDb.rawQuery("SELECT * FROM status", null);
    int[] savedStatus = null;
    if ((statusCursor != null) & (statusCursor.moveToFirst())) {
        savedStatus = new int[statusCursor.getCount()];
        int i = 0;
        do {
            savedStatus[i] = statusCursor.getInt(0);
            i++;
        } while (statusCursor.moveToNext());
    }
    // if the cursor is null or empty we just pass the null savedStatus to
    // the adapter constructor and let it handle(setting all the CheckBoxes
    // to unchecked)


    mainListView.setAdapter(listAdapter);

例外是,

10-07 13:07:15.922: E/AndroidRuntime(816): FATAL EXCEPTION: main
10-07 13:07:15.922: E/AndroidRuntime(816): java.lang.ClassCastException: com.kalnirnay.kalnirnay.EventsToRemindActivity$Even
10-07 13:07:15.922: E/AndroidRuntime(816):  at com.kalnirnay.kalnirnay.EventsToRemindActivity$EventArrayAdapter$1.onCheckedChanged(EventsToRemindActivity.java:264)
10-07 13:07:15.922: E/AndroidRuntime(816):  at android.widget.CompoundButton.setChecked(CompoundButton.java:124)
10-07 13:07:15.922: E/AndroidRuntime(816):  at android.widget.CompoundButton.toggle(CompoundButton.java:86)
10-07 13:07:15.922: E/AndroidRuntime(816):  at android.widget.CompoundButton.performClick(CompoundButton.java:98)
10-07 13:07:15.922: E/AndroidRuntime(816):  at android.view.View$PerformClick.run(View.java:9080)
10-07 13:07:15.922: E/AndroidRuntime(816):  at android.os.Handler.handleCallback(Handler.java:587)
10-07 13:07:15.922: E/AndroidRuntime(816):  at android.os.Handler.dispatchMessage(Handler.java:92)
10-07 13:07:15.922: E/AndroidRuntime(816):  at android.os.Looper.loop(Looper.java:123)
10-07 13:07:15.922: E/AndroidRuntime(816):  at android.app.ActivityThread.main(ActivityThread.java:3683)
10-07 13:07:15.922: E/AndroidRuntime(816):  at java.lang.reflect.Method.invokeNative(Native Method)
10-07 13:07:15.922: E/AndroidRuntime(816):  at java.lang.reflect.Method.invoke(Method.java:507)
10-07 13:07:15.922: E/AndroidRuntime(816):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-07 13:07:15.922: E/AndroidRuntime(816):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-07 13:07:15.922: E/AndroidRuntime(816):  at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

而不是将其状态保存在数据库中,您可以使用: -
1。一个静态arraylist来存储checked复选框的位置,并在返回视图之前在getView()方法中读取检查值,

2。你可以使用SharedPreferences来保存状态。

3。你也可以看看ViewHolder概念!!

我认为对于这种琐碎的使用数据库是不合适的。

它还可以节省一些代码!

您也可以参考: -

listview with check box