How to add event on google calendar using calendar API using android? - android

Hi I am trying to create an event in Google calendar using Google calendar API in android.
I have created a sample project provided by Google, and I followed the each steps and compiled the project successfully.
But in this Example of Google calendar, I can only create a calendar name to my Google calendar account, I can't create any event.
Is there any way to create an event in Google calendar? If so how can I do it?

After Searching for some time i have finally find the solution .the answer was in the google document it self just go through this link
it shows how to create an event using google calender api.

This is such a giant pain in the ass - but I finally got it working for creating events at least.
Download the most recent Google PHP API zip, and upload it to your includes folder on your webserver. Use Google API Console to set up an API client. Make sure you set your redirect url to be the same as your page's url - so it redirects to its self.
I've initially just set some variables for event details, you can make a form which shoves these in if you want.
Here's my code:
<?php
$jobname = "BINGO";
$joblocation = "Your mums house";
$jobdescription = "An interview with a dog.";
$startofjob = "2013-12-20T17:00:00.000+00:00"; //datetimes must be in this format
$endofjob = "2013-12-20T18:00:00.000+00:00"; // YYYY-MM-DDTHH:MM:SS.MMM+HH:MM
//So that's year, month, day, the letter T, hours, minutes, seconds, miliseconds, + or -, timezoneoffset in hours and minutes
include('google-api-php-client/src/Google_Client.php');
include('google-api-php-client/src/contrib/Google_CalendarService.php');
session_start();
$client = new Google_Client();
$client->setApplicationName('doesntmatter-whateveryouwant');
$client->setClientId('yourclientid');
$client->setClientSecret('yourclientsecret');
$client->setRedirectUri('yourredirecturl-setingoogleconsole');
$client->setDeveloperKey('yourdeveloperkey');
$cal = new Google_CalendarService($client);
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$event = new Google_Event();
$event->setSummary($jobname);
$event->setDescription($jobdescription);
$event->setLocation($joblocation);
$start = new Google_EventDateTime();
$start->setDateTime($startofjob);
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime($endofjob);
$event->setEnd($end);
$createdEvent = $cal->events->insert('YOURCALENDARID#GOOGLE.COM', $event);
echo $createdEvent->id;
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>

Related

Outlook - Read another user's calendar

