Pass connection object to other activity - Google

2019-09-19 06:41发布

问题:

I seem to have struck a wall with this problem of mine. Basically i'm working on an app which syncs your google tasks with the Google Tasks API. Everything is going great so far in my first activity. But now I want to create a new activity to show the users task lists. So to get the tasklists I need the connection object in this new activity. Normally I just give variables with i.putExtra() or something similiar but ofcourse this does not work with (custom) objects. I already tried to use Parceable and Serializable on a custom made class which had the object wrapped in it, but I keep getting errors about how the class (from Google API) itself does not implement these. It's also impossible to pass the parameters for creating a new instance of the class because they are themselfs custom objects from Google. Does anyone have an idea or experience with this?

It's the service object I need to pass to a new activity:

final HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();
final JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
credential = GoogleAccountCredential.usingOAuth2(this, Collections.singleton(TasksScopes.TASKS));
credential.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));
// Tasks Client
service = new com.google.api.services.tasks.Tasks.Builder(httpTransport, jsonFactory, credential).setApplicationName("Test").build();

Thanks in advance!

回答1:

Im not sure if it is the best way to do it (specially because I do not know this task service class), but one idea that came to my mind was of having the variable defined in a class that extends the Application. Here it is an article describing the Application class and illustrating the creation of class that extends it to manage some "global data"

In that way, you can set/get it in the different activities.