为啥我在执行 doInBackground() 时出错

Posted

技术标签:

【中文标题】为啥我在执行 doInBackground() 时出错【英文标题】:why i get An error occurred while executing doInBackground()为什么我在执行 doInBackground() 时出错 【发布时间】:2020-02-09 08:18:06 【问题描述】:

我正在尝试创建一个使用 api 和 JSONObject 从 Web 提取信息的应用程序。 我了解到我需要使用 asyncTask 来执行此操作,因此我创建了一个扩展 asyncTask 的类。 但应用不断崩溃。

我的异步任务:

public class MyDownloadTask extends AsyncTask<String, String, String> 

SecondActivity secondActivity;
Context context;

boolean tof;

@Override
protected String doInBackground(String... urls) 
    MyBoiler myData = null;
    try 
        myData = new MyBoiler("0e3a4cef498bc2ad18a97e1817c79e87", "50.4019514,30.6727719", "Ramat-Gan");
        tof = myData.openBoiler(30, 20);

     catch (IOException e) 
        e.printStackTrace();
     catch (JSONException e) 
        e.printStackTrace();
    
    return tof ? "true" : "false";



@Override
protected void onPostExecute(String s) 
    super.onPostExecute(s);

    printToTV(tof, secondActivity);



public void printToTV(boolean turnOnOrNot, Context context)
    int cloud = 0;
    int temp = 0;
    LinearLayout linearLayout = (LinearLayout)secondActivity.findViewById(R.id.secActLayout);
    TextView tvToF = new TextView(context);
    TextView tvCloud = new TextView(context);
    TextView tvTemp = new TextView(context);

    tvToF.setText(turnOnOrNot ? "Turn On" : "Dont Turn On");
    String cloudString = String.valueOf(cloud);
    tvCloud.setText(cloud + "% cloud coverage");
    String tempString = String.valueOf(temp);
    tvTemp.setText(temp + " Celsius Degrees");
    linearLayout.addView(tvToF);
    linearLayout.addView(tvCloud);
    linearLayout.addView(tvTemp);

我正在尝试使用它的活动

public class SecondActivity extends AppCompatActivity 

Button boilerBtn;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);


    boilerBtn = findViewById(R.id.openBoilerBtn);
    boilerBtn.setOnClickListener(new View.OnClickListener()

        @Override
        public void onClick(View view) 
            new MyDownloadTask().execute(MyBoiler.fullURL);
        


    );

myBoiler 类:

public class MyBoiler 
public final String API_URL = "https://api.darksky.net/forecast/"; // url of the site
private String apiKey; // api key from the site
private String GPSlocation; // gps location -_-
private String rawData; // the raw data
protected static String fullURL; // the full url location
private String cityName; // name of the city
JSONObject jsonObject;

public MyBoiler(String apiKey, String GPSlocation, String cityName) throws IOException, JSONException 
    this.apiKey = apiKey;
    this.GPSlocation = GPSlocation;
    this.cityName = cityName;
    // create the full url
    fullURL = API_URL + this.apiKey + "/" + this.GPSlocation;


private JSONObject readJsonFromUrl()throws IOException, JSONException
    //open a connection to the internet
    InputStream is = new URL(this.fullURL).openStream();
    // create a buffer for collection of all data
    BufferedReader buf = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
    // read all data and append it to one happy string
    String jsonText = readAll(buf);
    //convert to json object so we can use the json power
    jsonObject = new JSONObject(jsonText);
    // returns the json object
    return jsonObject;


private String readAll(BufferedReader rd) throws IOException 
    // create a string builder
    StringBuilder sb = new StringBuilder();
    // create a char point
    int cp;
    while((cp = rd.read()) != -1)
        sb.append(cp);
    
    // sets the rawData value to the string
    rawData = sb.toString();
    // return the result
    return sb.toString();


public String getRaw()
    return rawData;


public int getCloud(JSONObject cur) throws  IOException, JSONException
    int cloud = (int)(cur.getDouble("cloudCover")*100);
    return cloud;


public int getTemp(JSONObject cur) throws IOException, JSONException
   int temp = (int)(cur.getDouble("temperature"));
   return (int)((temp-32)/1.8);


public boolean openBoiler(int tolerance, int minTemp)throws IOException, JSONException
    JSONObject myData = readJsonFromUrl();
    JSONObject currently = myData.getJSONObject("currently");

    return getCloud(currently) > tolerance && getTemp(currently) < minTemp;

日志猫:

