【问题标题】:Why my Toast Not Displaying为什么我的吐司不显示
【发布时间】:2016-07-11 08:36:18
【问题描述】:

在下面的代码中,我的 toast 没有显示。但是,我收到错误消息“RuntimeException:无法在未调用 Looper.prepare() 的线程内创建处理程序”。 我试过Add_City.thisgetApplicationContext

try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();

                JSONObject json_data = new JSONObject(result);
                code=(json_data.getInt("code"));
                System.out.println(code);
                if(code==1)
                {
                    Toast.makeText(Add_City.this, "Inserted Successfully",Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(Add_City.this, "Sorry, City Already Available",Toast.LENGTH_LONG).show();
                }
                Log.i("TAG", "Result Retrieved");
            } catch (Exception e) {
                Log.i("TAG", e.toString());
            }

【问题讨论】:

  • 打开流或解析器json时可能会出现异常
  • 是 System.out.println(code);在您的控制台中打印。如果没有,您的执行永远不会到达那段代码。检查 Log.i("TAG", e.toString());正在登录控制台。如果是这样,你有一个例外。解决异常,你应该得到你的祝酒词。
  • 要在控制台中打印代码,我得到 {"code":"0"} @Tony
  • 是 Log.i("TAG", e.toString());在android显示器上打印一些东西?如果有,那是什么?
  • 使用 e.printStackTrace(); catch 语句中的语句,您将拥有可以帮助您解决问题的整个堆栈跟踪。

标签: android android-toast


【解决方案1】:

如果你得到,

Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

我相信你是在工作线程中调用你的 toast。例如,AsyncTask 的 doInBackground()。 Toast 只能在 UI 线程中调用。

试试这个,

new AsyncTask<Integer, Void, Integer>() {
        @Override
        protected Integer doInBackground(Integer[] params) {
            int code = 1; //your logic here.
            return code;
        }

        @Override
        protected void onPostExecute(Integer code) {
            super.onPostExecute(code);
            if(code==1)
            {
                Toast.makeText(Add_City.this, "Inserted Successfully",Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(Add_City.this, "Sorry, City Already Available",Toast.LENGTH_LONG).show();
            }

        }
    }.execute();

【讨论】:

  • @AndroidBoy,以上回答如您满意请采纳。
【解决方案2】:

我的猜测是,要么您遇到了一些异常,要么显示 toast 的代码没有在主线程上执行。

试试这个

runOnUiThread(new Runnable() {
            public void run() {
            //Your toast here
 Toast.makeText(Add_City.this, "Sorry, City Already Available",Toast.LENGTH_LONG).show();
        }
    });

【讨论】:

  • 我该如何预防?
猜你喜欢
  • 1970-01-01
  • 2017-05-23
  • 1970-01-01
  • 1970-01-01
  • 2016-06-16
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多