以异步方式显示toast



因此,如果";编辑文本"等于特定链接。否则,代码将一直运行到结果。

这就是我试图做的(它没有检测到链接(:

if (urls[0].equals ("http://api.openweathermap.org/data/2.5/weather?q=null&appid=8e19904c6a1db15924eef5084a978de7"))
{
Log.e("Test","Error!");
}

我的主要代码,如果你需要代码中的任何其他内容,只要告诉我,我就会上传:

公共类DownloadTask扩展AsyncTask<字符串,无效,字符串>{

@Override
protected String doInBackground(final String... urls) {
Log.e("URL", "Loading url = " + urls[0]);

StringBuilder result = new StringBuilder();
if (urls[0].equals ("http://api.openweathermap.org/data/2.5/weather?q=null&appid=8e19904c6a1db15924eef5084a978de7"))
{
Log.e("Test","DSADSADASDASDAS");
}
URL url;
HttpURLConnection urlConnection = null;
try{
url = new URL(urls[0]);
urlConnection =  (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line;

while ((line = bufferedReader.readLine()) != null) {
result.append(line).append("n");
}
return result.toString();
} catch (MalformedURLException e) {
result.append("Error: MalformedURLException");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}

@SuppressLint("SetTextI18n")
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String weatherInfo = jsonObject.getString("weather");
Log.e("JSON data",""+weatherInfo);
Toast.makeText(MainActivity.this, mCityName +" has been loaded", Toast.LENGTH_SHORT).show();
JSONArray jArray = new JSONArray(weatherInfo);
for(int i = 0; 0 < jArray.length(); i++){

JSONObject partJson = jArray.getJSONObject(i);
mMain.setText("The Weather in " + mCityName + " is: " + partJson.getString("main"));
mDescription.setText("And " + partJson.getString("description"));
mMain.setVisibility(View.VISIBLE);
mDescription.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
}

}

}

谢谢!

要从后台线程显示Toast,需要在runOnUIThread内部调用它,如下所示:

runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(this, "URL is the same", Toast.LENGTH_SHORT).show();
}
});

这是假设您的AsincTask在一个活动类中。

runOnUIThreadActivity类的一个方法,您需要一个Context来显示Toast

如果AsyncTask在单独的类中,则需要提供Activity作为参数,或者使用IntentActivity通信。

最新更新