作者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
1F:→ lo33:恩恩 我有初始Strinr result = null; 10/08 20:16
2F:→ lo33:我log出来的result结果 只有一堆json字串和null两种而已 10/08 20:17
3F:→ lo33:我是想写若是null就会提醒使用者这样 但log出来是null 10/08 20:18
4F:→ lo33:却跑不进if理@@ 10/08 20:18
5F:→ lo33:但我照大大的方式不用if判断了 直接在catch例外理提醒使用者 10/08 20:20
6F:→ lo33:有达到我想要的效果了 感谢大大^^ 10/08 20:20
7F:→ lo33:虽然我还是对if (result==null) 无法判断感到疑惑XDD 10/08 20:21
8F:推 ericinttu:变数等於null 跟 变数内容等於null, 是有差别的. 10/08 20:43
9F:推 cavitylapper:也许可以试试看.equals() 10/09 22:20
10F:→ cavitylapper:抱歉 好像你原本就是这样写orz 10/09 22:20
11F:推 milochen:上次遇到类似的问题,是程式在执行过程中,被 GC掉 . 10/14 21:26