android youtube data api - android

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" />

Related

Sony QX100 return 403 error for supported methods

I am trying to set the Exposure mode and Focus mode for my QX100 device. Each time I make the API call I get a 403 error. However, these two methods setExposureMode and setFocusMode are supported by the QX100 as it clearly states in the API docs. In addition, I can set the focus mode through Playmemories. This same problem also occurs with setBeepMode, which is also supported. Any ideas about why this could be occurring?
There are some supported methods that are working, such as actTakePicture and setPostviewImageSize
An example call:
public JSONObject setFocusMode() throws IOException {
String service = "camera";
try {
JSONObject requestJson =
new JSONObject().put("method", "setFocusMode").put("params", new JSONArray().put("MF")) //
.put("id", id()).put("version", "1.0");
String url = findActionListUrl(service) + "/" + service;
log("Request: " + requestJson.toString());
JSONObject responseJson = SimpleHttpClient.httpPost(url, requestJson, null);
log("Response: " + responseJson.toString());
return responseJson;
} catch (JSONException e) {
throw new IOException(e);
}
}
Is your QX100 updated to the latest firmware? On old one, most of APIs are restricted.
Or they may be temporary disabled. You can use getAvailableApiList to know that.

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();

Sony remote camera API QX 10, Error 1

I got "Error 1" without any comment as a response for most of my requests to Sony qx10 (last firmware 3.00).
For example:
03-10 13:22:50.830: D/SimpleRemoteApi(4418): Request: {"method":"getAvailableExposureCompensation","params":[],"id":11,"version":"1.0"}
03-10 13:22:51.012: D/SimpleRemoteApi(4418): Response: {"error":[1,""],"id":11}
Same result have
getAvailableWhiteBalance
getAvailableIsoSpeedRate
getAvailableExposureCompensation
But getAvailableStillSize returns proper response with list of image sizes.
Also getAvailableFocusMode returns error "40401, Camera Not Ready". What does it mean? Liveview is started, and camera is sending images to phone.
All my request are sent in this way (just a bit modified code from example SDK):
public JSONObject getSomeParameter() throws IOException {
String service = "camera";
try {
JSONObject requestJson =
new JSONObject().put("method", "getSomeParameter") //
.put("params", new JSONArray()).put("id", id()) //
.put("version", "1.0");
String url = findActionListUrl(service) + "/" + service;
log("Request: " + requestJson.toString());
String responseJson = SimpleHttpClient.httpPost(url, requestJson.toString());
log("Response: " + responseJson);
return new JSONObject(responseJson);
} catch (JSONException e) {
throw new IOException(e);
}
}
My questions are:
How to solve error 1?
How to solve error 40401?
Is there more detailed documentation for errors and other stuff, then PDF supplied with SDK usage example?
To get availability to control settings of camera (such as Exposure compensation, WB mode, ISO mode) you should call "setExposureMode" with parameter "Program Auto".

How to get reddit URL JSON data in android?

