繁体   English   中英

使用AsyncTask时应用程序崩溃

[英]App crashes when using AsyncTask

我已经检查过我正在引用的TextView是否正确,并确定该应用程序具有Internet权限。

我正在尝试编写一个应用程序,它将从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

}

doInBackground无法触摸UI 如果你需要这样做那些调用(在你的情况下为setText() ),请执行'onPreExecute()'或onPostExecute()

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

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

尝试private class TickerTask extends AsyncTask<String, String, String>而不是private class TickerTask extends AsyncTask<Void, Void, Void>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM