Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MainActivity extends AppCompatActivity {
- static final int REQUEST_ACCOUNT_PICKER = 1000;
- static final int REQUEST_AUTHORIZATION = 1001;
- static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;
- private static final String[] SCOPES = {CalendarScopes.CALENDAR_READONLY, CalendarScopes.CALENDAR};
- private static final String PREF_ACCOUNT_NAME = "accountName";
- GoogleAccountCredential mCredential;
- ProgressDialog mProgress;
- TextView tv;
- private String myaccountName;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
- ///////////////////////////////c2 Manages Intent from SignIn/////////////////
- Intent inn = getIntent();
- Bundle extras = inn.getExtras();
- if (extras != null) {
- // Intent inn=getIntent();
- myaccountName = extras.getString("accountName");
- SharedPreferences.Editor editor = settings.edit();
- editor.putString(PREF_ACCOUNT_NAME, myaccountName);
- editor.apply();
- }
- tv = (TextView) findViewById(R.id.result1);
- if (myaccountName != null) {
- mCredential = GoogleAccountCredential.usingOAuth2(
- getApplicationContext(), Arrays.asList(SCOPES))
- .setBackOff(new ExponentialBackOff())
- .setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));
- }
- tv.setVerticalScrollBarEnabled(true);
- tv.setMovementMethod(new ScrollingMovementMethod());
- mProgress = new ProgressDialog(this);
- mProgress.setMessage("Getting Your Data Champ :-) ");
- //////////////// CODE NEW///////////////////
- mService = new com.google.api.services.calendar.Calendar.Builder(
- transport, jsonFactory, mCredential)
- .setApplicationName("MeetingPlanner")
- .build();
- btnEvent = (Button) findViewById(R.id.evt_button);
- btnEvent.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- Log.d("Meeting Planner: ",mService.toString());
- new CreateEventTask(mService).execute();
- }
- });
- ///////////////////////////////////
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- switch (requestCode) {
- case REQUEST_GOOGLE_PLAY_SERVICES:
- if (resultCode != RESULT_OK) {
- isGooglePlayServicesAvailable();
- }
- break;
- case REQUEST_ACCOUNT_PICKER:
- if (resultCode == RESULT_CANCELED) {
- tv.setText("Account unspecified.");
- }
- }
- super.onActivityResult(requestCode, resultCode, data);
- }
- @Override
- protected void onResume() {
- super.onResume();
- if (isGooglePlayServicesAvailable()) {
- refreshResults();
- } else {
- tv.setText("Google Play Services required: " +
- "after installing, close and relaunch this app.");
- }
- }
- private void refreshResults() {
- if (isDeviceOnline()) {
- new MakeRequestTask(mCredential).execute();
- } else {
- tv.setText("No network connection available.");
- }
- }
- private boolean isDeviceOnline() {
- ConnectivityManager connMgr =
- (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
- return (networkInfo != null && networkInfo.isConnected());
- }
- private boolean isGooglePlayServicesAvailable() {
- final int connectionStatusCode =
- GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
- if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
- showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
- return false;
- } else if (connectionStatusCode != ConnectionResult.SUCCESS) {
- return false;
- }
- return true;
- }
- void showGooglePlayServicesAvailabilityErrorDialog(
- final int connectionStatusCode) {
- Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
- connectionStatusCode,
- MainActivity.this,
- REQUEST_GOOGLE_PLAY_SERVICES);
- dialog.show();
- }
- private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
- private com.google.api.services.calendar.Calendar mService = null;
- private Exception mLastError = null;
- public MakeRequestTask(GoogleAccountCredential credential) {
- HttpTransport transport = AndroidHttp.newCompatibleTransport();
- JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
- mService = new com.google.api.services.calendar.Calendar.Builder(
- transport, jsonFactory, credential)
- //.setApplicationName("Google Calendar API Android Quickstart")
- .build();
- }
- /**
- * Background task to call Google Calendar API.
- *
- * @param params no parameters needed for this task.
- */
- @Override
- protected List<String> doInBackground(Void... params) {
- try {
- return getDataFromApi();
- } catch (Exception e) {
- mLastError = e;
- cancel(true);
- return null;
- }
- }
- /**
- * Fetch a list of the next 10 events from the primary calendar.
- *
- * @return List of Strings describing returned events.
- * @throws IOException
- */
- private List<String> getDataFromApi() throws IOException, ParseException {
- // List the next 10 events from the primary calendar.
- DateTime now = new DateTime(System.currentTimeMillis());
- List<String> eventStrings = new ArrayList<String>();
- Events events = mService.events().list("primary")
- .setMaxResults(30)
- .setTimeMin(now)
- .setOrderBy("startTime")
- .setSingleEvents(true)
- .execute();
- List<Event> items = events.getItems();
- for (Event event : items) {
- DateTime start = event.getStart().getDateTime();
- if (start == null) {
- // All-day events don't have start times, so just use
- // the start date.
- start = event.getStart().getDate();
- }
- DateTime end = event.getEnd().getDateTime();
- String eventTitle = event.getSummary();
- String StartDB = String.valueOf(start);
- String EndDB = String.valueOf(end);
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
- Calendar cal = Calendar.getInstance();
- cal.setTime(sdf.parse(StartDB));
- SimpleDateFormat[] dateFormat= new SimpleDateFormat[2];
- dateFormat[0] = new SimpleDateFormat("yyyy-MM-dd");
- dateFormat[1] = new SimpleDateFormat("HH:mm:ss");
- String Start_Date= dateFormat[0].format(cal.getTime());
- String Start_Time= dateFormat[1].format(cal.getTime());
- Calendar cal1 = Calendar.getInstance();
- cal1.setTime(sdf.parse(EndDB));
- String End_Date= dateFormat[0].format(cal1.getTime());
- String End_Time= dateFormat[1].format(cal1.getTime());
- String Location = event.getLocation();
- String Creator = String.valueOf(event.getCreator());
- Creator = Creator.replace(""", ""); //Removes all the Quotes from the string displayName:Qamran Rajput,email:qami1502@gmail.com,self:true}
- StringTokenizer tokens = new StringTokenizer(Creator, ":");
- tokens.nextToken();
- String first = tokens.nextToken();// this will contain Qamran Rajput,email
- String second = tokens.nextToken();/////////////////qami1502@gmail.com,self
- StringTokenizer tokens1 = new StringTokenizer(first, ",");
- String creatorName = tokens1.nextToken();// this will contain Qamran Rajput
- StringTokenizer tokens2 = new StringTokenizer(second, ",");
- String creatorEmail = tokens2.nextToken();/////////////////qami1502@gmail.com
- String mFlag= "0";
- new Datasync().execute(eventTitle, Start_Date, End_Date, Start_Time, End_Time, creatorEmail, mFlag, Location);
- // TODO
- Log.d("Title :", eventTitle);
- Log.d("Name :", creatorName);
- Log.d("Start Date :", Start_Date);
- Log.d("End Date :", End_Date );
- Log.d("Start Time :", Start_Time );
- Log.d("End Time :", End_Time );
- Log.d("Email :", creatorEmail);
- Log.d("Location :", Location );
- eventStrings.add(
- String.format("%s (%s)", event.getSummary(), start));
- }
- return eventStrings;
- }
- @Override
- protected void onPreExecute() {
- tv.setText("");
- mProgress.show();
- }
- @Override
- protected void onPostExecute(List<String> output) {
- mProgress.hide();
- if (output == null || output.size() == 0) {
- tv.setText("No results returned.");
- } else {
- output.add(0, "Data retrieved using the Google Calendar API:");
- tv.setText(TextUtils.join("n", output));
- }
- }
- @Override
- protected void onCancelled() {
- mProgress.hide();
- if (mLastError != null) {
- if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
- showGooglePlayServicesAvailabilityErrorDialog(
- ((GooglePlayServicesAvailabilityIOException) mLastError)
- .getConnectionStatusCode());
- } else if (mLastError instanceof UserRecoverableAuthIOException) {
- startActivityForResult(
- ((UserRecoverableAuthIOException) mLastError).getIntent(),
- MainActivity.REQUEST_AUTHORIZATION);
- } else {
- tv.setText("The following error occurred:n"
- + mLastError.getMessage());
- }
- } else {
- tv.setText("Request cancelled.");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement