I've checked that the TextView I'm referencing is correct and am sure that the app has internet permission.
I'm attempting to write an app that will pull the current price of Bitcoin from Coinbase's API and display it in the TextView. The code for interacting with the API was copied exactly from a desktop java program I wrote to get the price and put it into a database; whichd has been running without a hitch for almost a week now.
The app, though, crashes on start up. Here is the only java code:
import android.app.*;
import android.os.*;
import android.widget.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String price = "";
TextView tester = (TextView) findViewById(R.id.ticker);
tester.setText("new text");//This is not displayed before crash
TickerTask ticker = new TickerTask();
ticker.execute();
}
private class TickerTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... nothing) {
String coinbase = "https://api.coinbase.com/v2/prices/spot?currency=USD";
int i = 0;
int y = 0;
String price = "";
String formatted_price;
TextView ticker = (TextView) findViewById(R.id.ticker);
try {
URL url = new URL(coinbase);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader (
new InputStreamReader(connection.getInputStream()));
String urlString = "";
String current;
while ((current = in.readLine()) != null) {
urlString += current;
}
int begin = urlString.indexOf("amount");
int end = urlString.indexOf("currency");
price = urlString.substring(begin+9, end-3);
ticker.setText(price);
} catch (Exception e) {
ticker.setText(e.getMessage());
}
y++;
return nothing[0];
}//End of doInBackground
}//End of TickerTask
}