为什么我的 Toast 不显示

Why my Toast Not Displaying

在下面的代码中,我的toast没有显示出来。但是,我收到错误 "RuntimeException: Can't create handler inside thread that has not called 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());
            }

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

试试这个

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

如果你得到,

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();