I'm attempting to get a list of URL's from a subreddit in order to load them into universal image loader for viewing pleasure. However, I cannot figure out where my query is going wrong. Plus, I'm not familiar with android studio's logcat as compared to eclipses logcat, so I'm not exactly sure where to look for my debugging responses.
Here's the query method:
public void queryReddit()
{
// Prepare your search string to be put in a URL
// It might have reserved characters or something
// String urlString = "";
// try {
// urlString = URLEncoder.encode(searchString, "UTF-8");
// } catch (UnsupportedEncodingException e) {
//
// // if this fails for some reason, let the user know why
// e.printStackTrace();
// Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
// }
// Create a client to perform networking
AsyncHttpClient client = new AsyncHttpClient();
// 11. start progress bar
setProgressBarIndeterminateVisibility(true);
// Have the client get a JSONArray of data
// and define how to respond
client.get("http://www.reddit.com/r/pics/.json",
new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONObject jsonObject) {
// 11. stop progress bar
setProgressBarIndeterminateVisibility(false);
// Display a "Toast" message
// to announce your success
Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_LONG).show();
// // 8. For now, just log results
// Log.d("omg android", jsonObject.toString());
try
{
Log.d("go reddit yay", jsonObject.toString());
JSONObject testingData = (JSONObject) jsonObject.get("data");
JSONArray testingChildren = (JSONArray) testingData.get("children");
JSONObject testingLogData = (JSONObject) testingChildren.get(0);
JSONArray children = (JSONArray) jsonObject.get("children");
JSONObject logData = (JSONObject) children.get(0);
Log.d("go reddit yay", logData.getString("url"));
Log.d("go reddit yay", testingLogData.getString("url"));
for(int i = 0; i < 10; i++)
{
JSONObject data = (JSONObject) children.get(i);
if(data.getString("url") != null)
{
System.out.println(data.getString("url"));
}
//if the url field exists and it's a picture that univ image loader understands then add it
if(data.getString("url") != null && data.getString("url").substring(data.getString("url").length()-3).equals("png") ||
data.getString("url").substring(data.getString("url").length()-3).equals("jpg"))
{
imageUrls.add(data.getString("url"));
System.out.println(data.getString("url"));
}
//TODO I found this error: this requires android.permission.INTERACT_ACROSS_USERS_FULL
}
mPagerAdapter.notifyDataSetChanged();
} catch (JSONException e)
{
e.printStackTrace();
}
//TODO Might want to put all this data in a try catch block and do it right here.
// update the data in your custom method.
//updateData()
}
#Override
public void onFailure(int statusCode, Throwable throwable, JSONObject error)
{
// 11. stop progress bar
setProgressBarIndeterminateVisibility(false);
// Display a "Toast" message
// to announce the failure
Toast.makeText(getApplicationContext(), "Error: " + statusCode + " " + throwable.getMessage(), Toast.LENGTH_LONG).show();
// Log error message
// to help solve any problems
Log.e("omg android", statusCode + " " + throwable.getMessage());
}
});
}
Within the try catch block, the only logged information that ends up being sent to logcat is the first line, Log.d("go reddit yay", jsonObject.toString());
I can't find the responses from the other log calls which is very strange to me.
Here's the response from the first log call:
06-17 06:35:29.324 17133-17133/.wallpaper D/absfr﹕ {"data":{"after":"t3_2823ou","children":[{"data":{"media_embed":{},"author_flair_css_class":null,"score":503,"created_utc":1402931529,"clicked":false,"visited":false,"id":"28a94k","author":"JamesBDW","title":"Any Bronson fans? [1920x1080]","over_18":false,"created":1402960329,"name":"t3_28a94k","selftext_html":null,"domain":"i.imgur.com","author_flair_text":null,"secure_media":null,"num_reports":null,"edited":false,"stickied":false,"link_flair_text":null,"link_flair_css_class":null,"saved":false,"secure_media_embed":{},"subreddit_id":"t5_2qmjl","distinguished":null,"gilded":0,"url":"https:\/\/i.imgur.com\/Hq1fcSm.jpg","banned_by":null,"subreddit":"wallpaper","is_self":false,"num_comments":31,"approved_by":null,"thumbnail":"http:\/\/a.thumbs.redditmedia.com\/Dh2iU7Q0rpFogkWt.jpg","permalink":"\/r\/wallpaper\/comments\/28a94k\/any_bronson_fans_1920x1080\/","hidden":false,"likes":null,"downs":188,"ups":691,"selftext":"","media":null},"kind":"t3"},{"data":{"media_embed":{},"author_flair_css_class":null,"score":8,"created_utc":1402989714,"clicked":false,"visited":false,"id":"28cnyn","author":"ZadocPaet","title":"Active Dunes on Mars (OS) [1024x768]","over_18":false,"created":1403018514,"name":"t3_28cnyn","selftext_html":null,"domain":"nasa.gov","author_flair_text":null,"secure_media":null,"num_reports":null,"edited":false,"stickied":false,"link_flair_text":null,"link_flair_css_class":null,"saved":false,"secure_media_embed":{},"subreddit_id":"t5_2qmjl","distinguished":null,"gilded":0,"url":"http:\/\/www.nasa.gov\/sites\/default\/files\/styles\/1024x768_autoletterbox\/public\/pia18244.jpg","banned_by":null,"subreddit":"wallpaper","is_self":false,"num_comments":1,"approved_by":null,"thumbnail":"http:\/\/a.thumbs.redditmedia.com\/dFTBquSWiMSjK0aZ.jpg","permalink":"\/r\/wallpaper\/comments\/28cnyn\/active_dunes_on_mars_os_1024x768\/","hidden":false,"likes":null,"downs":3,"ups":11,"selftext":"","media":null},"kind":"t3"},{"data":{"media_embed":{"content":"<iframe class=\"embedly-embed\" src=\"\/\/cdn.embedly.com\/widgets\/media.html?src=http%3A%2F%2Fimgur.com%2Fa%2F0jeZf%2Fembed&url=http%3A%2F%2Fimgur.com%2Fa%2F0jeZf&image=http%3A%2F%2Fi.imgur.com%2F2PdUiuE.jpg&key=2aa3c4d5f3de4f5b9120b660ad850dc9&type=text%2Fhtml&schema=imgur\" width=\"550\" height=\"550\" scrolling=\"no\" frameborder=\"0\" allowfullscreen><\/iframe>","scrolling":false,"height":550,"width":550},"author_flair_css_class":null,"score":1,"created_utc":1403004127,"clicked":false,"visited":false,"id":"28czid","author":"smessies","title":"I found a wallpaper album full of iconic design chairs. I tought there were some important ones missing so i started adding some myself. work in progress! [1920x1200]","over_18":false,"created":1403032927,"name":"t3_28czid","selftext_html":null,"domain":"imgur.com","author_flair_text":null,"secure_media":null,"num_reports":null,"edited":false,"stickied":false,"link_flair_text":null,"link_flair_css_class":null,"saved":false,"secure_media_embed":{},"subreddit_id":"t5_2qmjl","distinguished":null,"gilded":0,"url":"http:\/\/imgur.com\/a\/0jeZf","banned_by":null,"subreddit":"wallpaper","is_self":false,"num_comments":0,"approved_by":null,"thumbnail":"http:\/\/b.thumbs.redditmedia.com\/GYaN5fyJfY8fI8xE.jpg","permalink":"\/r\/wallpaper\/comments\/28czid\/i_found_a_wallpaper_album_full_of_iconic_design\/","hidden":false,"likes":null,"downs":0,"ups":1,"selftext":"","media":{"type":"imgur.com","oembed":{"thumbnail_height":1200,"author_url":"http:\/\/imgur.com\/user\/smessies","width":550,"type":"rich","version":"1.0","thumbnail_url":"http:\/\/i.imgur.com\/2PdUiuE.jpg","thumbnail_width":1920,"title":"imgur: the simple image sharer","height":550,"description":"Imgur is home to the web's most popular image content, curated in real time by a dedicated community through commenting, voting and sharing.","author_name":"smessies","html":"<iframe class=\"embedly-embed\" src=\"\/\/cdn.embedly.com\/widgets\/media.html?src=http%3A%2F%2Fimgur.com%2Fa%2F0jeZf%2Fembed&url=http%3A%2F%2Fimgur.com%2F
no idea what to do.
One last debugging info is that the toast for the onSuccess method does appear, so it is clearly successful in it's query, I'm just doing something wrong in interpreting the data.
From your description it seems like a statement after the first Log.d("go reddit yay", ...); call throws an exception which you can't see.
Try replacing your exception handling code:
} catch (JSONException e)
{
e.printStackTrace();
}
with this:
} catch (Throwable t)
{
Log.e("omg android", "Exception in onSuccess()", t);
}
and check if any exceptions are logged.

How to search videos with youtube data API in 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

Categories

Resources