I'm developing an Android App based on Outlook-SDK-Android. The App talks with Outlook Calendar REST API to retrieve, book and delete events (see code examples here and here). Now I need to read someone else's calendar and I've been provided an Office365 account with delegate access (author permission level) towards other users.
I've registered my app using the provided account on the new portal. In my App I use the scope "https://outlook.office.com/Calendars.ReadWrite".
(The scope is used in com.microsoft.aad.adal.AuthenticationContext.acquireToken() to initialize an Office REST Client for Android OutlookClient, a shared client stack provided by orc-for-android)
When I try to read another user's calendar on which I have delegate access I just receive back a 403 response:
{
"error": {
"code": "ErrorAccessDenied",
"message": "Access is denied. Check credentials and try again."
}
}
Any help?
Is it a limitation of the API? If so why is the following method invocation chain provided then?
outlookClient.getUsers()
.getById("meetingRoom#company.com")
.getCalendarView()
UPDATE:
It seems like there are works in progress that will allow this scenario, as reported here: Office 365 REST API - Access meeting rooms calendars
So if progress in that direction has been made can I achieve my goal without using an "admin service app"? (see Office 365 API or Azure AD Graph API - Get Someone Elses Calendar)
Can I use basic authentication as suggested here?
Calendar delegation is a feature of Exchange, the Graph API and Outlook API do not allow the user to access the delegated calendar.
Currently, the alternative workaround could be use the EWS. And here is an sample for your reference:
static void DelegateAccessSearchWithFilter(ExchangeService service, SearchFilter filter)
{
// Limit the result set to 10 items.
ItemView view = new ItemView(10);
view.PropertySet = new PropertySet(ItemSchema.Subject,
ItemSchema.DateTimeReceived,
EmailMessageSchema.IsRead);
// Item searches do not support deep traversal.
view.Traversal = ItemTraversal.Shallow;
// Define the sort order.
view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
try
{
// Call FindItems to find matching calendar items.
// The FindItems parameters must denote the mailbox owner,
// mailbox, and Calendar folder.
// This method call results in a FindItem call to EWS.
FindItemsResults<Item> results = service.FindItems(
new FolderId(WellKnownFolderName.Calendar,
"fx#msdnofficedev.onmicrosoft.com"),
filter,
view);
foreach (Item item in results.Items)
{
Console.WriteLine("Subject: {0}", item.Subject);
Console.WriteLine("Id: {0}", item.Id.ToString());
}
}
catch (Exception ex)
{
Console.WriteLine("Exception while enumerating results: { 0}", ex.Message);
}
}
private static void GetDeligateCalendar(string mailAddress, string password)
{
ExchangeService service = new ExchangeService();
service.Credentials = new WebCredentials(mailAddress, password);
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.AutodiscoverUrl(mailAddress, RedirectionUrlValidationCallback);
SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(AppointmentSchema.Subject, "Discuss the Calendar REST API"));
DelegateAccessSearchWithFilter(service, sf);
}
And if you want the Outlook and Graph API to support this feature, you can try to contact the Office developer team from link below:
https://officespdev.uservoice.com/
FindMeetingTimes is currently in preview! To view the details, use this link and then change it to view the Beta version of the article (top right in the main column): https://msdn.microsoft.com/en-us/office/office365/api/calendar-rest-operations#Findmeetingtimespreview
Details below from the article, but please use the link to get the latest:
Find meeting times (preview)
Find meeting time suggestions based on organizer and attendee availability, and time or location constraints.
This operation is currently in preview and available in only the beta version.
All the supported scenarios use the FindMeetingTimes action. FindMeetingTimes accepts constraints specified as parameters in the request body, and checks the free/busy status in the primary calendars of the organizer and attendees. The response includes meeting time suggestions, each of which is defined as a MeetingTimeCandidate, with attendees having on the average a confidence level of 50% chance or higher to attend.

Google Plus Domain Api Access For Android

I am trying to integrate Google Plus and Google Plus Domain API In my android application.
I have integrated Google Plus API using Google Plus Services. It was quiet simple steps.
Now i want to fetch List of Circles by user. So i guess i need to use Google Plus Domain API . However I can not see any methods or class to Fetch Circles of user using Google Play services.
So i Goggled and found these libraries to call Google Plus Domain API.
Libraries are in this link https://code.google.com/p/google-api-java-client/wiki/Setup
As i have authenticated user from Google Play services , how to create object of PlusDomain to get List of Circles by User
Code example by Google
https://developers.google.com/+/domains/circles/listing
PlusDomains.Circles.List listCircles = plusDomains.circles().list("me");
listCircles.setMaxResults(5L);
CircleFeed circleFeed = listCircles.execute();
List<Circle> circles = circleFeed.getItems();
// Loop until no additional pages of results are available.
while (circles != null) {
for (Circle circle : circles) {
System.out.println(circle.getDisplayName());
}
// When the next page token is null, there are no additional pages of
// results. If this is the case, break.
if (circleFeed.getNextPageToken() != null) {
// Prepare the next page of results
listCircles.setPageToken(circleFeed.getNextPageToken());
// Execute and process the next page request
circleFeed = listCircles.execute();
circles = circleFeed.getItems();
} else {
circles = null;
}
}
"Domain API will work only with domain email id".
Now that the base is clear, here is the solution for your question. I know I am replying to this post very late, but I hope it will be helpful to others looking for the solution.
Steps:
Use GoogleAuthUtil to get Access token for the accountName (which is domain email address)
http://developer.android.com/reference/com/google/android/gms/auth/GoogleAuthUtil.html
String scope = “oauth2:”+ ”<profile scope>”+”<circles scope>”+.....maybe more...
// Replace <> part with scope URLs from Google Domain API scopes page
String token = GoogleAuthUtil.getToken(this, accountName , scope);
2.Initialize GoogleCredential with Access token and Initialize PlusDomain API Client with the credential from Step1.
GoogleCredential credential = new GoogleCredential().setAccessToken( token );
PlusDomains plusDomains = new PlusDomains.Builder(new NetHttpTransport, new
JacksonFactory, credential ).build();
//Example of retrieving profile
Person mePerson = plusDomains.people().get("me").execute();
//Retrieve circles, people
Note that SCOPE is very important, make sure you are providing appropriate scopes.

