java - ToastMessages 不显示
问题描述
此代码中的 ToastMessage 均未显示。
private final class FetchUrlLINKTOINCREASECOIN extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
try {
Toast.makeText(MainActivity.this, "THIS IS NOT SHOWN", Toast.LENGTH_SHORT).show();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://example.com/xx.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userid", f12139v0));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
Pattern pattern = Pattern.compile(",\"postid\":\"(.*?)\",\"");
Matcher matcher = pattern.matcher(responseString);
if (matcher.find())
{
String req_id = matcher.group(1);
Toast.makeText(MainActivity.this, req_id, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "n", Toast.LENGTH_SHORT).show();
}
Toast.makeText(MainActivity.this, responseString, Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
} catch (Exception e) {
}
return "executed";
}
}
但是网络请求很好。这就是我运行此功能的方式:
Toast.makeText(MainActivity.this, "This is fine", Toast.LENGTH_SHORT).show();
new FetchUrlLINKTOINCREASECOIN().execute();
如您所见,我在运行该功能之前放了一条祝酒词,应用程序显示了这一点。
解决方案
doInBackground() 将在工作线程中运行。您无法控制 UI 线程来执行 toast 消息。
您只需要在 onPostExecute 方法中显示。
否则使用日志。
希望对你有帮助!
推荐阅读
- opencart - 如何在下拉菜单 Opencart 中使所有子类别可扩展?
- amazon-web-services - 为 ELB 和 EC2 设置 HTTPS
- javascript - 使用 JS 插件对表进行排序会导致错误
- docker - 是否可以将其他 PTY 连接到 docker 容器?
- reactjs - 作为 npm 包的子应用程序不会重新呈现
- xamarin.forms - 当前上下文中不存在名称“XForms”
- android - 如何将 PMD 更新到较新版本?
- javascript - 我无法通过 socket.io 获取实时数据到客户端并将其显示在页面上
- marklogic - MarkLogic 光学 API:按性能排序
- html - 为什么在页脚部分顶部给出的边框比预期的要远得多?