Re: [問題] null值無法進入if 判斷式

看板AndroidDev作者 (null)時間12年前 (2011/10/08 19:50), 編輯推噓3(308)
留言11則, 4人參與, 最新討論串2/2 (看更多)
※ 引述《lo33 (lo33)》之銘言: : 目前在寫一個程式 : 是先抓到mysql的再轉換成json字串 : 但我想寫個判斷式若 值result是null的話 會出現警語 : 程式是這樣: 不知道你的 result 一開始定義成什麼樣子 假設它是 local variable 那就會有個初值。 Strinr result = null; /* 假設你設為 null */ : try { : HttpClient httpclient = new DefaultHttpClient(); : HttpPost httppost = new HttpPost(link); : httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); : HttpResponse response = httpclient.execute(httppost); : HttpEntity entity = response.getEntity(); : is = entity.getContent(); : } catch (Exception e) { : Log.e("1", "Error in http connection " + e.toString()); : } : // convert response to string 其實我不太懂為什麼上下要分開 try catch 上或下掛了,就肯定沒有 json 能玩了。 : try { : BufferedReader reader = new BufferedReader(new InputStreamReade : is, "UTF-8"), 8); : StringBuilder sb = new StringBuilder(); : String line = null; : while ((line = reader.readLine()) != null) { : sb.append(line + "\n"); : } : is.close(); : result = sb.toString(); 假設有到這行,不管有沒有讀到東西。 result 至少是空字串,不會是 null 現在的情況跟你描述的都合不起來,實在很詭異。 : } catch (Exception e) { : Log.e("2", "Error converting result " + e.toString()); : } : // parse json data : // Log.e("result", result); : if (result==null) { : Toast.makeText(ScheduleActivity.this, R.string.noresult, : Toast.LENGTH_LONG).show(); : } : else { : /////////////////////// : } : 我重Log.e看可以看到我所抓的result 的值是null : 但是程式都會進入else裡面而不是在if那邊出現警語 : 我也試過 : if (result.equals(null)) { : } : 的寫法還是不行@@ : 還請高手指點!!! 也許換個方式來想 try { 1. 取得 http response 並轉成字串 2. 將字串轉成 json 3. 驗證 json 內容是否正確 3.1 若不正確也能丟出例外 catch(任何例外) { 提醒使用者 } 這樣寫應該比較簡單,反正程式在跑的情況, 也沒有 recovery exception 的能力,catch 那麼只是徒勞罷了。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.231.49.61

10/08 20:16, , 1F
恩恩 我有初始Strinr result = null;
10/08 20:16, 1F

10/08 20:17, , 2F
我log出來的result結果 只有一堆json字串和null兩種而已
10/08 20:17, 2F

10/08 20:18, , 3F
我是想寫若是null就會提醒使用者這樣 但log出來是null
10/08 20:18, 3F

10/08 20:18, , 4F
卻跑不進if理@@
10/08 20:18, 4F

10/08 20:20, , 5F
但我照大大的方式不用if判斷了 直接在catch例外理提醒使用者
10/08 20:20, 5F

10/08 20:20, , 6F
有達到我想要的效果了 感謝大大^^
10/08 20:20, 6F

10/08 20:21, , 7F
雖然我還是對if (result==null) 無法判斷感到疑惑XDD
10/08 20:21, 7F

10/08 20:43, , 8F
變數等於null 跟 變數內容等於null, 是有差別的.
10/08 20:43, 8F

10/09 22:20, , 9F
也許可以試試看.equals()
10/09 22:20, 9F

10/09 22:20, , 10F
抱歉 好像你原本就是這樣寫orz
10/09 22:20, 10F

10/14 21:26, , 11F
上次遇到類似的問題,是程式在執行過程中,被 GC掉 .
10/14 21:26, 11F
文章代碼(AID): #1Ea3aE_C (AndroidDev)
文章代碼(AID): #1Ea3aE_C (AndroidDev)