作者qrtt1 (null)
看板AndroidDev
標題Re: [問題] null值無法進入if 判斷式
時間Sat Oct 8 19:50:35 2011
※ 引述《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
→ lo33:恩恩 我有初始Strinr result = null; 10/08 20:16
→ lo33:我log出來的result結果 只有一堆json字串和null兩種而已 10/08 20:17
→ lo33:我是想寫若是null就會提醒使用者這樣 但log出來是null 10/08 20:18
→ lo33:卻跑不進if理@@ 10/08 20:18
→ lo33:但我照大大的方式不用if判斷了 直接在catch例外理提醒使用者 10/08 20:20
→ lo33:有達到我想要的效果了 感謝大大^^ 10/08 20:20
→ lo33:雖然我還是對if (result==null) 無法判斷感到疑惑XDD 10/08 20:21
推 ericinttu:變數等於null 跟 變數內容等於null, 是有差別的. 10/08 20:43
推 cavitylapper:也許可以試試看.equals() 10/09 22:20
→ cavitylapper:抱歉 好像你原本就是這樣寫orz 10/09 22:20
推 milochen:上次遇到類似的問題,是程式在執行過程中,被 GC掉 . 10/14 21:26