簡體   English   中英

如何在 android 天氣應用程序 API 調用中更改城市?

[英]How to change city in an android weather app API call?

目標是讓用戶在應用程序的 editText 中輸入一個城市,它將更改 api 調用並根據用戶輸入獲取正確的城市。

我在布局文件中添加了一個edittext,然后在mainactivity中我像這樣保存了它:

String CITY_COUNTRY = edittextname.getEditableText().toString();

然后我將 CITY_COUNTRY 添加到以下行:

String response = HttpRequest.executeHttpGetRequest("https://api.openweathermap.org/data/2.5/weather?q=" + CITY_COUNTRY + "&units=metric&appid=" + API_KEY);

該應用程序剛剛崩潰,有什么想法嗎?

    Process: com.example.weatherapptwo, PID: 10461
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.weatherapptwo/com.example.weatherapptwo.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2886)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3091)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:280)
        at android.app.ActivityThread.main(ActivityThread.java:6744)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
        at android.app.Activity.findViewById(Activity.java:2656)
        at com.example.weatherapptwo.MainActivity.<init>(MainActivity.java:31)
        at java.lang.Class.newInstance(Native Method)
        at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
        at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1216)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2874)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3091) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:280) 
        at android.app.ActivityThread.main(ActivityThread.java:6744) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends Activity {

    TextView cityText, weatherUpdateText, weatherTypeText, temperatureText, minTempText, maxTempText, sunriseText,
            sunsetText, windSpeedText, pressureText, humidityPrcntText, timezoneText;
    EditText edt;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        cityText = findViewById(R.id.address);
        weatherUpdateText = findViewById(R.id.weatherUpdateAt);
        weatherTypeText = findViewById(R.id.weatherType);
        temperatureText = findViewById(R.id.temperature);
        minTempText = findViewById(R.id.minTemp);
        maxTempText = findViewById(R.id.maxTemp);
        sunriseText = findViewById(R.id.sunrise);
        sunsetText = findViewById(R.id.sunset);
        windSpeedText = findViewById(R.id.windSpeed);
        pressureText = findViewById(R.id.pressure);
        humidityPrcntText = findViewById(R.id.humidity);
        timezoneText = findViewById(R.id.tz);
        edt = findViewById(R.id.cityEdtText);

        new weatherTask().execute();
    }


    String CITY_COUNTRY = edt.getEditableText().toString();
    String API_KEY = "blabla";

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

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            findViewById(R.id.loader).setVisibility(View.VISIBLE);
            findViewById(R.id.mainContainer).setVisibility(View.GONE);
            findViewById(R.id.exceptionText).setVisibility(View.GONE);
        }

        protected String doInBackground(String... args) {

            String response = HttpGetRequest.executeHttpGetRequest("https://api.openweathermap.org/data/2.5/weather?q=" + CITY_COUNTRY + "&units=metric&appid=" + API_KEY);
            return response;

        }


        @Override
        protected void onPostExecute(String result) {

            try {
                JSONObject jsonObj = new JSONObject(result);
                JSONObject main = jsonObj.getJSONObject("main");
                JSONObject sys = jsonObj.getJSONObject("sys");
                JSONObject wind = jsonObj.getJSONObject("wind");
                JSONObject weather = jsonObj.getJSONArray("weather").getJSONObject(0);

                Long updatedAt = jsonObj.getLong("dt");
                Long tz = jsonObj.getLong("timezone");
                String updatedAtText = "Weather updated at: " + new SimpleDateFormat("dd/MM/yyy hh:mm a", Locale.ENGLISH)
                        .format(new Date(updatedAt * 1000));
                String tzText = String.valueOf(tz);
                String temp = main.getString("temp") + "°C";
                String pressure = main.getString("pressure") + " hpa";
                String humidity = main.getString("humidity") + " %";
                String tempMin = "Min Temp: " + main.getString("temp_min") + "°C";
                String tempMax = "Max Temp: " + main.getString("temp_max") + "°C";
                String windSpeed = wind.getString("speed") + " m/s";
                String weatherTypeDescription = weather.getString("description");
                String cityCountryAddress = jsonObj.getString("name") + ", " + sys.getString("country");
                Long sunrise = sys.getLong("sunrise");
                Long sunset = sys.getLong("sunset");

                cityText.setText(cityCountryAddress);
                weatherUpdateText.setText(updatedAtText);
                weatherTypeText.setText(weatherTypeDescription.toUpperCase());
                temperatureText.setText(temp);
                minTempText.setText(tempMin);
                maxTempText.setText(tempMax);
                sunriseText.setText(new SimpleDateFormat("hh:mm a", Locale.ENGLISH).format(new Date(sunrise * 1000)));
                sunsetText.setText(new SimpleDateFormat("hh:mm a", Locale.ENGLISH).format(new Date(sunset * 1000)));
                windSpeedText.setText(windSpeed);
                pressureText.setText(pressure);
                humidityPrcntText.setText(humidity);
                timezoneText.setText(tzText);

                findViewById(R.id.loader).setVisibility(View.GONE);
                findViewById(R.id.mainContainer).setVisibility(View.VISIBLE);
                }
                catch (JSONException e) {
                    findViewById(R.id.loader).setVisibility(View.GONE);
                    findViewById(R.id.exceptionText).setVisibility(View.VISIBLE);
            }
        }
    }
}```

您正在嘗試在創建活動之前在EditText上調用getEditableText() String CITY_COUNTRY = edt.getEditableText().toString(); 在調用onCreate()之前執行。

所以刪除這一行:

String CITY_COUNTRY = edt.getEditableText().toString();

並把它里面doInBackground()weatherTask

protected String doInBackground(String... args) {
    String CITY_COUNTRY = edt.getEditableText().toString(); // Move it here
    String response = HttpGetRequest.executeHttpGetRequest("https://api.openweathermap.org/data/2.5/weather?q=" + CITY_COUNTRY + "&units=metric&appid=" + API_KEY);
    return response;
}

希望能幫助到你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM