【问题标题】:java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()java.lang.RuntimeException:无法在未调用 Looper.prepare() 的线程内创建处理程序
【发布时间】:2016-01-18 18:12:03
【问题描述】:

我正在使用以下MainActivity,但仍然收到以下错误消息:

Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:344)
at android.widget.Toast.<init>(Toast.java:100)
at android.widget.Toast.makeText(Toast.java:258)
at com.example.edtomach.whatstheweather.MainActivity$DownloadTask.doInBackground(MainActivity.java:114)
at com.example.edtomach.whatstheweather.MainActivity$DownloadTask.doInBackground(MainActivity.java:80)

为什么会出现此错误?相关代码在这里:

public class MainActivity extends Activity {
    EditText cityname;
    TextView resulttextview;

    public void findWeather(View view) {
        Log.i("cityname", cityname.getText().toString());

        InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mgr.hideSoftInputFromWindow(cityname.getWindowToken(), 0);

        try {
            String encodedCityName = URLEncoder.encode(cityname.getText().toString(), "UTF-8");

            DownloadTask task = new DownloadTask();
            task.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCityName);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

            Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
        }
    }

    @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);
    }

    public class DownloadTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            String result = "";
            URL url;
            HttpURLConnection urlConnection = null;
            try {
                url = new URL(urls[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream in = urlConnection.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 (Exception e) {
                Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
            }

            return null;
        }

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

            try {
                String message = "";
                JSONObject jsonObject = new JSONObject(result);

                String weatherInfo = jsonObject.getString("weather");
                Log.i("Weather content", weatherInfo);

                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 != "") {
                        message += main + ": " + description + "\r\n";
                    }
                }

                if (message != "") {
                    resulttextview.setText(message);
                } else {
                    Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

【问题讨论】:

  • 标题的“或不被使用”部分是什么意思?
  • 不,这只是我试图发布的标题,因为我研究过的这个主题的类似答案对我没有帮助

标签: java android-looper


【解决方案1】:

不要放任何东西可以修改从 asynctask 进程继承的 doBackground 方法上的主线程,在你的情况下,当你捕捉到异常时你会放上 toast 消息:

Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();

而不是使用记录器消息,例如:Log.(TAG, "your message");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-27
    • 2019-06-04
    • 1970-01-01
    相关资源
    最近更新 更多