Re: [問題] null值無法進入if 判斷式
※ 引述《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
10/08 20:16, 1F
→
10/08 20:17, , 2F
10/08 20:17, 2F
→
10/08 20:18, , 3F
10/08 20:18, 3F
→
10/08 20:18, , 4F
10/08 20:18, 4F
→
10/08 20:20, , 5F
10/08 20:20, 5F
→
10/08 20:20, , 6F
10/08 20:20, 6F
→
10/08 20:21, , 7F
10/08 20:21, 7F
推
10/08 20:43, , 8F
10/08 20:43, 8F
推
10/09 22:20, , 9F
10/09 22:20, 9F
→
10/09 22:20, , 10F
10/09 22:20, 10F
推
10/14 21:26, , 11F
10/14 21:26, 11F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):