Reputation: 1
I am relatively new to android studio. I am trying to build a very simple app that fetches the price of cryptocurrencies using the Bittrex exchanges api. However every time I try to get the info from the URL, my app crashes. I am using Kotlin by the way. I'm having trouble solving this because I don't know how to run the emulator in debug mode, just the compiler. Here is my code:
package com.example.sebastian.cryptoapp
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import java.net.URL
import java.net.MalformedURLException
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
fun search(): String {
//read in value
var market = searchBar.getText().toString()
//output text from URL query
val result = URL("https://bittrex.com/api/v1.1/public/getticker?market="
+ market).readText()
return result
}
fun getPrice(): String {
//calling search function
var info = search()
//split the string into a list
var list: List<String> = info.split(":", "}")
//access 7th index of list for last traded price
return list[6]
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
text_output.setText(getPrice())
}
}
}
Upvotes: 0
Views: 932
Reputation: 2331
This line here:
val result = URL("https://bittrex.com/api/v1.1/public/getticker?market=" + market).readText()
looks like it is being run on the main thread. This will cause the app to crash with a a NetworkOnMainThreadException
.
You can read more on this exception here.
Also, make sure you have the following in your AndroidManifest.xml
:
<uses-permission android:name="android.permission.INTERNET" />
Check out these answers for more information on how to run this in the background:
Alternatively in Kotlin you could also Anko or Coroutines.
Upvotes: 2