2016-07-11 142 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