E/androidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.myturnonboilerapp, PID: 24762
java.lang.RuntimeException: An error occurred while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:354)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
    at java.util.concurrent.FutureTask.run(FutureTask.java:271)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:764)
 Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
    at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:151)
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:105)
    at java.net.InetAddress.getAllByName(InetAddress.java:1154)
    at com.android.okhttp.Dns$1.lookup(Dns.java:39)
    at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175)
    at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141)
    at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83)
    at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)
    at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
    at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
    at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
    at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:244)
    at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
    at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:26)
    at java.net.URL.openStream(URL.java:1072)
    at com.example.myturnonboilerapp.MyBoiler.readJsonFromUrl(MyBoiler.java:32)
    at com.example.myturnonboilerapp.MyBoiler.openBoiler(MyBoiler.java:72)
    at com.example.myturnonboilerapp.MyDownloadTask.doInBackground(MyDownloadTask.java:26)
    at com.example.myturnonboilerapp.MyDownloadTask.doInBackground(MyDownloadTask.java:14)
    at android.os.AsyncTask$2.call(AsyncTask.java:333)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
    at java.lang.Thread.run(Thread.java:764) 
 Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
    at libcore.io.Linux.android_getaddrinfo(Native Method)
    at libcore.io.BlockGuardOs.android_getaddrinfo(BlockGuardOs.java:172)
    at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:137)
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:105) 
    at java.net.InetAddress.getAllByName(InetAddress.java:1154) 
    at com.android.okhttp.Dns$1.lookup(Dns.java:39) 
    at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175) 
    at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141) 
    at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83) 
    at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174) 
    at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126) 
    at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95) 
    at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281) 
    at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224) 
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461) 
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407) 
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:244) 
    at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210) 
    at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:26) 
    at java.net.URL.openStream(URL.java:1072) 
    at com.example.myturnonboilerapp.MyBoiler.readJsonFromUrl(MyBoiler.java:32) 
    at com.example.myturnonboilerapp.MyBoiler.openBoiler(MyBoiler.java:72) 
    at com.example.myturnonboilerapp.MyDownloadTask.doInBackground(MyDownloadTask.java:26) 
    at com.example.myturnonboilerapp.MyDownloadTask.doInBackground(MyDownloadTask.java:14) 
    at android.os.AsyncTask$2.call(AsyncTask.java:333) 
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
    at java.lang.Thread.run(Thread.java:764) 
 Caused by: android.system.ErrnoException: android_getaddrinfo failed: EACCES (Permission denied)
    at libcore.io.Linux.android_getaddrinfo(Native Method) 
    at libcore.io.BlockGuardOs.android_getaddrinfo(BlockGuardOs.java:172) 
    at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:137) 
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:105) 
    at java.net.InetAddress.getAllByName(InetAddress.java:1154) 
    at com.android.okhttp.Dns$1.lookup(Dns.java:39) 
    at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175) 
    at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141) 
    at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83) 
    at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174) 
    at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126) 
    at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95) 
    at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281) 
    at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224) 
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461) 
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407) 
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:244) 
    at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210) 
    at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:26) 
    at java.net.URL.openStream(URL.java:1072) 
    at com.example.myturnonboilerapp.MyBoiler.readJsonFromUrl(MyBoiler.java:32) 
    at com.example.myturnonboilerapp.MyBoiler.openBoiler(MyBoiler.java:72) 
    at com.example.myturnonboilerapp.MyDownloadTask.doInBackground(MyDownloadTask.java:26) 
    at com.example.myturnonboilerapp.MyDownloadTask.doInBackground(MyDownloadTask.java:14) 
    at android.os.AsyncTask$2.call(AsyncTask.java:333) 
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
    at java.lang.Thread.run(Thread.java:764) 

I/Process:发送信号。 PID:24762 SIG:9 进程 24762 终止。

我的第二个活动 xml:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    tools:context=".SecondActivity"
    android:id="@+id/secActLayout">

<Button
    android:layout_
    android:layout_
    android:id="@+id/openBoilerBtn"
    android:text="Turn On"
    android:textAllCaps="false"/>

</LinearLayout>

【问题讨论】:

【参考方案1】:

Internet 权限缺失,将以下代码添加到您的 AndroidManifest.xml 中

<uses-permission android:name="android.permission.INTERNET" />

【讨论】:

我添加了,但现在我得到:尝试在空对象引用上调用虚拟方法 'android.view.View android.app.Activity.findViewById(int)',可能是因为我正在尝试空secondActivity 在我的 printToTv 方法中,但我不知道任何其他方法可以使 findviewbyid 工作.. 在非活动类中。帮助? 请显示您的activity_second.xml的xml代码 您没有在 MyDownloadTask 中传递活动实例,创建 MyDownloadTask 的构造函数,并使用 SecondActivity 作为 ann 参数,或者通过这篇文章***.com/questions/12252654/… 它现在工作了,上帝保佑你,祝你财富和健康

以上是关于为啥我在执行 doInBackground() 时出错的主要内容,如果未能解决你的问题,请参考以下文章

为啥 doInbackground 方法不能有空体?

运行时异常:在Activity执行doInBackground时出错

为 keyclock authService.performTokenRequest() 函数执行 doInBackground() 时出错

在 client.execute(httpGet) 上的 doInBackground() 行上发生崩溃。为啥?

为啥我的 AsyncTask 在主线程上运行?

致命异常:AsyncTask #1 java.lang.RuntimeException:执行 doInBackground() 时发生错误