App crashes when using AsyncTask

user2465510

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

}
Shaishav Jogani

Problem is you can not change UI in doInBackground(method) and you called ticker.setText() that's why it is giving error. Use onPreExecute() method to initialize variable and onPostExecute() method to do task after background task completed.

I have updated your code here and it will work well. Look here to get idea about lifecycle of asyctask

class TickerTask extends AsyncTask<Void, Void, String> {
    String coinbase;
    int i, y;
    String price, formatted_price;
    TextView ticker;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        coinbase = "https://api.coinbase.com/v2/prices/spot?currency=USD";
        i = 0;
        y = 0;
        price = "";
        ticker = (TextView) findViewById(R.id.ticker);
    }

    protected String doInBackground(Void... nothing) {
        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;
            }

            return urlString;


        } catch (Exception e) {
            return "error"
            e.printStackTrace();
        }
//        return nothing[0];
          return "error";
    }//End of doInBackground

    @Override
    protected void onPostExecute(String urlString) {
        super.onPostExecute(urlString);
        if(!urlString.equal("error")) {
          int begin = urlString.indexOf("amount");
          int end = urlString.indexOf("currency");
          price = urlString.substring(begin + 9, end - 3);
          ticker.setText(price);
        } else 
          ticker.setText("Error");
        y++;
    }
}//End of TickerTask

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related