使用AsyncTask

时间:2016-08-14 20:53:17

标签: java android android-asynctask

我已检查过我引用的TextView是否正确,并确定该应用具有互联网权限。

我试图编写一个应用程序,它将从Coinbase的API中提取比特币的当前价格并将其显示在TextView中。与API交互的代码完全从我编写的桌面java程序中复制,以获取价格并将其放入数据库中;现在差不多一个星期一直在运行。

然而,该应用程序在启动时崩溃。这是唯一的java代码:

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

}

3 个答案:

答案 0 :(得分:2)

doInBackground无法触及UI。如果您需要这样做,请拨打这些电话(setText()),请执行'onPreExecute()'或onPostExecute()

答案 1 :(得分:1)

问题是您无法在doInBackground(方法)中更改UI,并且您调用了ticker.setText(),这就是为什么它会给出错误。 在后台任务完成后,使用onPreExecute()方法初始化变量和onPostExecute()方法来执行任务。

我在这里更新了你的代码,它会运行良好。看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

答案 2 :(得分:0)

尝试使用private class TickerTask extends AsyncTask<String, String, String>代替private class TickerTask extends AsyncTask<Void, Void, Void>