Reputation: 17
How to get view count from YouTube APIs for android : I am unable to find any document related to getViewCount from YouTube APIs for Android. There is information available for java in general but not for android. I am stuck please help.
Upvotes: 0
Views: 2828
Reputation: 3118
https://www.googleapis.com/youtube/v3/videos?part=statistics&id={{VIDEO-ID}}&key={{YOUR-KEY}}
And under the JSONObject for statistics is a field called "viewCount"
Documentation to help you: https://developers.google.com/youtube/v3/docs/videos#resource
Here is the sample when you add the statistics part:
{
"kind": "youtube#videoListResponse",
"etag": etag,
"pageInfo": {
"totalResults": integer,
"resultsPerPage": integer
},
"items": [
{
"kind": "youtube#video",
"etag": etag,
"id": string,
"statistics": {
"viewCount": unsigned long,
"likeCount": unsigned long,
"dislikeCount": unsigned long,
"favoriteCount": unsigned long,
"commentCount": unsigned long
}
}
]
Just grab the JSONObject called "statistics" and then directly access the field "viewCount".
JSONArray items = response.getJSONArray("items");
JSONObject statistics = items.getJSONObject(0).getJSONObject("statistics");
Long views = statistics.getLong("viewCount");
EDIT: to show an actual response and proper access
Add the Youtube API v3 dependency to your project in the app build.gradle folder:
dependencies {
compile 'com.google.apis:google-api-services-youtube:v3-rev152-1.21.0'
}
That is the header, or jar file, in question you need. Then you can instantiate a YouTube object like I showed above:
YouTube youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer());
YouTube.Videos.List videoRequest = youtube.videos().list("contentDetails");
videoRequest.setId("SOME-VIDEO-ID");
videoRequest.setFields("items/contentDetails");
videoRequest.setKey("YOUR-API-KEY");
VideoListResponse response = videoRequest.execute(); //blocking call, ensure to perform off ui thread via AsyncTask
List<Video> videosList = response.getItems();
if(videosList != null && videosList.size() > 0){
Video video = videosList.get(0);
VideoStatistics statistics = video.getStatistics();
BigInteger viewCount = statistics.getViewCount();
}
Upvotes: 1