How can i parse code from URL in Android? - android

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

Related

how to get youtube videoId from url?

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)?=))([^#\&\?]*).*/

How to parse or split URL Address in Kotlin?

If I have this url address
https://googledroids.com/post.html?limit=25&since=1374196005&md5=d8959d12ab687ed5db978cb078f1e&time=0dfdbac117
How could I get (or split) parameters (avoiding hard coding)?
I need separated values:
https
googledroids.com
/post.html
parameters and values: {limit=25, time=0dfdbac117, since=1374196005, md5=d8959d12ab687ed5db978cb078f1e}
The following should work, it gives a list of parameter values rather than just one.
val uri = Uri.parse("https://googledroids.com/post.html?limit=25&since=1374196005&md5=d8959d12ab687ed5db978cb078f1e&time=0dfdbac117")
val host = uri.host // googledroids.com
val protocol = uri.scheme // https
val path = uri.path // /post.html
val parameters = uri.queryParameterNames.associateWith { uri.getQueryParameters(it) } // {limit:[25], time:[0dfdbac117], since:[1374196005], md5:[d8959d12ab687ed5db978cb078f1e]}
Using the class:
import android.net.Uri
We can the values protocol, server, path, parameters and we have the option to get a specific parameter value using uri.getQueryParameter():
val url = "https://googledroids.com/post.html?limit=25&since=1374196005&md5=d8959d12ab687ed5db978cb078f1e&time=0dfdbac117"
val uri = Uri.parse(url)
val protocol = uri.scheme // https
val server = uri.authority // googledroids.com
val path = uri.path // /post.html
val args = uri.queryParameterNames //size: 4 parameters
val limit = uri.getQueryParameter("limit") // limit: "25"
println("value of limit: $limit")
we can get a list of parameters too (Using this question´s answer (java)):
val url = "https://googledroids.com/post.html?limit=25&since=1374196005&md5=d8959d12ab687ed5db978cb078f1e&time=0dfdbac117"
val uri = Uri.parse(url)
val protocol = uri.scheme // https
val server = uri.authority // googledroids.com
val path = uri.path // /post.html
val args = uri.queryParameterNames //size: 4 parameters
val query = uri.query
val data: MutableMap<String, String> = HashMap()
for (param in query?.split("&")?.toTypedArray()!!) {
val params = param.split("=").toTypedArray()
val paramName = URLDecoder.decode(params[0], UTF_8)
var value = ""
if (params.size == 2) {
value = URLDecoder.decode(params[1], UTF_8)
}
data[paramName] = value
}
println("$data") //{limit=25, time=0dfdbac117, since=1374196005, md5=d8959d12ab687ed5db978cb078f1e}
this is a better and easy way to get the paramaters and values using uri.queryParameterNames:
val uri = Uri.parse(url)
val protocol = uri.scheme
val server = uri.authority
val path = uri.path
val args = uri.queryParameterNames
val limit = uri.getQueryParameter("limit")
val query = uri.query
for (paramName in uri.queryParameterNames) {
println("parameter => $paramName | value: ${uri.getQueryParameter(paramName)}")
}
}

Get a value from JSON using crypto API with Kotlin(Android Studio)

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

Convert string with separator to data class instance

I have a string separated by ";" like this:
var dataString: String = "Juan;25;Argentina"
And I want to convert it to this sample data class:
data class Person (
var name: String? = "",
var age: Int? = "",
var location: String? = "")
The only way I figured out to that is like this:
var dataString: String = "Juan;25;Argentina"
var fieldList = dataString.split(";").map { it.trim() }
var personItem = Person(fieldList[0], fieldList[1], fieldList[2])
But this is too static, if I then have to add new field to Person data class, I have to manually add fieldList[3]
Which is the most efficient way to do this? (I searched a lot, but couldn't find it :S )
SOLUTION:
//Data in string
val rawData = "name;age;location\nPerson1;20;USA\nPerson2;30;Germany"
//Custom string reader with ";" separator
val customCSV = csvReader { delimiter = ';' }
//String to map list
val parsed = csvReader().readAllWithHeader(rawData)
//Mal list to list of <Person>
val finalData = grass<Person>().harvest(parsed)
for (entry in entryList) {
//entry is an instance of Person
}
EDIT2:
You can obtain field names for header line like this:
var headerLine = ""
for (entry in Person::class.members) {
if (member.name.isNotEmpty())
headerLine += ";${member.name}"
}
headerLine.substring(1)
The string you showed here looks like a CSV dataset. So I think you could use kotlin-grass and kotlin-csv
https://github.com/blackmo18/kotlin-grass
https://github.com/doyaaaaaken/kotlin-csv/
Example:
val rawData = "Person1;20;USA/nPerson1;30;Germany"
val parsed = csvReader().readAllWithHeader(rawData)
val finalData = grass<Person>().harvest(parsed)

Accessing local variable in lambda in Kotlin

I want to save data acquired from Volley, But lambda used in VolleyRequest function(which gets json data from server) blocks it.
How should I change local variable that is in outside of lambda?
Thanks in advance.
class ConDataforReturn( val title:String , val imgDataList: ArrayList<ConImgData>)
fun getConData(context: Context, idx : String):ConDataforReturn{
val params = HashMap<String,String>()
var cd = arrayListOf<ConImgData>()
var title =""
params.put("package_idx",idx)
Log.e("idx size",idx.length.toString())
VolleyRequest(context,params,"https://dccon.dcinside.com/index/package_detail") { response ->
val answer = JSONObject(response)
var json = answer.getJSONArray("detail")
title = answer.getJSONObject("info").getString("title")
Log.d("title",title)//Prints right data
for (i in 0..(json.length() - 1)) {
val v = json.getJSONObject(i)
cd.add(ConImgData(v.getString("title"), v.getString("ext"), v.getString("path")))
}
}
return ConDataforReturn(title,cd)//returns ConDataforReturn("",arrayListOf<ConImgData>())
}
Here the the code from were you are calling this method
getConData(this, "id") { condata ->
}
Now, your method look like this,
fun getConData(context: Context, idx : String, returnConData : (condata : ConDataforReturn) -> Unit){
val params = HashMap<String,String>()
var cd = arrayListOf<ConImgData>()
var title =""
params.put("package_idx",idx)
Log.e("idx size",idx.length.toString())
VolleyRequest(context,params,"https://dccon.dcinside.com/index/package_detail") { response ->
val answer = JSONObject(response)
var json = answer.getJSONArray("detail")
title = answer.getJSONObject("info").getString("title")
Log.d("title",title)//Prints right data
for (i in 0..(json.length() - 1)) {
val v = json.getJSONObject(i)
cd.add(ConImgData(v.getString("title"), v.getString("ext"), v.getString("path")))
}
returnConData(ConDataforReturn(title,cd)) //returns ConDataforReturn("",arrayListOf<ConImgData>())
}
}

Categories

Resources