How to search videos with youtube data API in Android - android

I'm developing an application in Android which needs to search for videos of YouTube by Keyword. I have used Youtube data API with the code below:
try {
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("YoutubeQoE").build();
// Define the API request for retrieving search results.
YouTube.Search.List search = youtube.search().list("id,snippet");
// Set your developer key from the Google Cloud Console for
// non-authenticated requests. See:
// https://cloud.google.com/console
search.setKey(DeveloperKey.DEVELOPER_KEY);
search.setQ("dogs");
// Restrict the search results to only include videos. See:
// https://developers.google.com/youtube/v3/docs/search/list#type
search.setType("video");
// To increase efficiency, only retrieve the fields that the
// application uses.
//search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
search.setMaxResults(25);
SearchListResponse searchResponse = search.execute();
List<SearchResult> lista = searchResponse.getItems();
} catch (GoogleJsonResponseException e) {
System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
} catch (IOException e) {
System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
For de DEVELOPER_KEY I have used a public API access at google developer console.
But when I execute the program there is a problem in the line:
SearchListResponse searchResponse = search.execute();
In the android manifest.xml I have these permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
I would be very grateful if anybody could help me

Another way of achieving this would be getting results from this:
https://www.googleapis.com/youtube/v3/search?part=snippet&q=eminem&type=video&key=<key>
You can play with parameters to get what you actually need. You also need an API key from https://console.developers.google.com/.

You can compare your project against YouTube Direct Lite for Android. Yes, instead of OAuth2, setting API key would be enough.

Generally, this error occurs when someone tries to perform network calls on UI Thread, which is not allowed in Android.
check logcat if you get this error - (error-android-os-networkonmainthreadexception)
Go through this answer for the solution to this problem - fix of neworkonmainthreadexception

Related

android youtube data api

I am trying to find the details of a youtube video through its ID (example ->
yb7E4lQIaZI). I read that if we just want the details we can use the api_key from the developer console. if we want to do operations such as upload a video we need to use oauth. I just want to go with the firstcase. i just need the details of the video like thumnail url and title which i want to show in a listview.
I am trying to do this with the use of my api_key but i cant make it to work.The last line (system.out.println) is not printing anything. The code i have written is below
try {
YouTube youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new
HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("my_project").build();
HashMap<String, String> parameters = new HashMap<>();
parameters.put("part", "snippet,contentDetails,statistics");
parameters.put("id", "yb7E4lQIaZI");
YouTube.Videos.List videosListByIdRequest = youtube.videos().list(parameters.get("part").toString());
videosListByIdRequest.setKey(MY_API_KEY_FROM_DEVELOPER_CONSOLE);
if (parameters.containsKey("id") && parameters.get("id") != "") {
videosListByIdRequest.setId(parameters.get("id").toString());
}
VideoListResponse response = videosListByIdRequest.execute();
System.out.println(response);
} catch (GoogleJsonResponseException e) {
e.printStackTrace();
System.err.println("There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
When i run the debug it exits after the line 'VideoListResponse response = videosListByIdRequest.execute();' and doesnot go to the line 'System.out.println(response)'.
The app doesnot crash or show any error, it just doesnt go to the 'system.out.print' line
Did you check if you have added internet permission in your manifest.
<uses-permission android:name="android.permission.INTERNET" />

Error 200 (job canceled) when streaming data from Android to BigQuery

I've been trying to build some functionality into my app too allow user-generated data (EEG recordings) to be sent to a central BigQuery database.
I've never done any networking code in Java before, so I shied away from doing the POST or REST-based strategies recommended here. The BigQuery Java client library seemed to be exactly what I needed, though I was completely confused why it wouldn't officially support Android.
Still, I came across this example Android app (from Google no less) that promised to do exactly what I wanted with the BigQuery Client library. I incorporated it into my app as follows:
// .... in an AsyncTask
#Override
protected String doInBackground(String... params) {
String CSV_CONTENT = params[0];
try {
AssetManager am = MainApplication.getInstance().getAssets();
InputStream isCredentialsFile = am.open(CREDENTIALS_FILE);
BigQuery bigquery = BigQueryOptions.builder()
.authCredentials(AuthCredentials.createForJson(isCredentialsFile))
.projectId( PROJECT_ID )
.build().service();
TableId tableId = TableId.of(DATASET,TABLE);
Table table = bigquery.getTable(tableId);
int num = 0;
Log.d("Main", "Sending CSV: ");
WriteChannelConfiguration configuration = WriteChannelConfiguration.builder(tableId)
.formatOptions(FormatOptions.csv())
.build();
try (WriteChannel channel = bigquery.writer(configuration)) {
num = channel.write(ByteBuffer.wrap(CSV_CONTENT.getBytes(StandardCharsets.UTF_8)));
} catch (Exception e) {
Log.d("Main", e.toString());
}
Log.d("Main", "Loading " + Integer.toString(num) + " bytes into table " + tableId);
} catch (Exception e) {
Log.d("Main", "Exception: " + e.toString());
}
return "Done";
}
This runs without any errors and fires off an API call that is detected by Google Cloud Storage. However, it returns error 200 (job was cancelled) every time. I don't understand how this could be since I'm not doing anything in the code to cancel the request and I don't see how the async task I put the call in could be cancelled.
Was this just a bad example app I copied and a bad usage of the BigQuery Client? If so, what's the best way to send data to BigQuery from Android?

How to retrieve details of single video from youtube using videoID through Data API v3.0 in Android?

My server sends the list of videoID to Android. Now, I want to show Title, Thumbnail and Number of Comments on these videos in List View. I have done this in web using GET request to https://www.googleapis.com/youtube/v3/videos?part=snippet&id={VIDEO_ID}&key={YOUR_API_KEY} but how to do this in Android? Is there any YouTube SDK to initialize YouTube object? How do I retrieve this information from YouTube using VideoID?
EDIT: I have found a way to this using YouTube Data API Client Library for Java but It is giving runtime error without any explanation.
Here is the code I used
/**
* Define a global instance of a Youtube object, which will be used
* to make YouTube Data API requests.
*/
private static YouTube youtube;
youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer(){
public void initialize(com.google.api.client.http.HttpRequest request) throws IOException {
}
}).setApplicationName("youtube-cmdline-search-sample").build();
// Call the YouTube Data API's videos.list method to retrieve videos.
VideoListResponse videoListResponse = youtube.videos().
list("snippet").setId(videoId).execute();
// Since the API request specified a unique video ID, the API
// response should return exactly one video. If the response does
// not contain a video, then the specified video ID was not found.
List<Video> videoList = videoListResponse.getItems();
if (videoList.isEmpty()) {
System.out.println("Can't find a video with ID: " + videoId);
return;
}
Video video = videoList.get(0)
// Print information from the API response.
}
YouTube provides (at least) two official libraries relevant to your question:
YouTube Android Player API
YouTube Data API Client Library for Java
As the name already suggests, the first library is specifically developed for the Android platform. Its focus is on enabling you to incorporate video playback functionality into an app by providing a player framework. If your goal is to enable users to simply play YouTube videos, then is probably easiest to implement. Do note that this library requires the official YouTube app to be installed on the device.
The second library is more generic (although there are separate instructions for using it on Android) and provides a wrapper around YouTube's Data API to make interfacing with it a little easier. Hence, it allows you to do basically everything you can also do with the web API. As such, it solves a different problem than the Android Player API and is more likely the way to go if you want full control over how you display video data in your own UI.
Your third option would be to do exactly what you did for your web-based solution: make the API call yourself, parse the response and bind up the relevant data to your UI components. Various networking libraries (i.e. Retrofit) can greatly simplify this process.
Refer my post here. I just tried this method for my project and it works very nicely. You don't need the above code or any google api jar imports. Just replace the HTTP request with your HTTP request.
Output is returned in JSON, for which you can use a JSON parser jar to retrieve the title,thumbnails and other details you may require, as I have described in my answer there.
Try this:
protected void requestYoutubeVideos(String text) {
try {
youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("My app name").build();
// Define the API request for retrieving search results.
YouTube.Search.List query = youtube.search().list("id");
// Set your developer key from the Google Cloud Console for
// non-authenticated requests. See:
// https://cloud.google.com/console
query.setKey(YOUTUBE_API_KEY);
query.setQ(text);
query.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
// To increase efficiency, only retrieve the fields that the
// application uses.
query.setFields("items(id)");
query.setOrder("viewCount");
// Restrict the search results to only include videos. See:
// https://developers.google.com/youtube/v3/docs/search/list#type
query.setType("video");
SearchListResponse searchResponse = query.execute();
List<SearchResult> list = searchResponse.getItems();
Log.e("Youtube search", "list ===> " + list);
//Get Info for each video id
for (SearchResult video: list) {
youtubeList.add(video);
YouTube.Videos.List query2 = youtube.videos().list("id,contentDetails,snippet,statistics").setId(video.getId().getVideoId());
query2.setKey(YOUTUBE_API_KEY);
query2.setMaxResults((long) 1);
query2.setFields("items(id,contentDetails,snippet,statistics)");
VideoListResponse searchResponse2 = query2.execute();
List<Video> listEachVideo = searchResponse2.getItems();
Video eachVideo = listEachVideo.get(0);
}
} catch (GoogleJsonResponseException e) {
Log.e("Youtube search", "There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
} catch (IOException e) {
Log.e("Youtube search", "There was an IO error: " + e.getCause() + " : " + e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
}
and do not forget to call it from another thread:
new Thread(new Runnable() {
#Override
public void run() {
try {
requestYoutubeVideos("Harry el Sucio Potter");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();

Getting Google+ Friends Android (HTTP Request)

I am developing an app where users can log in with Google+. I added the Google+ sign in button and the user can log in without any issues.
Where I am having trouble is in retrieving the friends/ people in circles. This feature is not in the Android API, so I am trying to achieve this with an HTTP request (as documented here)
I set up my application in the developer console with a Public API access Android Key.
When I use an HttpGet with this URL:
https://www.googleapis.com/plus/v1/people/{the user's g+ id}/people/visible?key={my API key from the console}
I get a "keyInvalid" error with a "Bad Request" message.
If I try it without "?key={my key}" I get a "dailyLimitExceedingUnreg" error with message "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
Do you know why my reqest isn't working? What can I do to get it to work?
Okay, it turns out I didn't need to use HTTP get. Thanks for your responses.
This code did the trick:
Plus.PeopleApi.loadVisible(mGoogleApiClient,null).setResultCallback(new ResultCallback<People.LoadPeopleResult>() {
#Override
public void onResult(People.LoadPeopleResult loadPeopleResult) {
if (loadPeopleResult.getStatus().getStatusCode() == CommonStatusCodes.SUCCESS) {
PersonBuffer personBuffer = loadPeopleResult.getPersonBuffer();
try {
int count = personBuffer.getCount();
for (int i = 0; i < count; i++) {
Log.d(TAG, "Person " + i + " name: " + personBuffer.get(i).getDisplayName()+ " - id: " + personBuffer.get(i).getId());
}
} finally {
personBuffer.close();
}
} else {
Log.e(TAG, "Error");
}
}
});
You need to log in to http://console.developers.google.com and get an API key, the instead of ?key= you should put ?key=RANDOMCHARACTERS replacing RANDOMCHARACTERS for the key you got from Google.
If you haven't created a project, first you'll need to create one in that website, after that you should see the list of available API, search for the Google+ API and enable it to get the corresponding key.
People.list is an API method that requires user authentication not application authentication. Basically the only way you can make the request is like this:
GET https://www.googleapis.com/plus/v1/people/me/people/visible?access_token={user access_token}

How to properly integrate Pinterest in Android app?

I am using the REST API for integrating Pinterest into my Android app, but I'm getting an error when attempting to access categories.
My code:
String url = "https://api.pinterest.com/";
String allCategories = "/v2/boards/categories/";
RestClient client = new RestClient(url + allCategories);
String response = "";
try {
client.AddParam("limit", "36");
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
response = client.getResponse();
} catch (Exception e) {
System.out.println(">>> Exception >>> " + e + " >>> Message >>> "
+ e.getMessage());
}
System.out.println(">>> response >>> " + response);
Log.d(">> Login response >>> ", response);
I'm getting the following error returned from the endpoint:
{
"message": "Please upgrade your app!",
"error": "Authentication failed: Please upgrade your app!"
}
Pinterest doesn't have any official api, and it's unofficial api is not working now. So I don't think your code will work any way, unless someone finds any other unofficial api or Pinterest releases the official version.
PS: More Info.
As of today, pinterest API has been taken down
(look here)
In the meantime you might want to use this 3rd party implemented scraper, which works just like an API
http://pinterestapi.co.uk/
You can use this to get the boards, likes and pins of a user.
Note: Curiously the count for the v1 api still works. But again this is undocumented behaviour and dont rely on this

Categories

Resources