Java based Google App Engine, Android and authentication oauth2

Authentication and app engine, there is a lot to be read about it, but a lot seems to be outdated!
Even the google pages https://developers.google.com/appengine/docs/java/endpoints/consume_android#making-authenticated-calls
Here, they talk about 'GoogleAccountCredential.usingAudience', but nowadays, you should use GoogleAuthUtil (as far as I know, please correct me if I'm wrong).
I am trying to set up an app engine as a backend to my Android app (and in future, my iOS app).
I am using Android Studio, used the 'new module' and chose app engine with cloud messaging there.
I created a simple endpoint, and have a function there, here is some code:
public class ReviewEndpoint {
// Make sure to add this endpoint to your web.xml file if this is a web application.
private static final Logger LOG = Logger.getLogger(ReviewEndpoint.class.getName());
/**
* This method gets the <code>Review</code> object associated with the specified <code>id</code>.
* #param id The id of the object to be returned.
* #return The <code>Review</code> associated with <code>id</code>.
*/
#ApiMethod(name = "getReview")
public Review getReview(#Named("id") Long id) {
// Implement this function
Review r = new Review();
r.setData("test!");
As you can see, this is nicely generated by Android Studio. I implemented some stuf like creating the 'review' object and return it at the end.
On the Android side, I can do this:
ReviewEndpoint.Builder b = new ReviewEndpoint.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null);
ReviewEndpoint ep = b.build();
Review review = ep.getReview(1L).execute();
data = review.getData();
and yes, I get 'test!' :)
Now, I want to have this authenticated. I want to know which user wrote what, so I thought I am going to use GMail account and Facebook later.
Here I'm stuck. I am able to get a token from the user on Android:
token = GoogleAuthUtil.getToken(MainScreenActivity.this, mAccount.name, "oauth2:https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.profile");
then you are able to add this token as credential to the request:
Credential cr = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(token);
ReviewEndpoint.Builder b = new ReviewEndpoint.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), cr);
Then in the app engine I tried to get the user info, but how?
Will it be supplied as 'bearer'? How do I get this bearer token? Should I then do API request to get the data on the server?
this does not work:
OAuthService service = OAuthServiceFactory.getOAuthService();
try {
User user = service.getCurrentUser();
can anyone give me a heads up?
So finally, today, I found out how to do it! I had questions on Stackoverflow on this before and never had an answer, but these to sites gave me the answer:
https://developers.google.com/appengine/docs/java/endpoints/auth
https://developers.google.com/appengine/docs/java/endpoints/consume_android
The first shows what needs to be done on the app engine side. The second page will tell you how to get the credentials. I was quite close. I am not sure if the adjusting of the build.gradle file mentioned in the second link is necessary. What I added to the App Engine:
#Api(name = "reviewEndpoint", version = "v1", ...<<some more stuff here >>
scopes = {Constants.EMAIL_SCOPE},
clientIds = {Constants.WEB_CLIENT_ID, Constants.ANDROID_CLIENT_ID},
audiences = {Constants.ANDROID_AUDIENCE})
and then get the credentials:
// Initialize the scope using the client ID you got from the Console.
final String scope = "server:client_id:" + Constants.WEB_CLIENT_ID;
credential = GoogleAccountCredential.usingAudience(activity,scope);
You have to add the e-mail address of the user:
credential.setSelectedAccountName("some-mail-address#gmail.com");
you can get the e-mail address using the account picker (also example shown when you follow the link)
and next. you do a call to the endpoint, using the credential, I think Play Services will validate the user, because if I use an e-mail that is not logged in on the device, it will not work. The following code will throw an GoogleAuthIOException :
ReviewEndpoint.Builder b = new ReviewEndpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), id_token);
ReviewEndpoint ep = b.build();
Review review;
review = ep.getReview(1L).execute();
for testing, I've put the e-mail address I get at the server side as a string in the review object, and there it gave me the e-mail address instead of the user object being null. Ow! I forgot to tell you, you need a user argument on the app engine side. Even though you do not see the 'user' argument in the 'getReview' call above, it will be added by App Engine.
So this is how my getReview looks now:
#ApiMethod(name = "getReview")
public Review getReview(#Named("id") Long id, User user) {
// Implement this function
Review r = new Review();
r.setData("user == " + (user == null ? "NULL " : user.toString()));
Hope this will help someone

View activity list of google plus on android

I'm following the documentation of google plus list and I am using this code:
Plus.Activities.List listActivities = plus.activities().list("me", "public");
listActivities.setMaxResults(5L);
// Execute the request for the first page
ActivityFeed activityFeed = listActivities.execute();
// Unwrap the request and extract the pieces we want
List<Activity> activities = activityFeed.getItems();
// Loop through until we arrive at an empty page
while (activities != null) {
for (Activity activity : activities) {
System.out.println("ID " + activity.getId() + " Content: " +
activity.getObject().getContent());
}
// We will know we are on the last page when the next page token is null.
// If this is the case, break.
if (activityFeed.getNextPageToken() == null) {
break;
}
// Prepare to request the next page of activities
listActivities.setPageToken(activityFeed.getNextPageToken());
// Execute and process the next page request
activityFeed = listActivities.execute();
activities = activityFeed.getItems();
This does not work because I have to create a client object. I tried more example but I do not understand how to do. Now:
How do I create a client object?
Where do I insert this client object?
I've seen a lot of answers but none work. You can Help me.
The comment that proceeded that code sample asked you to take a look at the Google+ Java quickstart, see the source file in question for how to set up your credentials and Plus client. You'll also need to authorize your request, that sample project shows how to use Google+ Sign-In to authorize the user to get an access token. You must have an authorized user to search with "me".
This sample is Java code using the Google Java API client library, the Android SDK doesn't include the client library by default, so you'd need to import that into your project.
I think you should take a look at this project : google API calendar
It works exactly like that with the G+ API.

Android Facebook events invite

I'm developing an android application where I have to invite facebook friends to an event using Rest API.
Below is the code where I prepare bundle of parameters
Bundle eventInviteParams = new Bundle();
eventInviteParams.putString("method", "events.invite");
eventInviteParams.putString("eid", event.getFacebookEventId());
eventInviteParams.putString("personal_message", "Sample message");
String userIds = "";
for (int i = 0; i < facebookAdapter.getCount(); i++) {
FacebookUser user = facebookAdapter.getItem(i);
if (user.isSelected()) {
userIds += user.getId() + ",";
}
}
if (userIds.length() > 0) {
userIds = userIds.substring(0, userIds.length() - 1); // to remove last comma
eventInviteParams.putString("uids", userIds);
}
Then
response = mFacebook.request(eventInviteParams);
where mFacebook is Facebook api object.
The response is always
{"error_code":200,"error_msg":"Permissions
error","request_args":[{"key":"uids","value":"XXXXXXXXX,XXXXXXXXX"},{"key":"method","value":"events.invite"},{"key":"format","value":"json"},{"key":"eid","value":"XXXXXXXXXXX"},....]}
Application has following permissions
"email","publish_stream","read_stream","create_event","offline_access","user_events","friends_events","rsvp_event"
I want also to mention that I'm not event creator. I have searched on FCB docs and google but cannot find a proper answer.
Thank you very much for your response.
I continued with research and I found that the error
"error_code":200,"error_msg":"Permissions error"
was because I was not following the event. Once I RSVP to the event, I got the response false (I don't know why) and the error gone. I checked in Facebook and the given people were invited.
thanks
Only the user that has created the event can invite people to it. Even if the user has created the event with "Guests can invite friends" it seems that it is impossible to do it from an app. A few weeks ago I tried several methods to no avail!
The events.invite api is broken ..check it out on the facebook bugzilla http://bugs.developers.facebook.net/show_bug.cgi?id=17057

Categories

Resources