目标是让用户在应用程序的 editText 中输入一个城市,它将更改 api 调用并根据用户输入获取正确的城市。
我在布局文件中添加了一个编辑文本,然后在主活动中我像这样保存它:
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();
并将其放在weatherTask
doInBackground()
内:
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;
}
希望对你有帮助