I have the following string and inside the string you can see that there is number of arrays. "10, 20, 30, 40, 30, 20, 10, 5, 20, 30, 20, 30"
What I would like to do is basically need to divide this string in each individual strings and would like to convert them in to the integer array.
For example: String array = ["10", "20", "30", "40", "30", "20", "10", "5", "20", "30", "20", "30"] - > Integer array = [10, 20, 30, 40, 30, 20, 10, 5, 20, 30, 20, 30].
If you want convert String array to Int array:
val stringArray = arrayOf("10", "20", "30", "40", "30", "20", "10", "5", "20", "30", "20", "30")
And convert it to int array using map
val intArray = stringArray.map { it.toInt() }
If you want to print it:
print(stringArray)
print(intArray)
Or, if you want convert a "String" to int array, you need split it and map.
val inputString = "10, 20, 30, 40, 30, 20, 10, 5, 20, 30, 20, 30"
val intArray = inputString.split(", ").map { it.toInt() }
Assuming you have a string has an array in it. This following code should give you what you want.
val array = "[20, 30, 40, 30, 20, 10, 5, 20, 30, 20, 30]"
val items = array.replace("\\[".toRegex(), "").replace("\\]".toRegex(), "").replace("\\s".toRegex(), "").split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val results = IntArray(items.size)
for (i in items.indices) {
results[i] = Integer.parseInt(items[i])
}
Related
I want to get only those item which contain type Lunch `` This is a function where I can fetch data from Rest Api and also ApiResponse added
I need to get specific data from a session I send instead of getting the entire array from the response from the Api() method. How do I capture just the only those item which contain type Lunch from the array?
{
"success": true,
"data": [
{
"id": 6,
"name": "Snack",
"type": "breakfast",
"detail": "18",
"image": "uploads/Screenshot_2022-12-04-13-15-13-27.jpg",
"carbs": 6,
"proteins": 4,
"fats": 8,
"cal": 4,
"day": 1,
"created_at": null,
"updated_at": null
},
{
"id": 7,
"name": "Chicken",
"type": "lunch",
"detail": "White Chicken",
"image": "uploads/1670258808164716637219.jpg",
"carbs": 15,
"proteins": 18,
"fats": 10,
"cal": 200,
"day": 1,
"created_at": null,
"updated_at": null
},
{
"id": 8,
"name": "546e57rufjvjv",
"type": "lunch",
"detail": "gdyhj",
"image": "uploads/meat.png",
"carbs": 6578,
"proteins": 2345,
"fats": 5678,
"cal": 4325,
"day": 5,
"created_at": null,
"updated_at": null
},
{
"id": 9,
"name": "Anda Tikki",
"type": "dinner",
"detail": "Egg and Daal",
"image": "uploads/1670259245043112842388.jpg",
"carbs": 10,
"proteins": 8,
"fats": 12,
"cal": 180,
"day": 1,
"created_at": null,
"updated_at": null
},
{
"id": 10,
"name": "Boiled egg and cucumber",
"type": "breakfast",
"detail": "Egg and cucumber",
"image": "uploads/1670259362662817976982.jpg",
"carbs": 10,
"proteins": 5,
"fats": 5,
"cal": 100,
"day": 2,
"created_at": null,
"updated_at": null
}
],
"message": "Food Data retrieved successfully."
}
Future<List<ProductsModel>> getProducts({String? query}) async {
List<ProductsModel> products = [];
var data=[];
try {
String url = 'https://diet.appetitor.app/Celo/api/user/food/2000.0';
var response = await Dio().get(url,
options: Options(headers: {
HttpHeaders.contentTypeHeader: "application/json",
}));
if (response.statusCode == 200) {
products.clear();
ProductsModel.fromJson(response.data);
products.add(ProductsModel.fromJson(response.data));
if (query != null) {
print(products.length);
products = products
.map((e) {
e.data!.where((element) => element.type!.toLowerCase().contains('lunch'));
})
.cast<ProductsModel>()
.toList();
}
}
} on DioError catch (e) {
print(e.response);
}
return products;
}
}
If the response status code returns 200 after making a request with the rest api, assign the data in it to a variable of the type of your model, then you can get it from the variable as you want.
How to execute and get the output of the FFMProbe command on FFMPegKit? I tried various ways. But I failed. Can anyone help me, please?
After a few days later I got success (though the Question and answer time is same. But I tried it earlier more).
FFprobeKit.executeAsync("-v error -show_streams -print_format json videopath") { session ->
Log.d("TAG", "fileDetails: FMProbe output: ${session?.output}")
}
This Log.d print the details of inputted video as a JSON (as the command).
FFMProbe output: {
"streams": [
{
"index": 0,
"codec_name": "h264",
"codec_long_name": "unknown",
"profile": "100",
"codec_type": "video",
"codec_time_base": "1/60",
"codec_tag_string": "avc1",
"codec_tag": "0x31637661",
"width": 1920,
"height": 1080,
"coded_width": 1920,
"coded_height": 1088,
"closed_captions": 0,
"has_b_frames": 1,
"sample_aspect_ratio": "1:1",
"display_aspect_ratio": "16:9",
"pix_fmt": "yuv420p",
"level": 40,
"color_range": "tv",
"color_space": "bt709",
"color_transfer": "bt709",
"color_primaries": "bt709",
"chroma_location": "left",
"refs": 1,
"is_avc": "true",
"nal_length_size": "4",
"r_frame_rate": "30/1",
"avg_frame_rate": "30/1",
"time_base": "1/15360",
"start_pts": 0,
"start_time": "0.000000",
"duration_ts": 3329024,
"duration": "216.733333",
"bit_rate": "1461827",
"bits_per_raw_sample": "8",
"nb_frames": "6502",
"disposition": {
"default": 1,
"dub": 0,
"original": 0,
"comment": 0,
"lyrics": 0,
"karaoke": 0,
"forced": 0,
"hearing_impaired": 0,
"visual_impaired": 0,
"clean_effects": 0,
"attached_pic": 0,
"timed_thumbnails": 0
},
"tags": {
"language": "und",
"handler_name": "ISO Media file produced by Google Inc.",
"vendor_id": "[0][0][0][0]"
}
},
{
"index": 1,
"codec_name": "aac",
"codec_long_name": "unknown",
"profile": "1",
"codec_type": "audio",
"codec_time_base": "1/44100",
"codec_tag_string": "mp4a",
"codec_tag": "0x6134706d",
"sample_fmt": "fltp",
"sample_rate": "44100",
"channels": 2,
"channel_layout": "stereo",
"bits_per_sample": 0,
"r_frame_rate": "0/0",
"avg_frame_rate": "0/0",
"time_base": "1/44100",
"start_pts": 0,
"start_time": "0.000000",
"duration_ts": 9561088,
"duration": "216.804717",
"bit_rate": "127999",
"max_bit_rate": "127999",
"nb_frames": "9337",
"disposition": {
"default": 1,
"dub": 0,
"original": 0,
"comment": 0,
"lyrics": 0,
"karaoke": 0,
"forced": 0,
"hearing_impaired": 0,
"visual_impaired": 0,
"clean_effects": 0,
"attached_pic": 0,
"timed_thumbnails": 0
},
"tags": {
"language": "und",
"handler_name": "ISO Media file produced by Google Inc.",
"vendor_id": "[0][0][0][0]"
}
}
]
}
I'm making a project (for a programming class in uni) but when I try to run it in Android Studio, a warning appears very briefly in the emulator:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 5 column 21 path $[0].dateOfBirth
This is my JSON file:
{
"fighters": [
{
"id": 1,
"name": "Karl",
"dateOfBirth": "20-03-1975",
"level": 4,
"image": "karl.png"
},
{
"id": 2,
"name": "Geralt",
"dateOfBirth": "16-08-1964",
"level": 8,
"image": "Geralt.png"
},
{
"id": 3,
"name": "Darrak",
"dateOfBirth": "25-11-1940",
"level": 5,
"image": "Darrak.png"
},
{
"id": 4,
"name": "Jafar",
"dateOfBirth": "09-02-1920",
"level": 9,
"image": "Jafar.png"
},
{
"id": 5,
"name": "Cornelius",
"dateOfBirth": "28-06-1988",
"level": 2,
"image": "Cornelius.png"
},
{
"id": 6,
"name": "Laila",
"dateOfBirth": "18-10-1998",
"level": 5,
"image": "Laila.png"
},
{
"id": 7,
"name": "Marianne",
"dateOfBirth": "01-03-1975",
"level": 7,
"image": "Marianne.png"
},
{
"id": 8,
"name": "Petro",
"dateOfBirth": "10-07-1974",
"level": 10,
"image": "Petro.png"
},
{
"id": 9,
"name": "Ordelia",
"dateOfBirth": "18-05-1985",
"level": 5,
"image": "Ordelia.png"
},
{
"id": 10,
"name": "Lucina",
"dateOfBirth": "21-09-1992",
"level": 9,
"image": "Lucina.png"
},
{
"id": 11,
"name": "Hugo",
"dateOfBirth": "16-07-1938",
"level": 6,
"image": "Hugo.png"
},
{
"id": 12,
"name": "Sildar",
"dateOfBirth": "19-12-1980",
"level": 3,
"image": "Sildar.png"
},
{
"id": 13,
"name": "Zenok",
"dateOfBirth": "30-10-1999",
"level": 1,
"image": "Zenok.png"
},
{
"id": 14,
"name": "Violet",
"dateOfBirth": "02-04-2001",
"level": 8,
"image": "Violet.png"
},
{
"id": 15,
"name": "Tamara",
"dateOfBirth": "13-06-1963",
"level": 4,
"image": "Tamara.png"
}
],
"encounters": [
{
"id": 1,
"fighterId": 1,
"amount_of_monsters": 4,
"difficulty": "Medium"
},
{
"id": 2,
"fighterId": 5,
"amount_of_monsters": 1,
"difficulty": "Easy"
},
{
"id": 3,
"fighterId": 5,
"amount_of_monsters": 2,
"difficulty": "Medium"
},
{
"id": 4,
"fighterId": 7,
"amount_of_monsters": 1,
"difficulty": "Hard"
},
{
"id": 5,
"fighterId": 11,
"amount_of_monsters": 7,
"difficulty": "Medium"
},
{
"id": 6,
"fighterId": 7,
"amount_of_monsters": 2,
"difficulty": "Easy"
},
{
"id": 7,
"fighterId": 14,
"amount_of_monsters": 10,
"difficulty": "Extreme"
},
{
"id": 8,
"fighterId": 13,
"amount_of_monsters": 4,
"difficulty": "Medium"
},
{
"id": 9,
"fighterId": 7,
"amount_of_monsters": 5,
"difficulty": "Hard"
},
{
"id": 10,
"fighterId": 3,
"amount_of_monsters": 5,
"difficulty": "Easy"
}
]
}
Line 5 is "name": "Karl",
There's something wrong with my dateOfBirth attribute and I don't know why, because to me the syntax looks correct. I've tried reinstalling the app and rebuilding the project but that didn't work.
This is my first time posting a question on StackOverflow, so apologies if something isn't clear.
If anyone is able to help, I would greatly appreciate it.
EDIT (additional info)
I'm using Android Studio 3.6, API 29.
Android Gradle Plugin Version: 3.5.3
Gradle Version: 5.4.1
I use GSON to parse the JSON
JDK 11
This is the function I used for the GSON class:
fun getFighters(): Observable<Array<Fighter>> {
val observable = Observable.create<Array<Fighter>> { emitter ->
try {
var connection = connect("${BASE_URL}/fighters")
val gson = GsonBuilder().create()
val fighters = gson.fromJson(
InputStreamReader(connection.inputStream),
Array<Fighter>::class.java
)
for (fighter in fighters) {
connection = connect("${BASE_URL}/${fighter.image}")
fighter.imageBitmap = BitmapFactory.decodeStream(connection.inputStream)
}
emitter.onNext(fighters)
} catch(e: Exception) {
emitter.onError(e)
}
}
return observable
}
The BASE_URL is just a testing url since the assignment we have to do doesn't require to actually deploy the app. The for loop is to show the images of the Fighters in a RecyclerView list, so therefore I used a bitmap. Furthermore, here's the basic Fighter data class:
data class Fighter(
val id: Number,
val name: String,
val dateOfBirth: LocalDate,
val level: Number,
val image: String,
var imageBitmap: Bitmap
)
I think the class that you are using for parsing the JSON should be modified as follows.
data class Fighter(
val id: Number,
val name: String,
val dateOfBirth: String,
val level: Number,
val image: String,
var imageBitmap: Bitmap
)
The dateOfBirth is stored as a String in your JSON and you need to fetch that in that way. If you need to convert the value to a LocalDate object, you can always do that later after parsing the information. I hope that helps!
{
"totalHits": 500,
"hits": [
{
"largeImageURL": "https://pixabay.com/get/52e3d6414352af14f6da8c7dda79367b153fdee254506c4870277bd3934ec45ebf_1280.jpg",
"webformatHeight": 424,
"webformatWidth": 640,
"likes": 11,
"imageWidth": 4456,
"id": 4332903,
"user_id": 1151065,
"views": 697,
"comments": 14,
"pageURL": "https://pixabay.com/photos/evangelion-mech-unit-02-robot-4332903/",
"imageHeight": 2958,
"webformatURL": "https://pixabay.com/get/52e3d6414352af14f6da8c7dda79367b153fdee254506c4870277bd3934ec45ebf_640.jpg",
"type": "photo",
"previewHeight": 99,
"tags": "evangelion mech unit 02, robot, fighter",
"downloads": 311,
"user": "vinsky2002",
"favorites": 0,
"imageSize": 878944,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2019/05/15/02-40-06-911_250x250.png",
"previewURL": "https://cdn.pixabay.com/photo/2019/07/12/13/44/evangelion-mech-unit-02-4332903_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/55e7d54b4d51a514f6da8c7dda79367b153fdee254506c4870277bd3934ec45ebf_1280.jpg",
"webformatHeight": 359,
"webformatWidth": 640,
"likes": 18,
"imageWidth": 3863,
"id": 3708739,
"user_id": 10248012,
"views": 2696,
"comments": 2,
"pageURL": "https://pixabay.com/photos/sky-dark-night-moon-moonlight-3708739/",
"imageHeight": 2170,
"webformatURL": "https://pixabay.com/get/55e7d54b4d51a514f6da8c7dda79367b153fdee254506c4870277bd3934ec45ebf_640.jpg",
"type": "photo",
"previewHeight": 84,
"tags": "sky, dark, night",
"downloads": 1036,
"user": "Sritam_kumar_Sethy",
"favorites": 25,
"imageSize": 2027189,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2019/09/28/19-27-53-806_250x250.jpeg",
"previewURL": "https://cdn.pixabay.com/photo/2018/09/28/08/37/sky-3708739_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/57e2dc4a4c5aaf14f6da8c7dda79367b153fdee254506c4870277bd3934ec45ebf_1280.jpg",
"webformatHeight": 360,
"webformatWidth": 640,
"likes": 14,
"imageWidth": 4608,
"id": 1299683,
"user_id": 1151065,
"views": 2932,
"comments": 3,
"pageURL": "https://pixabay.com/photos/panda-z-panda-toy-children-child-1299683/",
"imageHeight": 2592,
"webformatURL": "https://pixabay.com/get/57e2dc4a4c5aaf14f6da8c7dda79367b153fdee254506c4870277bd3934ec45ebf_640.jpg",
"type": "photo",
"previewHeight": 84,
"tags": "panda-z, panda, toy",
"downloads": 1067,
"user": "vinsky2002",
"favorites": 7,
"imageSize": 1745060,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2019/05/15/02-40-06-911_250x250.png",
"previewURL": "https://cdn.pixabay.com/photo/2016/04/01/09/56/panda-z-1299683_150.jpg"
},
],
"total": 588
}
The API I'm fetching returns json value like this. I wrote the following code to extract the data, it works if I code it like this and the widget builds, but with this error before the widget loads
Future getJsonData() async{
var response;
for(int i=1; i<=5; i++){
response = await http.get(
Uri.encodeFull(widget.api+i.toString()),
headers: {"Accept": "application/json"}
);
setState(() {
var toJsonData = json.decode(response.body);
item.addAll(toJsonData['hits']);
});
}
print(response.body);
return item;
}
error image
But when I use FutureBuilder method, it fails to create the widget. It would be helpful if someone can tell a possibly working FutureBuilder method for this json data.
My Json Value is
{"candidateName":"Check","success":true,"candidateWorkExperience":"[{\"candidateWorkExperienceId\":7486,\"candidateBiographyRef\":{\"primaryKey\":98567,\"percent\":0.0,\"specialization\":0,\"rating\":0,\"description\":\"Check\",\"properties\":{},\"secondaryKey\":0,\"start\":0,\"limit\":0,\"noOfStud\":0,\"typingTest\":false,\"isPostGrad\":false},\"designation\":\"Check\",\"company\":\"Check\",\"startDate\":\"Jan 1, 2012\",\"endDate\":\"Jan 1, 2014\",\"workTypeMasterRef\":{\"primaryKey\":2,\"percent\":0.0,\"specialization\":0,\"rating\":0,\"description\":\"Permanent\",\"properties\":{},\"secondaryKey\":0,\"start\":0,\"limit\":0,\"noOfStud\":0,\"typingTest\":false,\"isPostGrad\":false},\"achivements\":\"Check\",\"candidateRecordStatus\":\"EXISTING\",\"currentCompany\":\"false\"}]"}
I am trying to pass the same by
JSONArray jarray = jsono.getJSONArray("candidateWorkExperience");
But I am getting org.json.JSON.typeMismatch exception.
Can any one suggest how to load the json data into the array.
Your problem is that you put "[]" which js is interpreting as a string not an array.
The arrays are enclosed by [] with no ".
Try the next json and let me know if this fix your problem:
{
"candidateName": "Check",
"success": true,
"candidateWorkExperience": [
{
"candidateWorkExperienceId": 7486,
"candidateBiographyRef": {
"primaryKey": 98567,
"percent": 0.0,
"specialization": 0,
"rating": 0,
"description": "Check",
"properties": {
},
"secondaryKey": 0,
"start": 0,
"limit": 0,
"noOfStud": 0,
"typingTest": false,
"isPostGrad": false
},
"designation": "Check",
"company": "Check",
"startDate": "Jan1, 2012",
"endDate": "Jan1, 2014",
"workTypeMasterRef": {
"primaryKey": 2,
"percent": 0.0,
"specialization": 0,
"rating": 0,
"description": "Permanent",
"properties": {
},
"secondaryKey": 0,
"start": 0,
"limit": 0,
"noOfStud": 0,
"typingTest": false,
"isPostGrad": false
},
"achivements": "Check",
"candidateRecordStatus": "EXISTING",
"currentCompany": "false"
}
]
}
Your JSON is not correct, your "candidateWorkExperience" parameter is not a JSONArray but a JSONString.
Paste your JSON here
And you will see how you JSON is parsed.
Cheers !