首页 > 解决方案 > 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();

如您所见,我在运行该功能之前放了一条祝酒词,应用程序显示了这一点。

标签: javaandroid

解决方案


doInBackground() 将在工作线程中运行。您无法控制 UI 线程来执行 toast 消息。

您只需要在 onPostExecute 方法中显示。

否则使用日志。

希望对你有帮助!


推荐阅读