简体   繁体   English

使用AsyncTask时应用程序崩溃

[英]App crashes when using AsyncTask

I've checked that the TextView I'm referencing is correct and am sure that the app has internet permission. 我已经检查过我正在引用的TextView是否正确,并确定该应用程序具有Internet权限。

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. 我正在尝试编写一个应用程序,它将从Coinbase的API中提取比特币的当前价格并将其显示在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; 与API交互的代码完全从我编写的桌面java程序中复制,以获取价格并将其放入数据库中; 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: 这是唯一的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 cannot touch the UI . doInBackground无法触摸UI If you need to do that make those calls ( setText() in your case), do in 'onPreExecute()' or onPostExecute() . 如果你需要这样做那些调用(在你的情况下为setText() ),请执行'onPreExecute()'或onPostExecute()

Problem is you can not change UI in doInBackground(method) and you called ticker.setText() that's why it is giving error. 问题是你无法在doInBackground(方法)中更改UI,并且你调用了ticker.setText() ,这就是它给出错误的原因。 Use onPreExecute() method to initialize variable and onPostExecute() method to do task after background task completed. 使用onPreExecute()方法初始化变量和onPostExecute()方法,在后台任务完成后执行任务。

I have updated your code here and it will work well. 我在这里更新了你的代码,它会运行良好。 Look here to get idea about lifecycle of asyctask 看看这里了解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