2

I know this is a common problem, but nothing I've found solves my issue. I've created a ContentProvider, closely following the tutorial here. My Activity, in its onCreate method immediately after super.onCreate does this:

StitchProvider stitchProvider = new StitchProvider();
stitchProvider.delete(STITCHES_URI, null, null);

StitchProvider is my ContentProvider. I've followed this code through the debugger and depending on where I put breakpoints, one of two things happen, but both lead to a NullPointerException in LogCat. The first option is I put a breakpoint here:

public SQLData(Context c) {
    super(c, DATABASENAME, null, DATABASEVERSION);
}

SQLData is my database class. If I put the breakpoint here, I see that c, the Context, is equal to android.app.Application@412a9b80. The code then returns to the onCreate method of StitchProvider:

public boolean onCreate() {
    mDB = new SQLData(getContext()); 
    return true;
}

and mDB becomes com.MyKnitCards.project.SQLData@412ab668. So far so good I think, but when I try to go past the return statement I get the NullPointerException. If I move the breakpoint to within the delete method of StitchProvider everything goes fine until I get to the getWriteableDatabase line, at which point I get a NullPointerException. Here's the delete method of StitchProvider:

public int delete(Uri uri, String selection, String[] selectionArgs) {
    int uriType = sURIMatcher.match(uri);
    int rowsAffected = 0;
    switch (uriType)
    {
    case STITCHES:
        SQLiteDatabase sqlDB = mDB.getWritableDatabase();
        rowsAffected = sqlDB.delete(STITCHTABLE_BASEPATH, selection, selectionArgs);
        break;
    case STITCHES_ID:
        SQLiteDatabase sqlDBwithID = mDB.getWritableDatabase();
        String id = uri.getLastPathSegment();
        if (TextUtils.isEmpty(selection))
        {
            rowsAffected = sqlDBwithID.delete(STITCHTABLE_BASEPATH, SQLData.KEY_ROWID + "=" + id, null);
        }
        else
        {
            rowsAffected = sqlDBwithID.delete(STITCHTABLE_BASEPATH, selection + " and " + SQLData.KEY_ROWID + "=" + id, selectionArgs);
        }
        break;
    default:
        throw new IllegalArgumentException("Unknown or Invalid URI " + uri);
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return rowsAffected;
}

One thing I have noticed, is that if I set a breakpoint at SQLData's onCreate method, I never get there. I think part of the problem is that the database is not getting created, but I don't know why. I'll post as much code or LogCat as people want, put I don't want to overwhelm folks with code either. Anyway, as always, if you have any suggestions, that'd be great, and thanks!

4

1 回答 1

4

我看到您在代码中实例化了您的提供程序,这是您不应该做的事情,因为它ContentProvider是由 Android 系统管理的。使用 a 的正确方法ContentProvider是通过 a ContentResolverwhich 可以在 an Activitywith中获得getContentResolver()

您可以在 android 开发者网站上的官方教程中找到更多关于ContentProviders它们以及如何使用它们的信息。

于 2012-11-07T20:56:12.020 回答