游标适配器未更新ListView

时间:2018-03-06 14:51:38

标签: android android-adapter

在我的自定义提供程序类中,我有一个getContentResolver()。notifyChange。这应该通知listView更新,但是当应用程序运行并编辑列表项时,程序似乎没有注意到更新。

PROVIDER CLASS

public class BarberProvider extends ContentProvider {

private final String LOG_TAG = "BarberProvider";
BarberDbHelper mDbHelper;

private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

private static final int BARBER = 100;
private static final int BARBER_ID = 101;
private static final int BARBER_ROW = 102;

static {
    sUriMatcher.addURI(BarberContract.CONTENT_AUTHORITY, BarberContract.PATH_BARBER, BARBER);

    sUriMatcher.addURI(BarberContract.CONTENT_AUTHORITY,  BarberContract.PATH_BARBER+ "/#", BARBER_ID);

    sUriMatcher.addURI(BarberContract.CONTENT_AUTHORITY, BarberContract.PATH_BARBER + "/Set/#/#", BARBER_ROW);
}


@Override
public boolean onCreate() {
    //Create and initialize a BarberDbHelper object to gain access to the pets database.
    // Make sure the variable is a global variable, so it can be referenced from other
    // ContentProvider methods.

    mDbHelper = new BarberDbHelper(getContext());
    return true;
}

@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {

    // Get readable database
    SQLiteDatabase database = mDbHelper.getReadableDatabase();

    // This cursor will hold the result of the query
    Cursor cursor;

    // Figure out if the URI matcher can match the URI to a specific code
    int match = sUriMatcher.match(uri);

    switch (match) {
        case BARBER:
            // For the PETS code, query the pets table directly with the given
            // projection, selection, selection arguments, and sort order. The cursor
            // could contain multiple rows of the pets table.
            // TODO: Perform database query on pets table
            return cursor = database.query(BarberContract.BarberEntry.TABLE_NAME, projection, selection, selectionArgs,
                    null, null, sortOrder);

        case BARBER_ID:

            selection = BarberContract.BarberEntry._ID + "=?";
            selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) };

            // This will perform a query on the pets table where the _id equals 3 to return a
            // Cursor containing that row of the table.
            cursor = database.query(BarberContract.BarberEntry.TABLE_NAME, projection, selection, selectionArgs,
                    null, null, sortOrder);
            break;
        default:
            throw new IllegalArgumentException("Cannot query unknown URI " + uri);
    }
    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    return cursor;
}

@Nullable
@Override
public String getType(@NonNull Uri uri) {
    final int match = sUriMatcher.match(uri);
    switch (match) {
        case BARBER:
            return BarberContract.BarberEntry.CONTENT_LIST_TYPE;
        case BARBER_ID:
            return BarberContract.BarberEntry.CONTENT_ITEM_TYPE;
        default:
            throw new IllegalStateException("Unknown URI " + uri + " with match " + match);
    }
}

@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
    final int match = sUriMatcher.match(uri);
    switch (match) {
        case BARBER:
            return insertBarberDaysTime(uri, values);
        default:
            throw new IllegalArgumentException("Insertion is not supported for " + uri);
    }
}

private Uri insertBarberDaysTime(Uri uri, ContentValues values) {

    SQLiteDatabase database = mDbHelper.getWritableDatabase();


    String days = values.getAsString(BarberContract.BarberEntry.COLUMN_DAYS);
    if(days == null){
        throw new IllegalArgumentException("Barber requires days to be inputted");
    }

    String startTime = values.getAsString(BarberContract.BarberEntry.COLUMN_START_TIME);
    if(startTime == null){
        throw new IllegalArgumentException("Barber needs a start time!");
    }

    String finishTime = values.getAsString(BarberContract.BarberEntry.COLUMN_FINISH_TIME);
    if(finishTime == null){
        throw new IllegalArgumentException("Barber needs a finish time");
    }

    // TODO: Insert a new pet into the pets database table with the given ContentValues
    long id = database.insert(BarberContract.BarberEntry.TABLE_NAME, null,values);

    if(id == -1){
        Log.e(LOG_TAG, "Failed to insert row for " + uri);
        return null;
    }

    getContext().getContentResolver().notifyChange(uri, null);
    // Once we know the ID of the new row in the table,
    // return the new URI with the ID appended to the end of it
    return ContentUris.withAppendedId(uri, id);
}


