【问题标题】:Where should I put toast statement in the try statement after finish()?我应该在finish()之后的try语句中将toast语句放在哪里?
【发布时间】:2014-12-26 14:03:03
【问题描述】:

在 try 语句中执行 toast 语句时遇到错误。这是我的代码。目前以这种方式放置一个toast语句(注释格式)。我可以知道什么是正确的放置方法吗?谢谢。

try {
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs2));
    HttpResponse response = httpclient.execute(httppost);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    final String response1 = httpclient.execute(httppost, responseHandler);
    System.out.println("Response : " + response1); 
    if(response1.contains("Duplicated")){
        finish();
    }
    //{Toast.makeText(getBaseContext(), "You have registered this event before.", Toast.LENGTH_LONG).show();}
    {
        jsonResult = inputStreamToString(
        response.getEntity().getContent()).toString();
    }

    catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

【问题讨论】:

  • 为什么你认为它被推荐?
  • “我面临错误” -- use LogCat 检查与您的错误相关的 Java 堆栈跟踪。此外,将Toast 用于错误条件(“尚未注册此事件”)也不是一个好主意,因为用户可能会分心而看不到Toast。您应该考虑使用其他可以保留一段时间的东西,例如 a crouton
  • 您需要纠正两件事。 1 catch block 应始终写作 immediately after try block2 你应该显示Toast before you write finish()
  • 使用你的activityName.this like---> Toast.makeText(activityName.this, "你之前注册过这个活动。", Toast.LENGTH_LONG).show()
  • 我自己修好了。伙计们,感谢您的帮助。

标签: android try-catch toast


【解决方案1】:

感谢各位的帮助。我自己修好了。

    try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs2));
        HttpResponse response = httpclient.execute(httppost);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        final String response1 = httpclient.execute(httppost, responseHandler);
        System.out.println("Response : " + response1); 
        if(response1.contains("Duplicated")){

            Register.this.runOnUiThread(new Runnable() {

                public void run() {
                    Toast.makeText(Register.this, "You have registered this event before.", Toast.LENGTH_LONG).show();

                }
            });

            finish();
        }
        jsonResult = inputStreamToString(
        response.getEntity().getContent()).toString();
    }

    catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 2011-09-02
    • 2012-03-30
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多