Sorry for the maybe poor title, no idea how to describe t开发者_JAVA百科his well.
I have written my own ContentProvider called DeaddropDBProvider, which includes the following lines to set some constants for the URIs to the provided content:
public static final String PROVIDER_NAME =
"squirrel.deaddropdroid.deaddropdbprovider";
public static final Uri BLOG_URI =
Uri.parse("content://"+ PROVIDER_NAME + "/blog");
Now to get to these URIs, I'm accessing them in two different ways. One works, the other fails, and I don't understand why.
The failing method:
Method 1): direct call. That works fine (abbreviated code):
public class DeaddropDB {
public void getData(...) {
Cursor cursor = context.getContentResolver().query(DeaddropDBProvider.BLOG_URI,
columns, selection, selectionArgs, orderBy);
}
}
Method 2): import URI as constant; then make the call. This gives a NullPointerException the moment I try to use that URI, as the URI is still null.
public class DeaddropDB {
public static final Uri BLOG_URI = DeaddropDBProvider.BLOG_URI;
public void getData(...) {
Cursor cursor = context.getContentResolver().query(BLOG_URI,
columns, selection, selectionArgs, orderBy);
}
}
How come this second method does not work? Why is BLOG_URI null?
I see this is a stale question at this point, but since it doesn't have an answer I thought I'd throw in my 2 cents...
I think it's failing because your DeaddropDBProvider.BLOG_URI isn't fully initialized when DeaddropDB.BLOG_URI is initialized.
I'm not a Java expert, but I know that static variables are defined when you first access a class; BUT, if there are initializers in class A that reference class B, and then class B tries to reference class A, Java may not handle that case correctly, so if DeaddropDBProvider tries to read anything from DeaddropDB to initialize a static variable, there may be a conflict.
My recommendation would be to create a DeaddropDBSettings class that both other classes read. That way you don't end up with mutual initialization conflicts.
Try to access as follow.
public class DeaddropDB {
public static final Uri BLOG_URI = Uri.parse("content://squirrel.deaddropdroid.deaddropdbprovide/blog");
public void getData(...) {
Cursor cursor = context.getContentResolver().query(BLOG_URI,
columns, selection, selectionArgs, orderBy);
}
}
精彩评论