2016-07-11 148 views
-1

在下面的代码中,我的吐司没有显示。但是,我得到错误,“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()); 
      } 
+1

可能有一个例外,当你打开一个流或JSON解析器是 – phongvan

+1

的System.out.println(代码);打印在您的控制台中。如果没有,你的执行永远不会达到那段代码。检查Log.i(“TAG”,e.toString());正在登录控制台。如果是这样,你有一个例外。解决例外,你应该得到你的敬酒。 – Tony

+0

我该如何解决? – AndroidBoy

回答

0

如果您收到,

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

我相信你调用一个工作线程里面你的面包。例如,AsyncTask的doInBackground()。吐司应该只在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(); 
+0

是正确的,那么这里是我得到的结果使 – AndroidBoy

+0

@AndroidBoy,请接受以上的答案,如果你觉得满意。 – Tony

0

我的猜测是不是你得到了一些异常,或者用于显示主线程在吐司没有被执行的代码。

尝试使用此

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

好吧,我可以调试我的应用程序得到这个结果{“代码”:“0”} – AndroidBoy

+0

那么你的代码不在主线程上执行 – Nitesh

+0

我该如何防止? – AndroidBoy