@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
    // Get writeable database
    SQLiteDatabase database = mDbHelper.getWritableDatabase();
    int rowsDeleted;

    final int match = sUriMatcher.match(uri);
    switch (match) {
        case BARBER:
            // Delete all rows that match the selection and selection args

            //Number of rows deleted
            rowsDeleted = database.delete(BarberContract.BarberEntry.TABLE_NAME, selection, selectionArgs);

            if(rowsDeleted != 0 ){
                getContext().getContentResolver().notifyChange(uri, null);
            }

            // Return the number of rows deleted
            return rowsDeleted;

        case BARBER_ID:
            // Delete a single row given by the ID in the URI
            selection = BarberContract.BarberEntry._ID + "=?";
            selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};

            rowsDeleted = database.delete(BarberContract.BarberEntry.TABLE_NAME, selection, selectionArgs);

            if(rowsDeleted != 0) {
                getContext().getContentResolver().notifyChange(uri, null);
            }

            return rowsDeleted;
        default:
            throw new IllegalArgumentException("Deletion is not supported for " + uri);
    }
}

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    final int match = sUriMatcher.match(uri);
    switch (match) {
        case BARBER:
            return updateBarberDaysTime(uri, values, selection, selectionArgs);
        case BARBER_ID:
            // For the Barber_ID code, extract out the ID from the URI,
            // so we know which row to update. Selection will be "_id=?" and selection
            // arguments will be a String array containing the actual ID.
            selection = BarberContract.BarberEntry._ID + "=?";
            selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) };
            return updateBarberDaysTime(uri, values, selection, selectionArgs);
        default:
            throw new IllegalArgumentException("Update is not supported for " + uri);
    }
}

private int updateBarberDaysTime(Uri uri, ContentValues values, String selection, String[] selectionArgs) {

    // Update the selected barber in the barber database table with the given ContentValues
    if(values.containsKey(BarberContract.BarberEntry.COLUMN_DAYS)){
        String days = values.getAsString(BarberContract.BarberEntry.COLUMN_DAYS);
        if(days == null){
            throw new IllegalArgumentException("Day required!");
        }
    }

    if (values.containsKey(BarberContract.BarberEntry.COLUMN_START_TIME)) {
        String start_time = values.getAsString(BarberContract.BarberEntry.COLUMN_START_TIME);
        if (start_time == null) {
            throw new IllegalArgumentException("Start time required!");
        }
    }

    if (values.containsKey(BarberContract.BarberEntry.COLUMN_FINISH_TIME)) {
        // Check that the weight is greater than or equal to 0 kg
        String finish_time = values.getAsString(BarberContract.BarberEntry.COLUMN_FINISH_TIME);
        if (finish_time == null) {
            throw new IllegalArgumentException("Finish time required!");
        }
    }

    // TODO: Return the number of rows that were affected
    if (values.size() == 0) {
        return 0;
    }

    // Otherwise, get writeable database to update the data
    SQLiteDatabase database = mDbHelper.getWritableDatabase();

    int rowsUpdated = database.update(BarberContract.BarberEntry.TABLE_NAME, values, selection, selectionArgs);

    if(rowsUpdated != 0) {
        getContext().getContentResolver().notifyChange(uri, null);
    }

    // Returns the number of database rows affected by the update statement
    return rowsUpdated;
}
}

显示列表视图

public class WorkHoursActivity extends AppCompatActivity implements
    LoaderManager.LoaderCallbacks<Cursor>{

static final String [] PROJECTION =  new String[] {
        BarberContract.BarberEntry._ID,
        BarberContract.BarberEntry.COLUMN_DAYS,
        BarberContract.BarberEntry.COLUMN_START_TIME,
        BarberContract.BarberEntry.COLUMN_FINISH_TIME };

BarberDaysHoursCursorAdapter cursorAdapter;
//BarberDbHelper mDbHelper;

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

    // Setup FAB to open EditorActivity
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(WorkHoursActivity.this, DaysHoursActivity.class);
            startActivity(intent);
        }
    });

    ListView workDaysHours = (ListView) findViewById(R.id.lv);
    workDaysHours.setEmptyView(findViewById(R.id.empty_list));

    //mDbHelper = new BarberDbHelper(this);

    cursorAdapter = new BarberDaysHoursCursorAdapter(this, null);
    workDaysHours.setAdapter(cursorAdapter);

    workDaysHours.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(WorkHoursActivity.this, DaysHoursActivity.class);

            Uri currentBarberUri = ContentUris.withAppendedId(BarberContract.BarberEntry.CONTENT_URI, id);

            intent.setData(currentBarberUri);

            Log.i("WorkHoursActivity", " ------ID------- " + id);
            startActivity(intent);
        }
    });

    getLoaderManager().initLoader(0, null, this);
}


@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    return new CursorLoader( this,
            BarberContract.BarberEntry.CONTENT_URI,
            PROJECTION,
            null,
            null,
            null);
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

    cursorAdapter.swapCursor(data);
}

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

    cursorAdapter.swapCursor(null);
}
}

带Listview的光标适配器 Cursor Adapter with Listview 编辑器视图添加了W并选择了保存 Editor view added W and select save 列表未更新 The list is not updated 返回列表项目仅选择W Go back into the List item only W is selected

0 个答案:

没有答案