AndroidRuntime:致命例外:AsyncTask#1进程

问题描述 投票:0回答:1

这是我要运行的代码:

package com.harshs.whatstheweather;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.lang.*;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class MainActivity extends AppCompatActivity {

  EditText cityName;
  TextView resultTextView;

  public void findWeather(View view) {

    Log.i("Button", cityName.getText().toString());

    InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    mgr.hideSoftInputFromInputMethod(cityName.getWindowToken(), 0);

    try {

      Weather task = new Weather();

      String encodedURL = URLEncoder.encode(cityName.getText().toString(), "UTF-8");

      task.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedURL + "&appid=ecd9af9d7b34407890a8b4096b6b90e2");

    } catch (Throwable e) {

      Toast.makeText(getApplicationContext(), "Could not find the Weather", Toast.LENGTH_LONG);

    }
  }

  class Weather extends AsyncTask < String, Void, String > {

    @Override
    protected String doInBackground(String...urls) {

      String result = "";

      URL url;

      HttpURLConnection connection;

      try {
        url = new URL(urls[0]);

        connection = (HttpURLConnection) url.openConnection();

        InputStream in = connection.getInputStream();

        InputStreamReader reader = new InputStreamReader( in );

        int data = reader.read();

        while (data != -1) {

          char current = (char) data;
          result += current;

          data = reader.read();
        }
        return result;

      } catch (Throwable e) {

        Toast.makeText(getApplicationContext(), "Could not find the Weather", Toast.LENGTH_LONG);

      }
      return null;
    }

    @Override
    protected void onPostExecute(String result) {
      super.onPostExecute(result);

      try {

        String mess = "";

        JSONObject jsonObject = new JSONObject(result);
        String weatherInfo = jsonObject.getString("weather");

        JSONArray arr = new JSONArray(weatherInfo);

        for (int i = 0; i < arr.length(); i++) {

          JSONObject jSonPart = arr.getJSONObject(i);

          String main = "";
          String description = "";


          main = jSonPart.getString("main");
          description = jSonPart.getString("description");

          if (main != "" && description != "'") {

            mess += main + ": " + description + "\r\n";
          }
        }
        if (mess != "") {

          resultTextView.setText(mess);

        } else {

          Toast.makeText(getApplicationContext(), "Could not find the Weather", Toast.LENGTH_LONG);

        }

      } catch (JSONException e) {

        Toast.makeText(getApplicationContext(), "Could not find the Weather", Toast.LENGTH_LONG);

      }

    }
  }

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

    cityName = (EditText) findViewById(R.id.cityName);
    resultTextView = (TextView) findViewById(R.id.resultTextView);


  }
}

我有正在构建的这个应用程序,但是catch语句不起作用。只要有例外,应用程序就会崩溃,并且日志中会出现以下错误,我不知道为什么。请帮忙!

这里是错误:

致命异常:AsyncTask#1流程:com.harshs.whatstheweather,PID:11019java.lang.RuntimeException:执行时发生错误doInBackground()在android.os.AsyncTask $ 3.done(AsyncTask.java:318)在java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)在java.util.concurrent.FutureTask.setException(FutureTask.java:223)在java.util.concurrent.FutureTask.run(FutureTask.java:242)在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:243)在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)在java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:607)在java.lang.Thread.run(Thread.java:761)原因:java.lang.RuntimeException:无法在其中创建处理程序没有调用Looper.prepare()的线程在android.os.Handler。(Handler.java:200)在android.os.Handler。(Handler.java:114)在android.widget.Toast $ TN。(Toast.java:346)在android.widget.Toast(Toast.java:101)在android.widget.Toast.makeText(Toast.java:260)在com.harshs.whatstheweather.MainActivity $ Weather.doInBackground(MainActivity.java:85)在com.harshs.whatstheweather.MainActivity $ Weather.doInBackground(MainActivity.java:52)在android.os.AsyncTask $ 2.call(AsyncTask.java:304)在java.util.concurrent.FutureTask.run(FutureTask.java:237)在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:243)在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)在java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:607)在java.lang.Thread.run(Thread.java:761)

请告诉我错误是什么意思。

android android-asynctask
1个回答
2
投票

Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

您应该进行更多的调试,以了解错误的根本原因。通常,您可以在日志/堆栈跟踪中找到caused by行,因此您可以知道导致错误的代码的哪一部分并予以解决。

我认为这里的错误是您正在尝试使用doInBackground()方法烤面包。尝试将其删除,然后捕获onPostExecute()中的异常/错误,然后从此处制作/显示Toast。 doInBackground()在UI线程中不执行。如果将AsyncTask类包装为Activity中的内部类,则也可以尝试调用runOnUiThread()方法并从此处进行制作/显示Toast。

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.