Advertisement
Guest User

Untitled

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