Domanda

I am creating a ContentProvider and understand that I need to share the URI format with clients. Lars Vogella's tutorial includes:

  public class MyTodoContentProvider extends ContentProvider {
      public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/todos";
      public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/todo";

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

      :
  }

This seems like an abstraction violation, since I want to share those constant definitions but not the code that services the request. Do people recommend putting them in a public abstract class that just defines constants? (The great Josh Bloch recommends against using interfaces for this purpose.)

In any case, how do I package up the constants so that clients can see them? If I write the client app, I can link in the class that defines the constants, but how are they visible to other clients? Do I upload my constants class where anyone can download it and link it in?

(In practice, nobody else will want to use my content provider, which I'm creating for a college course, but I want to teach my students best practices.)

È stato utile?

Soluzione

You can create a contract class, like the Android APIs do, for instance for the Contacts, where you define your content type, content uri, fields and so on:

http://developer.android.com/reference/android/provider/ContactsContract.html

For the implementation, as Effective Java Item #19 suggest, you can create a "normal" class:

public class MyTodoContract {

    private MyTodoContract() {}

    public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/todos";

    public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/todo";
}

If you want to provide this class to your clients you should create a Java Library and provide them the jar.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top