Search code examples
javaandroidlistviewandroid-cursoradapter

How to get my current ID in CursorAdapter?


I have a ListView, which is populated by a CursorAdapter. Each item in ListView has a spinner, a button and a checkbox. I need to update values in database when the user selects something in spinner, ticks the checkbox or pushes the button. The problem is, that I don't know how to access the ID for database entry to update it. Every time something in any of list items is changed, it updates values for the last list item.

I've tried to use setTag() and getTag() for my three views, but when getTag() is called in a listener, I get a null value. How I get the ID for my current list item?

UPDATE: Okay, I'm getting closer to solving the case. My problem now is that I don't know how to properly set and get a tag to a spinner. I tried to get tag from parent AdapterView, but that's not it.

public class DoorSelectorCursorAdapter extends CursorAdapter {
    private ProjectsDBHelper mDbHelper;
    Button bDelete;
    Spinner spDoor;
    TextView tvDoorName;
    CheckBox cbAdded;
    String doorID;
    long currentID, wallID;
    Intent mIntent;
    public DoorSelectorCursorAdapter(Context context, Cursor cursor, Intent intent) {

        super(context, cursor, 0);
        final String LOG_TAG = DoorSelectorCursorAdapter.class.getSimpleName();
        Log.v(LOG_TAG, "DoorSelectorCursorAdapter инициализирован");
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {

        return LayoutInflater.from(context).inflate(R.layout.selector_list_item, parent, false);
    }

    // The bindView method is used to bind all data to a given view
    // such as setting the text on a TextView.
    @Override
    public void bindView(final View view, Context context, final Cursor cursor) {
        final String LOG_TAG = DoorSelectorCursorAdapter.class.getSimpleName();
        Log.v(LOG_TAG, "вызван BindView");

        currentID = cursor.getLong(cursor.getColumnIndex(DataContract.WallDoorEntry.COLUMN_WALLDOOR_ID));
        wallID = cursor.getLong(cursor.getColumnIndex(DataContract.WallDoorEntry.COLUMN_WALLDOOR_IDWALL_FK));
        spDoor = (Spinner) view.findViewById(R.id.spinner_item);
        tvDoorName = (TextView) view.findViewById(R.id.selector_itemName);
        cbAdded = (CheckBox) view.findViewById(R.id.selector_checkbox);
        bDelete = (Button) view.findViewById(R.id.selector_button_delete);
        spDoor.setTag(currentID);
        cbAdded.setTag(currentID);
        bDelete.setTag(currentID);

        //res[0] = (cursor.getInt(cursor.getColumnIndex(DataContract.WallDoorEntry.COLUMN_WALLDOOR_IDDOOR_FK)) - 1);
//        final long[] iCurrentSelection = new long[1];
//        iCurrentSelection[0] = spDoor.getSelectedItemPosition();
        int currentPosition = cursor.getPosition();
        tvDoorName.setText("Дверь " + (currentPosition + 1));

        if(cursor.getInt(cursor.getColumnIndex(DataContract.WallDoorEntry.COLUMN_WALLDOOR_EXISTS)) == 1){
            cbAdded.setChecked(true);
        } else if(cursor.getInt(cursor.getColumnIndex(DataContract.WallDoorEntry.COLUMN_WALLDOOR_EXISTS)) == 0) {
            cbAdded.setChecked(false);
        }

        final Cursor doorCursor = context.getContentResolver().query(DataContract.DoorEntry.CONTENT_URI, null, null,  null, null);
        if (doorCursor.getCount() > 0){
            DoorCursorAdapter doorAdapter = new DoorCursorAdapter(context, doorCursor);
            spDoor.setAdapter(doorAdapter);
        }
        if(cursor.getString(cursor.getColumnIndex(DataContract.WallDoorEntry.COLUMN_WALLDOOR_IDDOOR_FK)) != null){
            spDoor.setSelection(cursor.getInt(cursor.getColumnIndex(DataContract.WallDoorEntry.COLUMN_WALLDOOR_IDDOOR_FK)) - 1);
        }

        spDoor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                if (res[0] == id){

//                }
//                else {
//                    spDoor.setSelection(cursor.getInt(cursor.getColumnIndex(DataContract.WallDoorEntry.COLUMN_WALLDOOR_IDDOOR_FK)) - 1);
//                }
//                if (iCurrentSelection[0] != id){
//                    // Your code here
                int intID = (Integer) view.getTag();
                    doorID = String.valueOf(id);
                    updateEntry(intID);
//                }
//                iCurrentSelection[0] = id;
        }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });
        cbAdded.setOnClickListener(new View.OnClickListener() {
                                       @Override
                                       public void onClick(View v) {
                                           int intID = (Integer) view.getTag();
                                           updateEntry(intID);
                                       }
                                   });
//                cbAdded.setOnClickListener(new CompoundButton.OnCheckedChangeListener() {
//                                               @Override
//                                               public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                                                   updateEntry();
//                                               }
//                                           }
//        );

        bDelete.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                deleteEntry(cursor, arg0.getTag());
            }
        });

    }

    private void deleteEntry(Cursor cursor, Object tag) {
            mContext.getContentResolver().delete(DataContract.WallDoorEntry.CONTENT_URI, DataContract.WallDoorEntry.COLUMN_WALLDOOR_ID + " LIKE " + tag, null);
//            Cursor newCursor = mContext.getContentResolver().query(DataContract.WallDoorEntry.CONTENT_URI, null,DataContract.WallDoorEntry.COLUMN_WALLDOOR_IDWALL_FK + " LIKE " + wallID, null, null);
//            super.swapCursor(newCursor);
    }

    private void updateEntry(int tagID) {
        ContentValues entryValues = new ContentValues();
        entryValues.put(DataContract.WallDoorEntry.COLUMN_WALLDOOR_IDDOOR_FK, doorID);
        int checked = 0;
        if (cbAdded.isChecked() == true){
            checked = 1;
        }
        entryValues.put(DataContract.WallDoorEntry.COLUMN_WALLDOOR_EXISTS, checked);

        int numOfUpdatedEntries = mContext.getContentResolver().update(DataContract.WallDoorEntry.CONTENT_URI, entryValues,
                DataContract.WallDoorEntry.COLUMN_WALLDOOR_ID + " LIKE " + tagID, null);
    }
}

Solution

  • You can save state of bound items in some Collection in Adapter.

    final Map<Integer, Integer> mBoundItems = new HashMap<>();
    

    Save state, once item binding. You can use any object, as key, to access you IDs. In this example, you can use your known Key for the Item.

    final int key = someKnownKeyForItem();
    mBoundItems.put(key, currentID);
    

    Then whenever you need data from based on Click of Views and known for this position Key, or any other condition.

    final int key = someKnownKeyForThisItem();
    final int id = mBoundItems.get(key);