所以我在Udemy“完整的Android N开发人员课程”上学习教程,并试图制作关于天气应用程序的第86讲。
我使用这里的APIhttps://openweathermap.org/current#cityid并使用JSON来获取所需的数据。
当我输入正确的城市名称时,应用程序正常工作,但当输入错误或清空时,应用程序会崩溃而不会捕获任何异常。
我不知道它为什么崩溃以及在哪里看。所以我给你我写的所有代码。我试图在这里和那里实现if语句来尝试找到它,但没有任何运气。
我想知道问题在哪里以及如何修复它,以便应用程序不再崩溃。
提前感谢。
public class MainActivity extends AppCompatActivity {
EditText editText;
String city = "";
TextView textView;
public void getWeather (View view) {
try {
city = URLEncoder.encode(editText.getText().toString(), "UTF-8");
if (editText.getText().toString() == "") {
Toast.makeText(MainActivity.this, "Could not find weather", Toast.LENGTH_SHORT).show();
textView.setText("Please enter a city.");
} else {
DownloadTask task = new DownloadTask();
task.execute("http://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=c6ef169a79d84674ef7e1414301eb5c4");
}
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(editText.getWindowToken(), 0);
} catch (UnsupportedEncodingException e1) {
Toast.makeText(MainActivity.this, "UnsupportedEncodingException", Toast.LENGTH_SHORT).show();
}catch (Exception e) {
Toast.makeText(MainActivity.this, "General exception (getWeather)", Toast.LENGTH_SHORT).show();
}
}
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 = null;
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 (MalformedURLException e1) {
Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
} catch (IOException e2) {
Toast.makeText(MainActivity.this, "IOException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "General exception (doInBackground)", Toast.LENGTH_SHORT).show();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = null;
jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
JSONArray jsonArray = new JSONArray(weatherInfo);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonPart = jsonArray.getJSONObject(i);
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if (main != "" && description != "") {
message += main + ": " + description + "\r\n";
}
}
if (message != "") {
textView.setText(message);
} else {
Toast.makeText(MainActivity.this, "Could not find weather", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e1) {
Toast.makeText(MainActivity.this, "JSONException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "General exception (onPostExecute)", Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
}
}
这是因为您试图在AsyncTask的doInbackground(Params…)方法中使用后台线程更改UI:
try {
...
return result;
} catch (MalformedURLException e1) {
Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
} catch (IOException e2) {
Toast.makeText(MainActivity.this, "IOException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "General exception (doInBackground)", Toast.LENGTH_SHORT).show();
}
您不应该在doInbackground(Params…)中调用Toast。在onPostExecute(Result)中执行此操作。
您可以通过忽略错误或在doIn背景中返回特定文本来避免这种情况。类似于这样:
public class DownloadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String result = "";
...
try {
...
return result;
} catch (MalformedURLException e1) {
result= "MalformedURLException";
} catch (IOException e2) {
result= "IOException";
} catch (Exception e) {
// do nothing and returning empty
result= "Exception";
}
return result;
}
@Override
protected void onPostExecute(String result) {
// check if there is an error
String errorMessage = "";
switch(result) {
case "MalformedURLException":
errorMessage = "MalformedURLException";
break;
case ""IOException":
errorMessage = "IOException";
break;
case "Exception":
errorMessage = "Exception";
break;
}
// there is an error, show a message.
if(!errorMessage.isEmpty()) {
Toast.makeText(MainActivity.this, "Could not find weather: " + errorMessage, Toast.LENGTH_SHORT).show();
return; // stop the process.
}
// do something when no error found.
}
}