It doesn't matter, but the language I'm using is kotlin.
my get video Id code
fun getVideoIdFromYoutubeUrl(url: String?): String? {
var videoId: String? = null
val regex =
"(?:https?:\\/\\/)?(?:www\\.)?youtu(?:\\.be\\/|be.com\\/\\S*(?:watch|shorts)(?:(?:(?=\\/[-a-zA-Z0-9_]{11,}(?!\\S))\\/)|(?:\\S*v=|v\\/)))([-a-zA-Z0-9_]{11,})"
// "http(?:s)?:\\/\\/(?:m.)?(?:www\\.)?youtu(?:\\.be\\/|be\\.com\\/(?:watch\\?(?:feature=youtu.be\\&)?v=|v\\/|embed\\/|user\\/(?:[\\w#]+\\/)+))([^&#?\\n]+)"
val pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE)
val matcher = pattern.matcher(url)
if (matcher.find()) {
videoId = matcher.group(1)
}
return videoId
}
test youtube shots url
https://youtube.com/shorts/IC7M4up0FOI?feature=share
But when I do it with that regular expression, null is returned.
On the other hand, this url works just fine.
https://www.youtube.com/shorts/YK1po3GW9oY
what do i need to fix?
Can you try with this regex
/^.*(?:(?:youtu\.be\/|v\/|vi\/|u\/\w\/|embed\/|shorts\/)|(?:(?:watch)?\?v(?:i)?=|\&v(?:i)?=))([^#\&\?]*).*/
Related
I know this can be achieved using Firebase Deep Linking, but I find it a bit too complicated with a custom domain, so I go with the regular one. But, I could not find how do I add an image, title and subtitle for it? Also, the URL will be dynamic like this:
forms.mysitename.in/solve/randomFormId
Because at the end of the day you're handling URI's you can pass them as query parameters. Note that you should base-64 encode the parameters before interpolating the string as it's otherwise unusable.
If you use Android's Uri class that's handled for you already and can write the following:
Uri
.Builder()
.scheme("https")
.authority("forms.mysitename.in")
.appendPath("solve")
.appendPath("$randomFormId")
.query("title=$title&description=$description&image=$imageUrl")
.build()
Assuming your image parameter is a Url. If it's not a URL you can use the Base64 encoded version into the query parameter but that's not advisable
The following code:
private fun makeUri(): Uri = with(Uri.Builder()) {
val randomFormId = UUID.randomUUID()
val title = "og:meow:My title with spaces and emoji 👀"
val description = "A description :)"
val imageUrl ="https://images.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"
scheme("https")
authority("forms.mysitename.in")
appendPath("solve")
appendPath("$randomFormId")
appendQueryParameter("title", title)
appendQueryParameter("description", description)
appendQueryParameter("image", imageUrl)
build()
}
Log.d("Test", "${makeUri()}")
Prints:
https://forms.mysitename.in/solve/a6d37c1f-ad7d-46f4-87ef-8e77a9159d6a?title=og%3Ameow%3AMy%20title%20with%20spaces%20and%20emoji%20%F0%9F%91%80&description=A%20description%20%3A)&image=https%3A%2F%2Fimages.pexels.com%2Fphotos%2F45201%2Fkitty-cat-kitten-pet-45201.jpeg%3Fauto%3Dcompress%26cs%3Dtinysrgb%26dpr%3D1%26w%3D500
Which is a valid Uri.
You can also use this following function to create a new Uri from an old one:
private fun fromUri(
uri: Uri,
newTitle: String = uri.getQueryParameter("title") ?: "",
newDescription: String = uri.getQueryParameter("description") ?: "",
newImageUrl: String = uri.getQueryParameter("imageUrl") ?: "",
) = with(Uri.Builder()) {
scheme(uri.scheme)
authority(uri.authority)
uri.pathSegments.forEach { pathSegment -> appendPath(pathSegment) }
// Trick to not add it if it's empty
newTitle.takeIf { it.isNotEmpty() }?.let { appendQueryParameter("title", it)}
newDescription.takeIf { it.isNotEmpty() }?.let { appendQueryParameter("description", it)}
newImageUrl.takeIf { it.isNotEmpty() }?.let { appendQueryParameter("imageUrl", it)}
build()
}
I'm building an android app just to show or convert some cripto to USD.. But I dont know how to use and API and get the exact price value of bitcoin(any cripto)...How do I filter the json to get just the right value?
private fun converter(){
val selectedCurrency = findViewById<RadioGroup>(R.id.radioGroup)
val editField = findViewById<EditText>(R.id.edit_field)
val value = editField.text.toString()
if (value.isEmpty() || value == ".")
return
Thread{
//Para here
val url = URL("https://api.coinmarketcap.com/data-api/v3/cryptocurrency/listing?start=1&limit=500")
val conn = url.openConnection() as HttpsURLConnection
try {
val data = conn.inputStream.bufferedReader().readText()
// {"price": 32000.000} what i want to get and idk how
val obj = JSONObject(data)
runOnUiThread{
val res = obj
result.text = res.toString()
result.visibility = View.VISIBLE
}
}finally{
conn.disconnect()
}
}.start()
I have next uri:
https://91c2ee0d-05ff-4611-2192-8472eabe98f1.example.org/redirect#code=d5215173-2be3-4491-bf2a-d9d039a50e97&id_token=eyJhbGciOiJQU
How i can parse my code?
d5215173-2be3-4491-bf2a-d9d039a50e97
I tried to do smth like this:
val uri: Uri = Uri.parse(url)
val code: String = uri.getQueryParameter("code").toString()
But it doesn't work for me.
Right now i solved this problem with next solution:
val url: String = Uri.parse(url).toString()
var code = ""
if (url.contains("#code=")) {
code = url.substring(url.indexOf("#code=") + 6)
if (code.contains("&")) {
code = code.split("&")[0]
}
}
Also you could do it with a Regex:
val url = Uri.parse(url).toString()
val matcher = Pattern.compile("#code=.+&").matcher(url)
val code = if (matcher.find())
url.slice(matcher.start() + 6 until matcher.end() - 1) else ""
I'm trying to do a search system.
In my code I have a list of objects, each object has a name and also has a list of keywords like this:
data class Sample(
val name: String,
val keywords: List<String>,
// etc
)
Now jumping to where I do the search, I have the following code:
private lateinit var samples: List<Sample>
// etc
fun search(keyword: String) {
val samplesSearch: MutableList<Sample> = mutableListOf()
samples.forEach { sample ->
val sampleName = sample.name.toLowerCase(Locale.ROOT)
val sampleKeywords = sample.keywords.joinToString(
separator = ",",
transform = { it.toLowerCase(Locale.ROOT) }
)
if (sampleName.contains(keyword) || sampleKeywords.contains(keyword))
samplesSearch.add(sample)
}
}
That way, it works the way I want. But I have a doubt if it would be possible to get the same result, without using joinToString()...
Without transforming the list of keywords into a single string, the result is not the same because contains() works differently between string and list...
fun search(keyword: String) {
val samplesSearch: MutableList<Sample> = mutableListOf()
samples.forEach { sample ->
val sampleName = sample.name.toLowerCase(Locale.ROOT)
val sampleKeywords = sample.keywords.onEach { it.toLowerCase(Locale.ROOT) }
if (sampleName.contains(keyword) || sampleKeywords.contains(keyword))
samplesSearch.add(sample)
}
}
Using String.contains() just need to have a sequence of characters, without needing the full word.
Using List.contains() need to have the full word.
Update
After milgner's answer I got what I wanted as follows:
fun search(keyword: String) {
val samplesSearch: MutableList<Sample> = mutableListOf()
samples.forEach { sample ->
val sampleName = sample.name
val sampleKeywords = sample.keywords
if (sampleName.contains(keyword, ignoreCase = true) ||
sampleKeywords.any { it.contains(keyword, ignoreCase = true) }
) samplesSearch.add(sample)
}
}
List.contains will check every element in the list against the argument using the equals implementation. If you're looking for a case-insensitive variant, you can use a construct like
sampleKeywords.any { it.equals(keyword, ignoreCase = true) }
There is a function param() in jQuery library
It serializes JS-object into a string set of HTTP parameters
Example: object {a:'x',b:{c:[0,1]}}
$.param({a:'x',b:{c:[0,1]}})
"a=x&b%5Bc%5D%5B%5D=0&b%5Bc%5D%5B%5D=1"
This string is encoded by encodeURIComponent()
It could be decoded by decodeURIComponent()
decodeURIComponent($.param({a:'x',b:{c:[0,1]}}))
"a=x&b[c][]=0&b[c][]=1"
We see that the object is converted into a set of parameters:
a=x
b[c][]=0
b[c][]=1
I need to do the same serialization in my Android application
I have to send data in the same format as is being done by jQuery
So the question is:
Is there some function in Android SDK which is an analogue of jQuery.param() ?
While people stays silent I offer my handmade solution on Kotlin:
fun serialize(data: JSONObject): String {
var result = arrayListOf<String>()
fun parse(value: Any, name: String, alt: String? = null) {
if (value is JSONObject) {
val keys = value.keys()
while (keys.hasNext())
keys.next().let {
parse(value[it], "$name[$it]")
}
} else if (value is JSONArray) {
for (i in 0 until value.length())
parse(value[i], "$name[$i]", "$name[]")
} else {
result.add(Uri.encode(alt ?: name) + "=" + Uri.encode("$value"))
}
}
val keys = data.keys()
while (keys.hasNext())
keys.next().let {
parse(data[it], it)
}
return result.joinToString("&")
}
This variant works identically to jQuery. It would be nice to avoid such homework though :-)