【问题标题】:ToastMessages are not shown [duplicate]Toast 消息未显示[重复]
【发布时间】:2026-02-20 11:40:01
【问题描述】:

此代码中的 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 中做任何事情如果你想调试使用日志。记录 catch 块以防出现问题。除此之外,AsynkTasks 已被弃用。

标签: java android


【解决方案1】:

由于这是另一个线程而不是 UI 线程,因此无法进行显示 Toast 等 UI 操作:

你有两个选择:

一个

使用onPostExecute()onProgressUpdate() 来更新UI。

两个

像这样在doInBackground() 中给你的 Toasts 打电话:

runonUiThread(new Runnable(){

public void run(){

    Toast.makeText(MainActivity.this, "THIS IS NOT SHOWN", Toast.LENGTH_SHORT).show();

}

});

【讨论】:

    【解决方案2】:

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

    只需要在 onPostExecute 方法中显示即可。

    否则使用日志。

    希望对您有所帮助!

    【讨论】: