my weather app getting crashing after i enter the Toast [closed]

Tags: , ,



my app was working properly in this code all the city weather data show correctly. i want to add a toast for if someone enter a wrong city name

i can understand what is the error android studio dont give any error . if enter a city name works fine but if i enter a wrong city name or any other word it crashing

working code :::

package com.study.whatstheweather;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.inputmethod.InputMethod;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

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

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

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

        editText = findViewById(R.id.editText);
textView2 = findViewById(R.id.textView2);
    }

    public void getweather (View view){
        Downlordtask task = new Downlordtask();
        task.execute("https://openweathermap.org/data/2.5/weather?q="+ editText.getText().toString()+ "&appid=439d4b804bc8187953eb36d2a8c26a02");
        InputMethodManager methodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        methodManager.hideSoftInputFromWindow(editText.getWindowToken(),0);

    }


    public class Downlordtask 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 inputStream = urlConnection.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                int data = inputStreamReader.read();

                while (data !=-1){ char curretnt = (char) data; result += curretnt; data = inputStreamReader.read(); }  return  result;}
            catch (Exception e){e.printStackTrace(); 
            return null; }
        }

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


            try {
                JSONObject jsonObject = new JSONObject(s);
                String wetherinfo = jsonObject.getString("weather");
                Log.i("weather",wetherinfo);
                JSONArray array = new JSONArray(wetherinfo);

                String message="";

                for (int i=0; i <array.length();i++){
                    JSONObject jsonPart = array.getJSONObject(i);

                    String main = jsonPart.getString("main");
                    String discrip = jsonPart.getString("description");

                    if (!main.equals("") && !discrip.equals("")){message += main + ":" + discrip + "rn";
                    }
                }

                    if(!message.equals("")) { textView2.setText(message);  }
            } catch (Exception e){e.printStackTrace();}
        }
    }

} 


then i enter the Toast in to this filed now app was crashing

crashing code ….

public class MainActivity extends AppCompatActivity {

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

        editText = findViewById(R.id.editText);
textView2 = findViewById(R.id.textView2);
    }

    public void getweather (View view){
        Downlordtask task = new Downlordtask();
        task.execute("https://openweathermap.org/data/2.5/weather?q="+ editText.getText().toString()+ "&appid=439d4b804bc8187953eb36d2a8c26a02");
        InputMethodManager methodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        methodManager.hideSoftInputFromWindow(editText.getWindowToken(),0);

    }


    public class Downlordtask 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 inputStream = urlConnection.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                int data = inputStreamReader.read();

                while (data !=-1){ char curretnt = (char) data; result += curretnt; data = inputStreamReader.read(); }  return  result;}
            catch (Exception e){e.printStackTrace();
                Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_LONG).show();
            return null; }
        }

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


            try {
                JSONObject jsonObject = new JSONObject(s);
                String wetherinfo = jsonObject.getString("weather");
                Log.i("weather",wetherinfo);
                JSONArray array = new JSONArray(wetherinfo);

                String message="";

                for (int i=0; i <array.length();i++){
                    JSONObject jsonPart = array.getJSONObject(i);

                    String main = jsonPart.getString("main");
                    String discrip = jsonPart.getString("description");

                    if (!main.equals("") && !discrip.equals("")){message += main + ":" + discrip + "rn";
                    }
                }

                    if(!message.equals("")) { textView2.setText(message);  }
            } catch (Exception e){e.printStackTrace();}
        }
    }

} ```

Answer

You cannot make ui calls from a backgroud thread.Use android OS handler So replace

Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_LONG).show();

with

new Handler().post(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_LONG).show();

        }
    });


Source: stackoverflow