Harsh Sani
Harsh Sani

Reputation: 39

AndroidRuntime: FATAL EXCEPTION: AsyncTask #1 Process

This is the code I am trying to run:

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


  }
}

I have this app that I'm building but the catch statements are not working. Whenever there is an exception the app crashes and the following error appears in the logs, and I don't know why. Please do help!

Here is the error:

FATAL EXCEPTION: AsyncTask #1 Process: com.harshs.whatstheweather, PID: 11019 java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:318) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354) at java.util.concurrent.FutureTask.setException(FutureTask.java:223) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) at java.lang.Thread.run(Thread.java:761) Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() at android.os.Handler.(Handler.java:200) at android.os.Handler.(Handler.java:114) at android.widget.Toast$TN.(Toast.java:346) at android.widget.Toast.(Toast.java:101) at android.widget.Toast.makeText(Toast.java:260) at com.harshs.whatstheweather.MainActivity$Weather.doInBackground(MainActivity.java:85) at com.harshs.whatstheweather.MainActivity$Weather.doInBackground(MainActivity.java:52) at android.os.AsyncTask$2.call(AsyncTask.java:304) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)  at java.lang.Thread.run(Thread.java:761)

Please tell me what the error means.

Upvotes: 0

Views: 766

Answers (1)

FEBRYAN ASA PERDANA
FEBRYAN ASA PERDANA

Reputation: 131

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

You should do more debugging to know what is the root cause of the error. Usually you can find the caused by line in the log/stack trace, thus you can know which part of your code are causing the error and fix that.

I think the error here is you are trying to make a Toast in doInBackground() method. Try to remove that, and capture the exception/error in onPostExecute() instead, and make/show Toast from there. doInBackground() does not execute in UI thread. If you are wrapping the AsyncTask class as an inner class in an Activity, you can also try to call runOnUiThread() method and make/show Toast from there, too.

Hope this helps.

Upvotes: 2

Related Questions