Android - YouTube API get videoId from video list - android

I want to get videoId in (items:[ id:{ ) but it shows org.json.JSONException: No value for videoId.
Is there any wrong code here?
items: [
{
kind: "youtube#searchResult",
etag: ""etag"",
id: {
kind: "youtube#video",
videoId: "nsVttBhYM2E"
},
snippet: {
publishedAt: "publishedAt",
channelId: "channelId",
title: "title",
description: description",
thumbnails: {
default: {
url: "thumbnail url",
width: 120,
height: 90
},
medium: {
url: "thumbnail url",
width: 320,
height: 180
},
high: {
url: "thumbnail url",
width: 480,
height: 360
}
},
channelTitle: "channelTitle",
liveBroadcastContent: "none"
}
},
This is part of source code get video id from video list
JSONArray items = jsonObject.getJSONArray("items");
for (int i = 0; i < items.length(); i++)
{
JSONObject json_data = items.getJSONObject(i);
strVideoID = json_data.getJSONObject("id").getString("videoId");
}

It's too late to answer, but it may help someone in future.
First check if "kind" equals to "youtube#video", then try to get the "id" string. Both the key are in the "id" JSONObject.
As the response may also contain some playlists, instead of "videoId" there may be "playlistId".

Related

How to convert JSONObject to a JSONArray?

Recently,I got the problem when I tried to implement a comment function in an Android APP.
The definition of comments in user.js is as follow
comnents: [{
ownerID: {
type: String,
required: true,
},
commenterID: {
type: String,
required: true,
},
commenterName: String,
content: {
type: String,
require: true,
}
}],
And I have a request like that:
{
"_id":"60d204d6efc6c70022b08dc4",
"comments":[
{
"ownerID":"60d204d6efc6c70022b08dc4",
"commenterID":"60d205afefc6c70022b08dc8",
"commenterName":"Bob",
"content":"Hello World!"
},
{
"ownerID":"60d204d6efc6c70022b08dc4",
"commenterID":"60d20892efc6c70022b08dd2",
"commenterName":"Alice",
"content":"Hello Earth!"
}
]
}
Here is my API
router.post("/writecomment",jsonParser,
async(req,res,next)=>{
const errors=validationResult(req);
if(!errors.isEmpty()){
return res.status(400).json({erros:errors.array()});
}
        User.findOneAndUpdate(
            { "_id": req.body._id},
            {
                $set: {
                    comments:req.body.comments
                }
            },
            {overwrite:true},
function(err,resp){
if(err) throw err;
if(resp) {
return res.send({
msg:' change successfully'
});
}else{
return res.status(403).json({ success: false, message: 'Failed to change'});
}
}
      )
}
)
How do I convert "comments" from request to comments array? Or have a better way to implement this function?
PS: I use Mongoose + Express Framework to develope.
const commentArray = [...req.body.comments]
Will make this for you:
[
{
"ownerID": "60d204d6efc6c70022b08dc4",
"commenterID": "60d205afefc6c70022b08dc8",
"commenterName": "Bob",
"content": "Hello World!"
},
{
"ownerID": "60d204d6efc6c70022b08dc4",
"commenterID": "60d20892efc6c70022b08dd2",
"commenterName": "Alice",
"content": "Hello Earth!"
}
]
Basically what is happening here is, we are iterating over the response you are getting and saving the result in an array. If you want to learn more about the ... operator, check out this link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

How do i play a track with a custom id in react-native?(react-native-track)

I can run music from my data file, but it automatically switches to the next. How can I prevent this?
TrackPlayer.setupPlayer().then(async() => {
console.log("player Ready");
await TrackPlayer.add(songs);
TrackPlayer.play();
});
2 examples from my data file:
const songs = [
{
title: "death bed",
artist: "Powfu",
image: require("./img/a.png"),
id: "1",
url:require("../assets/track/animals/lion.mp3"),
},
{
title: "bad liar",
artist: "Imagine Dragons",
image: require("./img/b.png"),
id: "2",
url:require("../assets/track/animals/bird.mp3"),
},

How would I go about de-serializing a list of objects using Kotlin's serialization library?

I've been running into the following exception at runtime with the debugger trying to de-serialize data from my Algolia index for my Kotlin Android recipe app I am trying to create by using the Kotlinx.Serialization library. The app compiles and runs fine, but no results show on the UI.
kotlinx.serialization.json.JsonDecodingException: Unexpected JSON token at offset -1: Failed to parse 'int'.
JSON input: {"amount":1.5,"name":"green beans","original":"1.5 pounds of green beans","unit":"pounds","unitLong":"pounds","unitShort":"lbs"}
Now from the looks this exception, It looks like the de-serializer is getting confused try to de-serialize my Ingredients data class. How would I go about de-serializing it?.
Example JSON data that is being sent over.
{
"cuisine": "European",
"diet": "Vegetarian",
"difficulty": 2,
"dishType": "Dinner",
"duration": 30,
"durationUnit": "minutes",
"image": "https://c.recipeland.com/images/r/1396/12f9fc271d8f1bfac5f6_550.jpg",
"ingredients": [
{
"amount": 1.5,
"name": "green beans",
"original": "1.5 pounds of green beans",
"unit": "pounds",
"unitLong": "pounds",
"unitShort": "lbs"
},
{
"amount": 1,
"name": "onion",
"original": "1.5 medium onion",
"unit": "medium",
"unitLong": "medium",
"unitShort": "med"
},
{
"amount": 2,
"name": "garlic",
"original": "2 teaspoons of garlic",
"unit": "teaspoons",
"unitLong": "teaspoons",
"unitShort": "tsps"
},
{
"amount": 1,
"name": "olive oil",
"original": "1 teaspoon olive oil",
"unit": "teaspoon",
"unitLong": "teaspoon",
"unitShort": "tsps"
},
{
"amount": 1,
"name": "mushrooms",
"original": "1 cup mushrooms",
"unit": "cup",
"unitLong": "cup",
"unitShort": "cup"
},
{
"amount": 1,
"name": "cherry tomatoes",
"original": "1 cup cherry tomatoes",
"unit": "cup",
"unitLong": "cup",
"unitShort": "cup"
}
],
"name": "Green Beans with Mushrooms and Cherry Tomatoes",
"preparation": [
"Steam green beans until tender.",
"Drain and set aside. Sauté onion and garlic in a medium skillet coated with olive oil, until tender. About 2 to 3 minutes.",
"Add mushrooms and sauté until tender. Stir in green beans and tomotoes until heated."
],
"yield": 4,
"objectID": "0"
}
I have my data classes for a recipe set up as the following:
Recipe.kt
#IgnoreExtraProperties
#Serializable
data class Recipe(
var difficulty: Int = 0,
var dishType: String? = null,
var duration: Int = 0,
var durationUnit: String? = null,
var image: String? = null,
var diet: String? = null,
var cuisine: String? = null,
var name: String? = null,
var ingredients: List<Ingredient> = emptyList(),
var preparation: List<String> = emptyList(),
var yield: Int = 0
) {
Ingredient.kt
#Serializable
data class Ingredient(
var amount: Int = 0,
var name: String? = null,
var original: String? = null, // Original text of the ingredient
var unit: String? = null,
var unitLong: String? = null,
var unitShort: String? = null
)
This block of code I got from Algolia's getting started guide for InstantSearch Android that de-serializes the data from the index.
private val datasourceFactory = SearcherSingleIndexDataSource.Factory(searcher) { hit ->
hit.deserialize(Recipe.serializer()) // Problem line I assume
}
val pagedListConfig = PagedList.Config.Builder().setPageSize(50).build()
val recipes: LiveData<PagedList<Recipe>> =
LivePagedListBuilder(datasourceFactory, pagedListConfig).build()
val searchBox =
SearchBoxConnectorPagedList(searcher, listOf(recipes))
I've tried to manually create the object by using the following code, but I run into issues when trying to create the list of ingredients.
val dataSourceFactory = SearcherSingleIndexDataSource.Factory(searcher) { hit ->
Recipe(
hit.json.getPrimitive("difficulty").content.toInt(),
hit.json.getPrimitive("dishType").content,
hit.json.getPrimitive("duration").content.toInt(),
hit.json.getPrimitive("durationUnit").content,
hit.json.getPrimitive("image").content,
hit.json.getPrimitive("diet").content,
hit.json.getPrimitive("cuisine").content,
hit.json.getPrimitive("name").content,
listOf(
Ingredient(
hit.json.getPrimitive("amount").content.toInt(),
hit.json.getPrimitive("name").content,
hit.json.getPrimitive("original").content,
hit.json.getPrimitive("unit").content,
hit.json.getPrimitive("unitLong").content,
hit.json.getPrimitive("unitShort").content
)
),
hit.json.getArray("preparation").content.map { prep -> prep.content },
hit.json.getPrimitive("yield").content.toInt()
)
}
I'm not 100% sure if I'm properly creating the preparation property member correctly as well as the whole creating the list of ingredients has side-tracked me. Any help would be greatly be appreciated and I apologize for my first post on here being a long one. I've been going at this for a couple of days already and I'm stumped as to what to do next.
As you can see this line:
kotlinx.serialization.json.JsonDecodingException: Unexpected JSON token at offset -1: Failed to parse 'int'.
Here JsonDecodingException exception occur that's why it is not giving proper response. You must check your all data classes are same variable which is in JSON Object.
Here I found 1 issue in your data class, First check this JSON Reposne:
"amount": 1.5
and now check your data class, which has var amount: Int = 0
#Serializable
data class Ingredient(
var amount: Int = 0,
var name: String? = null,
var original: String? = null, // Original text of the ingredient
var unit: String? = null,
var unitLong: String? = null,
var unitShort: String? = null
)
Here JSON Object is in Float and you are storing in it Int, which may cause exception. Make sure all values in data class are proper.
Or for work around you just make String all variable in data class to check all response show proper, than after just convert them to Int, Float according to your requirements.

Android JSON Nested Arrays

I've tried to imitate the chosen answers in this sort of problem but I'm unsure why I'm failing to retrieving the URLs of the "attachments" in this.
What I'm after is a way to get every "post" and then grab every "attachment" image URL to save as a string. I've tried doing this on my emulator but it just stalls and runs forever. For certain reasons I am unable to use my real phone as a debugger too or else I would post a logcat.
One thing I am certain is that everything, minus the attachments, is coming in correctly. I've managed to get the posts downloading but cannot get anything thats nested. I'm newer to JSON so any help is very appreciated.
My Async:
// you can make this class as another java file so it will be separated from your main activity.
// https://www.codeofaninja.com/2013/11/android-json-parsing-tutorial.html
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
private ArrayList<RssFeedItem> tempArray = new ArrayList<RssFeedItem>();
final String TAG = "AsyncTaskParseJson";
private ProgressDialog progress;
// set your json string url here
String yourJsonStringUrl = "http://www.prindlepost.org/?json=tag_slug=java";
// contacts JSONArray
JSONArray dataJsonArr = null;
JSONArray imageURLArr = null;
#Override
protected void onPreExecute() {
progress = new ProgressDialog(getActivity());
progress.setTitle("Downloading Prindle's Posts");
progress.setMessage("This should just take a moment.");
progress.show();
}
#Override
protected String doInBackground(String... arg0)
{
try
{
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("posts");
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++)
{
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("id");
String type = c.getString("type");
String slug = c.getString("slug");
String title = c.getString("title");
String content = c.getString("content");
String author = c.getString("author");
//http://stackoverflow.com/questions/19748829/android-get-json-array-nested-in-array
JSONObject attachments = c.getJSONObject("attachments");
Log.d("attachment",""+attachments.getString("url"));
// show the values in our logcat
Log.e(TAG, "id: " + id
+ ", type: " + type
+ ", slug: " + slug
+ ", title: " + title
+ ", author: " + author
+ ", content: " + content + "\n\n");
tempArray.add(new RssFeedItem(title, content, "", 0, new Date(), author));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
The JSON: http://www.prindlepost.org/?json=tag_slug=java
{
status: "ok",
count: 10,
count_total: 334,
pages: 34,
posts: [
{
id: 4230,
type: "post",
slug: "crowdsourcing-justice",
url: "http://www.prindlepost.org/2015/06/crowdsourcing-justice/",
status: "publish",
title: "Crowdsourcing Justice",
title_plain: "Crowdsourcing Justice",
content: "<p>The video begins abruptly. Likely recorded on a phone, the footage is shaky and blurry, yet the subject is sickeningly unmistakeable: a crying infant being repeatedly and violently dunked into a bucket of water. First it is held by the arms, then upside down by one leg, then grasped by the face as an unidentified woman pulls it through the water. Near the end of the video, the infant falls silent, the only remaining audio the splashing of water and murmured conversation as the child is dunked again and again.</p> <div class="more-link-wrap wpb_button"> Read more</div> ",
excerpt: "<p>Facebook’s decision not to censor a video of child abuse poses questions of censorship, activism and online justice. </p> ",
date: "2015-06-09 14:00:19",
modified: "2015-06-10 09:53:36",
categories: [
{
id: 433,
slug: "crime-and-law",
title: "Crime and Law",
description: "",
parent: 63,
post_count: 14
},
{
id: 38,
slug: "ethics-news",
title: "Ethics News",
description: "",
parent: 0,
post_count: 153
},
{
id: 63,
slug: "society-ethics-news",
title: "Society",
description: "",
parent: 38,
post_count: 187
}
],
tags: [
{
id: 180,
slug: "abuse",
title: "abuse",
description: "",
post_count: 2
},
{
id: 481,
slug: "child-abuse",
title: "child abuse",
description: "",
post_count: 1
},
{
id: 482,
slug: "doxxing",
title: "doxxing",
description: "",
post_count: 1
},
{
id: 57,
slug: "facebook",
title: "Facebook",
description: "",
post_count: 4
},
{
id: 470,
slug: "internet",
title: "internet",
description: "",
post_count: 2
},
{
id: 130,
slug: "justice",
title: "justice",
description: "",
post_count: 2
},
{
id: 59,
slug: "social-media",
title: "social media",
description: "",
post_count: 4
}
],
author: {
id: 43,
slug: "connergordon_2016",
name: "Conner Gordon",
first_name: "Conner",
last_name: "Gordon",
nickname: "connergordon_2016",
url: "http://connergordon.tumblr.com",
description: "Conner is a web and social media intern at the Prindle Institute. A Political Science and English double major from Carmel, Indiana, Conner's ethical interests lie in memory studies, conflict analysis and the ethics of representation. He also has interests in literature, art and photography."
},
comments: [ ],
attachments: [
{
id: 4233,
url: "http://www.prindlepost.org/wp-content/uploads/2015/06/Screen-Shot-2015-06-09-at-11.48.59-AM.png",
slug: "screen-shot-2015-06-09-at-11-48-59-am",
title: "",
description: "",
caption: "Image credit: Screenshot from Youtube",
parent: 4230,
mime_type: "image/png",
images: [ ]
},
{
id: 4235,
url: "http://www.prindlepost.org/wp-content/uploads/2015/06/Screen-Shot-2015-06-09-at-11.48.59-AM1.png",
slug: "screen-shot-2015-06-09-at-11-48-59-am-2",
title: "",
description: "",
caption: "Image/Youtube",
parent: 4230,
mime_type: "image/png",
images: [ ]
}
],
I had the same problem. After a few days melting my brain, I tried using Google's GSON. It does all the parsing and thinking for you, and returns a nice little object with all the information from the JSON.
Here's the project link: https://github.com/google/gson
To use it, you have to instantiate a new Gson parser, like so
Gson gson = new Gson();
YourObject object = gson.fromJson(jsonString, YourObject.class);
And the YourObject class should look something like this:
public class YourObject{
int status;
int count;
String count_total;
...
Post[] posts;
}
Now you create a Post class with the fields predicted in your JSON:
public class Post{
int id;
String type;
String slug;
...
Category[] categories;
}
I think you can get an idea on how to set up your POJO's. Keep in mind that, if you are getting an array of objects as your base object in JSON, be sure to use YourObject[] instead of YourObject when calling gson.fromJson
Just a heads-up: If any of the Json elements have a null or an empty value, even though they are primarily an int in your YourObject class, it is best to declare them as String to avoid java.lang.NumberFormatException.
You can use the method getJSONArray()

textField in listView

This is my first question in this community that refers to the API of titanium studio. I explain: I'm trying to put a textField inside a listView an item, but when compiled and when to focus on the text area will not let me write and when it does it does in other type of listView.
I hope you can help with this
var win = Ti.UI.createWindow({
backgroundColor:'#FFF'
});
var plainTemplate = {
childTemplates: [
{
type: 'Ti.UI.Label',
bindId: 'title',
properties: {
width: '100%',
height: 30,
left: 0,
top:0
}
},
{
type: 'Ti.UI.TextArea',
bindId: 'campo',
properties: {
top:60,
width: '70%',
left:10,
height:40
}
}
],
events: {click: check }
};
var listView = Ti.UI.createListView({
templates: { 'uncheck': plainTemplate},
defaultItemTemplate: 'uncheck'
});
var data = [];
for (var i = 0; i < 20; i++) {
data.push({
title : { text: 'row' + i },
properties : {
itemId: 'row' + i,
accessoryType: Ti.UI.LIST_ACCESSORY_TYPE_NONE,
}
});
}
var section = Ti.UI.createListSection();
section.setItems(data);
listView.sections = [section];
function check() {
alert('estas aqui!!');
}
win.add(listView);
win.open();
Have you tried out to remove the top-Property in UITextArea of 60px? That could be the reason, why your textarea is at another position as you've expected:
{
type: 'Ti.UI.TextArea',
bindId: 'campo',
properties: {
// top: 60 <--- remove that line
width: '70%',
left:10,
height:40
}
}
I haven't tested your whole code, but i added this value for a top property to a ListView in an App where i am working on and it ended in an similar behaviour as you wrote.

Categories

Resources