23
23
import java .util .Iterator ;
24
24
import java .util .List ;
25
25
26
- /**
27
- * An asynchronous task that handles the YouTube Data API call.
28
- * Placing the API calls in their own task ensures the UI stays responsive.
29
- */
26
+
30
27
public class MakeRequestTask extends AsyncTask <Void , Void , YoutubeUser > {
31
28
32
29
private com .google .api .services .youtube .YouTube mService = null ;
33
- private Exception mLastError = null ;
30
+ private GoogleAccountCredential credential ;
34
31
private ProgressDialog mProgress ;
35
32
private YoutubeUser youtubeUser ;
36
- private RequestInfo ri = RequestInfo .getInstance ();
37
-
38
- private static final int REQUEST_AUTHORIZATION = 1001 ;
33
+ private RequestInfo ri ;
39
34
40
35
MakeRequestTask (GoogleAccountCredential credential , ProgressDialog pd ) {
36
+ this .credential =credential ;
41
37
HttpTransport transport = AndroidHttp .newCompatibleTransport ();
42
38
JsonFactory jsonFactory = JacksonFactory .getDefaultInstance ();
43
39
mService = new com .google .api .services .youtube .YouTube .Builder (
44
40
transport , jsonFactory , credential )
45
41
.setApplicationName ("DataApi" )
46
42
.build ();
43
+ this .ri = RequestInfo .getInstance ();
47
44
this .mProgress = pd ;
48
- youtubeUser = new YoutubeUser ();
45
+ this . youtubeUser = new YoutubeUser ();
49
46
}
50
47
51
- /**
52
- * Background task to call YouTube Data API.
53
- * @param params no parameters needed for this task.
54
- */
55
48
@ Override
56
49
protected YoutubeUser doInBackground (Void ... params ) {
57
50
getDataFromApi ();
58
- return null ;
59
- }
60
-
61
- /**
62
- * Fetch information about the "GoogleDevelopers" YouTube channel.
63
- * @return List of Strings containing information about the channel.
64
- * @throws IOException
65
- */
66
- private List <String > getPrimaryData () throws IOException {
67
- // Get a list of up to 10 files.
68
- List <String > channelInfo = new ArrayList <String >();
69
- ChannelListResponse result = mService .channels ().list ("snippet,contentDetails,statistics" )
70
- .setMine (true )
71
- .execute ();
72
- List <Channel > channels = result .getItems ();
73
- if (channels != null ) {
74
- Channel channel = channels .get (0 );
75
- youtubeUser .addInformation (channel .getId (), channel .getSnippet ().getTitle (), channel .getStatistics ().getViewCount (), channel .getContentDetails ().getRelatedPlaylists ().getUploads ());
76
- channelInfo .add ("This channel's ID is " + channel .getId () + ". " +
77
- "Its title is '" + channel .getSnippet ().getTitle () + ", " +
78
- "and it has " + channel .getStatistics ().getViewCount () + " views." +
79
- "playslist upload : " + channel .getContentDetails ().getRelatedPlaylists ().getUploads ());
80
- }
81
- return channelInfo ;
51
+ return youtubeUser ;
82
52
}
83
53
84
54
private void getDataFromApi () {
85
- try {
86
- ChannelListResponse channelResult = mService .channels ().list ("snippet,contentDetails,statistics" )
55
+ ChannelListResponse channelResult = null ;
56
+ try {
57
+ channelResult = mService .channels ().list ("snippet,contentDetails,statistics" )
87
58
.setMine (true )
88
59
.setFields ("items/contentDetails,nextPageToken,pageInfo" )
89
60
.execute ();
90
61
91
62
System .out .println (channelResult );
92
63
64
+
93
65
List <Channel > channelsList = channelResult .getItems ();
94
66
95
67
if (channelsList != null ) {
68
+
96
69
System .out .println (channelsList .get (0 ));
70
+
71
+ youtubeUser .addUpload (channelsList .get (0 ).getContentDetails ().getRelatedPlaylists ().getUploads ());
72
+
97
73
// The user's default channel is the first item in the list.
98
74
// Extract the playlist ID for the channel's videos from the
99
75
// API response.
@@ -128,7 +104,7 @@ private void getDataFromApi() {
128
104
} while (nextToken != null );
129
105
130
106
// Prints information about the results.
131
- processPrint ( playlistItemList . size (), playlistItemList .iterator ());
107
+ processInfo ( playlistItemList .iterator ());
132
108
}
133
109
134
110
} catch (GoogleJsonResponseException e ) {
@@ -140,63 +116,18 @@ private void getDataFromApi() {
140
116
}
141
117
}
142
118
143
- private void getDataFromApiWithName (String name ) {
144
- try {
145
- ChannelListResponse channelResult = mService .channels ().list ("snippet,contentDetails,statistics" )
146
- .setForUsername (name )
147
- .setFields ("items/contentDetails,nextPageToken,pageInfo" )
148
- .execute ();
149
-
150
- System .out .println (channelResult );
151
-
152
- List <Channel > channelsList = channelResult .getItems ();
153
-
154
- if (channelsList != null ) {
155
- System .out .println (channelsList .get (0 ));
156
- // The user's default channel is the first item in the list.
157
- // Extract the playlist ID for the channel's videos from the
158
- // API response.
159
- String uploadPlaylistId =
160
- channelsList .get (0 ).getContentDetails ().getRelatedPlaylists ().getUploads ();
161
-
162
- // Define a list to store items in the list of uploaded videos.
163
- List <PlaylistItem > playlistItemList = new ArrayList <PlaylistItem >();
164
-
165
- // Retrieve the playlist of the channel's uploaded videos.
166
- YouTube .PlaylistItems .List playlistItemRequest =
167
- mService .playlistItems ().list ("id,contentDetails,snippet" );
168
- playlistItemRequest .setPlaylistId (uploadPlaylistId );
169
-
170
- // Only retrieve data used in this application, thereby making
171
- // the application more efficient. See:
172
- // https://developers.google.com/youtube/v3/getting-started#partial
173
- playlistItemRequest .setFields ("items(contentDetails/videoId,snippet/title,snippet/publishedAt),nextPageToken,pageInfo" );
174
-
175
- String nextToken = "" ;
176
-
177
- // Call the API one or more times to retrieve all items in the
178
- // list. As long as the API response returns a nextPageToken,
179
- // there are still more items to retrieve.
180
- do {
181
- playlistItemRequest .setPageToken (nextToken );
182
- PlaylistItemListResponse playlistItemResult = playlistItemRequest .execute ();
183
-
184
- playlistItemList .addAll (playlistItemResult .getItems ());
185
-
186
- nextToken = playlistItemResult .getNextPageToken ();
187
- } while (nextToken != null );
119
+ private void processInfo (Iterator <PlaylistItem > playlistEntries ) {
188
120
189
- // Prints information about the results.
190
- processPrint (playlistItemList .size (), playlistItemList .iterator ());
191
- }
192
-
193
- } catch (GoogleJsonResponseException e ) {
194
- e .printStackTrace ();
195
- System .err .println ("There was a service error: " + e .getDetails ().getCode () + " : " + e .getDetails ().getMessage ());
121
+ List <YoutubeVideo > myVideo = new ArrayList <>();
196
122
197
- } catch (Throwable t ) {
198
- t .printStackTrace ();
123
+ while (playlistEntries .hasNext ()) {
124
+ PlaylistItem playlistItem = playlistEntries .next ();
125
+ YoutubeVideo vid = new YoutubeVideo (playlistItem .getSnippet ().getTitle (),
126
+ playlistItem .getContentDetails ().getVideoId (),
127
+ playlistItem .getSnippet ().getPublishedAt ().toString ());
128
+ myVideo .add (vid );
199
129
}
130
+ youtubeUser .addVideoContent (myVideo );
200
131
}
201
132
202
133
@ Override
@@ -213,56 +144,17 @@ protected void onPostExecute(YoutubeUser output) {
213
144
} else {
214
145
ri .addInfo ("Data retrieved using the YouTube Data API:" );
215
146
}
147
+ System .out .println (output .toString ());
148
+ if (output .getNbVideo () == 0 ) {
149
+ System .out .println ("Launch the second asynchronous task" );
150
+ //new MakeRequestTaskName(this.credential,this.mProgress, youtubeUser.getPossibleUserName()).execute();
151
+ }
216
152
}
217
153
218
154
@ Override
219
155
protected void onCancelled () {
220
156
mProgress .hide ();
221
- if (mLastError != null ) {
222
- if (mLastError instanceof GooglePlayServicesAvailabilityIOException ) {
223
- int connectionStatusCode = ((GooglePlayServicesAvailabilityIOException ) mLastError ).getConnectionStatusCode ();
224
- ri .addStatus (connectionStatusCode );
225
- } else if (mLastError instanceof UserRecoverableAuthIOException ) {
226
- ri .addStatus (this .REQUEST_AUTHORIZATION );
227
- } else {
228
- ri .addInfo ("The following error occurred:\n " +mLastError .getMessage ());
229
- }
230
- } else {
231
- ri .addInfo ("Request cancelled." );
232
- }
157
+ ri .addInfo ("Request cancelled." );
233
158
}
234
159
235
-
236
- /*
237
- * Print information about all of the items in the playlist.
238
- *
239
- * @param size size of list
240
- *
241
- * @param iterator of Playlist Items from uploaded Playlist
242
- */
243
- private void processPrint (int size , Iterator <PlaylistItem > playlistEntries ) {
244
-
245
- List <YoutubeVideo > myVideo = new ArrayList <>();
246
-
247
- System .out .println ("=============================================================" );
248
- System .out .println ("\t \t Total Videos Uploaded: " + size );
249
- System .out .println ("=============================================================\n " );
250
-
251
- while (playlistEntries .hasNext ()) {
252
-
253
- PlaylistItem playlistItem = playlistEntries .next ();
254
-
255
- System .out .println (" video name = " + playlistItem .getSnippet ().getTitle ());
256
- System .out .println (" video id = " + playlistItem .getContentDetails ().getVideoId ());
257
- System .out .println (" upload date = " + playlistItem .getSnippet ().getPublishedAt ());
258
- System .out .println ("\n -------------------------------------------------------------\n " );
259
-
260
- YoutubeVideo vid = new YoutubeVideo (playlistItem .getSnippet ().getTitle (),
261
- playlistItem .getContentDetails ().getVideoId (),
262
- playlistItem .getSnippet ().getPublishedAt ().toString ());
263
- myVideo .add (vid );
264
-
265
- }
266
- youtubeUser .addVideoContent (myVideo );
267
- }
268
160
}
0 commit comments