0

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())
}
}
}
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • 3
    Learning how to use the debugger is a priority. Then you can check if you're actually getting what you expect back from the api. I'm guessing here, but I think list[6] is out of bounds. – Mathemats Jun 25 '17 at 23:37
  • I tested the code in IntelliJ beforehand and it worked so I know it's not that – user8213376 Jun 27 '17 at 14:29

1 Answers1

2

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.

Bulwinkel
  • 2,111
  • 25
  • 23