Advertisement
Guest User

Untitled

a guest
Dec 24th, 2015
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.92 KB | None | 0 0
  1. static final int REQUEST_ACCOUNT_PICKER = 1000;
  2. static final int REQUEST_AUTHORIZATION = 1001;
  3. static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;
  4. private static final String[] SCOPES = {CalendarScopes.CALENDAR_READONLY, CalendarScopes.CALENDAR};
  5. private static final String PREF_ACCOUNT_NAME = "accountName";
  6. GoogleAccountCredential mCredential;
  7. ProgressDialog mProgress;
  8. TextView tv;
  9. private String myaccountName;
  10.  
  11. @Override
  12. protected void onCreate(Bundle savedInstanceState) {
  13. super.onCreate(savedInstanceState);
  14. setContentView(R.layout.activity_main);
  15. SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
  16. ///////////////////////////////c2 Manages Intent from SignIn/////////////////
  17. Intent inn = getIntent();
  18. Bundle extras = inn.getExtras();
  19. if (extras != null) {
  20. // Intent inn=getIntent();
  21. myaccountName = extras.getString("accountName");
  22. SharedPreferences.Editor editor = settings.edit();
  23. editor.putString(PREF_ACCOUNT_NAME, myaccountName);
  24. editor.apply();
  25. }
  26.  
  27. tv = (TextView) findViewById(R.id.result1);
  28. if (myaccountName != null) {
  29. mCredential = GoogleAccountCredential.usingOAuth2(
  30. getApplicationContext(), Arrays.asList(SCOPES))
  31. .setBackOff(new ExponentialBackOff())
  32. .setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));
  33. }
  34.  
  35. tv.setVerticalScrollBarEnabled(true);
  36. tv.setMovementMethod(new ScrollingMovementMethod());
  37. mProgress = new ProgressDialog(this);
  38. mProgress.setMessage("Getting Your Data Champ :-) ");
  39.  
  40. //////////////// CODE NEW///////////////////
  41. mService = new com.google.api.services.calendar.Calendar.Builder(
  42. transport, jsonFactory, mCredential)
  43. .setApplicationName("MeetingPlanner")
  44. .build();
  45. btnEvent = (Button) findViewById(R.id.evt_button);
  46. btnEvent.setOnClickListener(new View.OnClickListener() {
  47.  
  48. @Override
  49. public void onClick(View view) {
  50. Log.d("Meeting Planner: ",mService.toString());
  51. new CreateEventTask(mService).execute();
  52. }
  53. });
  54. ///////////////////////////////////
  55.  
  56. }
  57.  
  58. @Override
  59. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  60. super.onActivityResult(requestCode, resultCode, data);
  61. switch (requestCode) {
  62. case REQUEST_GOOGLE_PLAY_SERVICES:
  63. if (resultCode != RESULT_OK) {
  64. isGooglePlayServicesAvailable();
  65. }
  66. break;
  67. case REQUEST_ACCOUNT_PICKER:
  68. if (resultCode == RESULT_CANCELED) {
  69. tv.setText("Account unspecified.");
  70. }
  71. }
  72. super.onActivityResult(requestCode, resultCode, data);
  73. }
  74.  
  75. @Override
  76. protected void onResume() {
  77. super.onResume();
  78. if (isGooglePlayServicesAvailable()) {
  79. refreshResults();
  80. } else {
  81. tv.setText("Google Play Services required: " +
  82. "after installing, close and relaunch this app.");
  83. }
  84. }
  85.  
  86. private void refreshResults() {
  87. if (isDeviceOnline()) {
  88. new MakeRequestTask(mCredential).execute();
  89. } else {
  90. tv.setText("No network connection available.");
  91. }
  92. }
  93.  
  94. private boolean isDeviceOnline() {
  95. ConnectivityManager connMgr =
  96. (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  97. NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
  98. return (networkInfo != null && networkInfo.isConnected());
  99. }
  100.  
  101. private boolean isGooglePlayServicesAvailable() {
  102. final int connectionStatusCode =
  103. GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
  104. if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
  105. showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
  106. return false;
  107. } else if (connectionStatusCode != ConnectionResult.SUCCESS) {
  108. return false;
  109. }
  110. return true;
  111. }
  112.  
  113. void showGooglePlayServicesAvailabilityErrorDialog(
  114. final int connectionStatusCode) {
  115. Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
  116. connectionStatusCode,
  117. MainActivity.this,
  118. REQUEST_GOOGLE_PLAY_SERVICES);
  119. dialog.show();
  120. }
  121.  
  122. private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
  123. private com.google.api.services.calendar.Calendar mService = null;
  124. private Exception mLastError = null;
  125.  
  126. public MakeRequestTask(GoogleAccountCredential credential) {
  127. HttpTransport transport = AndroidHttp.newCompatibleTransport();
  128. JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  129. mService = new com.google.api.services.calendar.Calendar.Builder(
  130. transport, jsonFactory, credential)
  131. //.setApplicationName("Google Calendar API Android Quickstart")
  132. .build();
  133. }
  134.  
  135. /**
  136. * Background task to call Google Calendar API.
  137. *
  138. * @param params no parameters needed for this task.
  139. */
  140. @Override
  141. protected List<String> doInBackground(Void... params) {
  142. try {
  143. return getDataFromApi();
  144. } catch (Exception e) {
  145. mLastError = e;
  146. cancel(true);
  147. return null;
  148. }
  149. }
  150.  
  151. /**
  152. * Fetch a list of the next 10 events from the primary calendar.
  153. *
  154. * @return List of Strings describing returned events.
  155. * @throws IOException
  156. */
  157. private List<String> getDataFromApi() throws IOException, ParseException {
  158. // List the next 10 events from the primary calendar.
  159. DateTime now = new DateTime(System.currentTimeMillis());
  160. List<String> eventStrings = new ArrayList<String>();
  161. Events events = mService.events().list("primary")
  162. .setMaxResults(30)
  163. .setTimeMin(now)
  164. .setOrderBy("startTime")
  165. .setSingleEvents(true)
  166. .execute();
  167. List<Event> items = events.getItems();
  168.  
  169. for (Event event : items) {
  170. DateTime start = event.getStart().getDateTime();
  171. if (start == null) {
  172. // All-day events don't have start times, so just use
  173. // the start date.
  174. start = event.getStart().getDate();
  175. }
  176. DateTime end = event.getEnd().getDateTime();
  177.  
  178. String eventTitle = event.getSummary();
  179.  
  180. String StartDB = String.valueOf(start);
  181. String EndDB = String.valueOf(end);
  182.  
  183. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
  184.  
  185. Calendar cal = Calendar.getInstance();
  186. cal.setTime(sdf.parse(StartDB));
  187.  
  188. SimpleDateFormat[] dateFormat= new SimpleDateFormat[2];
  189. dateFormat[0] = new SimpleDateFormat("yyyy-MM-dd");
  190. dateFormat[1] = new SimpleDateFormat("HH:mm:ss");
  191.  
  192. String Start_Date= dateFormat[0].format(cal.getTime());
  193. String Start_Time= dateFormat[1].format(cal.getTime());
  194.  
  195. Calendar cal1 = Calendar.getInstance();
  196. cal1.setTime(sdf.parse(EndDB));
  197.  
  198. String End_Date= dateFormat[0].format(cal1.getTime());
  199. String End_Time= dateFormat[1].format(cal1.getTime());
  200.  
  201. String Location = event.getLocation();
  202.  
  203. String Creator = String.valueOf(event.getCreator());
  204. Creator = Creator.replace(""", ""); //Removes all the Quotes from the string displayName:Qamran Rajput,email:qami1502@gmail.com,self:true}
  205.  
  206. StringTokenizer tokens = new StringTokenizer(Creator, ":");
  207. tokens.nextToken();
  208. String first = tokens.nextToken();// this will contain Qamran Rajput,email
  209. String second = tokens.nextToken();/////////////////qami1502@gmail.com,self
  210. StringTokenizer tokens1 = new StringTokenizer(first, ",");
  211. String creatorName = tokens1.nextToken();// this will contain Qamran Rajput
  212. StringTokenizer tokens2 = new StringTokenizer(second, ",");
  213. String creatorEmail = tokens2.nextToken();/////////////////qami1502@gmail.com
  214.  
  215. String mFlag= "0";
  216.  
  217. new Datasync().execute(eventTitle, Start_Date, End_Date, Start_Time, End_Time, creatorEmail, mFlag, Location);
  218. // TODO
  219. Log.d("Title :", eventTitle);
  220. Log.d("Name :", creatorName);
  221. Log.d("Start Date :", Start_Date);
  222. Log.d("End Date :", End_Date );
  223. Log.d("Start Time :", Start_Time );
  224. Log.d("End Time :", End_Time );
  225. Log.d("Email :", creatorEmail);
  226. Log.d("Location :", Location );
  227.  
  228. eventStrings.add(
  229. String.format("%s (%s)", event.getSummary(), start));
  230. }
  231. return eventStrings;
  232. }
  233.  
  234.  
  235. @Override
  236. protected void onPreExecute() {
  237. tv.setText("");
  238. mProgress.show();
  239. }
  240.  
  241. @Override
  242. protected void onPostExecute(List<String> output) {
  243. mProgress.hide();
  244. if (output == null || output.size() == 0) {
  245. tv.setText("No results returned.");
  246. } else {
  247. output.add(0, "Data retrieved using the Google Calendar API:");
  248. tv.setText(TextUtils.join("n", output));
  249. }
  250. }
  251.  
  252. @Override
  253. protected void onCancelled() {
  254. mProgress.hide();
  255. if (mLastError != null) {
  256. if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
  257. showGooglePlayServicesAvailabilityErrorDialog(
  258. ((GooglePlayServicesAvailabilityIOException) mLastError)
  259. .getConnectionStatusCode());
  260. } else if (mLastError instanceof UserRecoverableAuthIOException) {
  261. startActivityForResult(
  262. ((UserRecoverableAuthIOException) mLastError).getIntent(),
  263. MainActivity.REQUEST_AUTHORIZATION);
  264. } else {
  265. tv.setText("The following error occurred:n"
  266. + mLastError.getMessage());
  267. }
  268. } else {
  269. tv.setText("Request cancelled.");
  270. }
  271. }
  272. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement