2013年9月12日

试了N多方法,貌似在终端执行命令:
export LC_ALL=zh_CN.GB2312;export LANG=zh_CN.GB2312是最有效的。
=======================
1.不管用那种ssh客户端,字体设定一定要设为可以显示中文的字体。

2.远程的locale一定要设置为LANG=zh_CN.UTF-8

========================================
修改/etc/profile

增加这一行
export LC_ALL=zh_CN.GBK

========================================

SSH显示中文乱码问题
(1) 打开/etc/sysconfig/i18n
设置为:
LANG="zh_CN.GB2312"
LANGUAGE="zh_CN.GB18030:zh_CN.GB2312:zh_CN"
SUPPORTED="zh_CN.GB18030:zh_CN.GB2312:zh_CN.UTF-8:zh:en_US.UTF-8:en_US:en:ja_JP.UTF-8:ja_JP:ja"
SYSFONT="lat0-sun16"
SYSFONTACM="8859-15"

其中LANG="zh_CN.GB2312" 是必须的(如果你不想让中文乱码的话!!!)
其它的可以按照自已的需求来改变。
(2) 打开smb.conf
添加:

   display charset=cp936
    unix charset=cp936
    doc  charset=cp936
========================
posted @ 2013-09-12 17:23 姚先进 阅读(230) | 评论 (0)编辑 收藏

2013年9月11日

 与association一样,collection元素也有两种形式,现介绍如下:
一、嵌套的resultMap

      实际上以前的示例使用的就是这种方法,今天介绍它的另一种写法。还是以教师映射为例,修改映射文件TeacherMapper.xml如下(点击此处进入嵌套resultMap形式的示例源码下载页面。注:本示例代码是在修改本系列的上篇博文示例代码的基础上完成的,用到了MapperScannerConfigurer和注解等知识。对这些知识不熟悉的读者,可参考上篇博文:http://legend2011.blog.51cto.com/3018495/980150):

  1. <?xmlversion="1.0"encoding="utf8"?>

  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

  3. <!--与以前一样,namespace的值是对应的映射器接口的完整名称-->

  4. <mappernamespace="com.abc.mapper.TeacherMapper">

  5.          <!--TeacherMapper接口中getById方法对应的SQL语句。  

  6.          查询教师及其指导的学生的信息。由于教师、学生都有  

  7.          id、name、gender等属性,因此给教师的字段都起了别名-->

  8. <selectid="getById"parameterType="int"resultMap="supervisorResultMap">

  9.           select t.id t_id, t.name t_name, t.gender t_gender,  

  10.           t.research_area t_research_area, t.title t_title,  

  11.           s.id,s.name, s.gender,s.major,s.grade  

  12.           from teacher t,student s where t.id=#{id}  

  13.           and s.supervisor_id = t.id  

  14. </select>

  15. <!--教师实体映射-->

  16. <resultMapid="supervisorResultMap"type="Teacher">

  17. <idproperty="id"column="t_id"/>

  18. <resultproperty="name"column="t_name"/>

  19. <resultproperty="gender"column="t_gender"/>

  20. <resultproperty="researchArea"column="t_research_area"/>

  21. <resultproperty="title"column="t_title"/>

  22.             <!--需要注意的是,上面的select语句中学生的字段名/别名应与  

  23.             下面的column属性一致。ofType指collection包含的元素的类型,  

  24.             此属性不可少-->

  25. <collectionproperty="supStudents"ofType="Student">

  26. <idproperty="id"column="id"/>

  27. <resultproperty="name"column="name"/>

  28. <resultproperty="gender"column="gender"/>

  29. <resultproperty="major"column="major"/>

  30. <resultproperty="grade"column="grade"/>

  31.                <!--映射学生的指导教师属性,用到了  

  32.                supervisorResultMap本身-->

  33. <associationproperty="supervisor"

  34. resultMap="supervisorResultMap"/>

  35. </collection>

  36. </resultMap>

  37. </mapper>

      运行程序结果如下: 

       与以前的写法相比,这种写法的缺点是学生实体映射被嵌入到教师实体映射中,因此学生实体映射不能被重用。

二、嵌套的select语句

      这种方式是使用一条单独的select语句来加载关联的实体(在本例中就是学生实体),然后在collection元素中引用此select语句(注:此方法会产生N+1问题,关于这个问题可参考本系列博客中的“MyBatis中的N+1问题”)。首先修改TeacherMapper.xml如下(点击此处进入嵌套select语句形式示例源码下载页面):

  1. <?xmlversion="1.0"encoding="utf8"?>

  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

  3. <!--与以前一样,namespace的值是对应的映射器接口的完整名称-->

  4. <mappernamespace="com.abc.mapper.TeacherMapper">

  5.          <!--TeacherMapper接口中getById方法对应的SQL语句。  

  6.          查询教师的信息。-->

  7. <selectid="getById"parameterType="int"resultMap="supervisorResultMap">

  8.           select * from teacher where id=#{id}  

  9. </select>

  10. <!--教师实体映射-->

  11. <resultMapid="supervisorResultMap"type="Teacher">

  12. <idproperty="id"column="id"/>

  13. <resultproperty="name"column="name"/>

  14. <resultproperty="gender"column="gender"/>

  15. <resultproperty="researchArea"column="research_area"/>

  16. <resultproperty="title"column="title"/>

  17.             <!--ofType指collection包含的元素的类型,此属性不可少。  

  18.             column属性指把上述的getById的select语句中的教师id列的值作为参数  

  19.             传递给将要引用到的下述的getStudents的select语句,此属性不可少。  

  20.             引用的形式为:命名空间.select语句id-->

  21. <collectionproperty="supStudents"column="id"ofType="Student"

  22. select="com.abc.mapper.StudentMapper.getStudents"/>

  23. </resultMap>

  24. </mapper>

       在这里把根据指导教师id查询学生信息的SQL语句写在StudentMapper.xml中,并引用其中的学生实体映射studentResultMap。修改StudentMapper.xml如下:

  1. <?xmlversion="1.0"encoding="utf8"?>

  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

  3. <mappernamespace="com.abc.mapper.StudentMapper">

  4. <resultMapid="studentResultMap"type="Student">

  5. <idproperty="id"column="id"/>

  6. <resultproperty="name"column="name"/>

  7. <resultproperty="gender"column="gender"/>

  8. <resultproperty="major"column="major"/>

  9. <resultproperty="grade"column="grade"/>

  10.           <!--在这里引用supervisorResultMap和getById,亦采用  

  11.           命名空间名.相关元素id的形式。column="supervisor_id"

  12.           属性不可少-->

  13. <associationproperty="supervisor"

  14. resultMap="com.abc.mapper.TeacherMapper.supervisorResultMap"

  15. select="com.abc.mapper.TeacherMapper.getById"column="supervisor_id"/>

  16. </resultMap>

  17. <!--根据指导教师id查询学生信息-->

  18. <selectid="getStudents"parameterType="int"

  19. resultMap="studentResultMap">

  20.             select * from student where supervisor_id = #{id}  

  21. </select>

  22. </mapper>

      执行结果如下:

posted @ 2013-09-11 13:44 姚先进 阅读(395) | 评论 (0)编辑 收藏

2013年9月10日

最近在工作中遇到了一个需求

在执行数据库操作时需要先判断指定的数据是否存在,如果不存在则插入,存在则更新

最开始使用的是三条SQL语句:

  1. SELECT bl_count,bl_src,bl_date,bl_topic FROM temp_table WHERE bl_topic=? AND bl_src=? AND bl_date=?;  
  2.   
  3. UPDATE temp_table SET bl_count=? WHERE bl_topic=? AND bl_src=? AND bl_date=?;  
  4.   
  5. INSERT INTO temp_table (bl_src,bl_date,bl_count,bl_topic) values(?,?,?,?)  
逻辑是:
  1. if(SELECT!= null){  
  2.     UPDATE  
  3. }else{  
  4.     INSERT  
  5. }  

后来leader提示还有新的方法,一条SQL语句就能搞定:

  1. INSERT INTO temp_table(bl_src,bl_date,bl_count,bl_topic) VALUES(?,?,?,?) ON DUPLICATE KEY UPDATE bl_count=bl_count+?;  

但是有个前提就是:什么时候会执行update语句?在SQL语句中并没有条件。

后来在网上看到的,执行update语句的条件是insert语句的执行会造成唯一键的重复。

所以,在创建表的时候还要加上唯一键的约束

  1. ALTER TABLE temp_table ADD CONSTRAINT c_topic_src_date UNIQUE(bl_topic,bl_src,bl_date);  

这样就能达到目的。

posted @ 2013-09-10 18:56 姚先进 阅读(895) | 评论 (0)编辑 收藏

2013年7月29日

JSP:include的flush属性的作用

分类: 其他 2012-04-06 10:51 2572人阅读 评论(2) 收藏 举报
includejspservlet服务器浏览器
JSPinclude 另一个文件时有个很偏的属性,叫flush,默认为 false。

在同一个 JSP 中,如果不断 include 自己(源文件),在逻辑上会形成死循环。若默认情况下,服务器会等待该文件被读到底端,然后才输出到客户端,并且销毁该次访问的 request 和 response。而当把flush 属性赋为真值时,在缓存累积了一定数据时,服务器会先提供一部分数据给浏览器,并等待后续内容。

由此可以得出结论,在简单页面中,该属性不纳入考虑,而在页面包含大量数据时,为缩短客户端延迟,可将一部分内容先行输出。该属性在 Servlet 中也有对应的应用。
posted @ 2013-07-29 20:54 姚先进 阅读(466) | 评论 (1)编辑 收藏

2013年5月17日

 大家都在为项目开发成功而喜悦,但可不知成功的路上是会经常出错的,下面是我碰到的一些错误集合!

【错误信息】

01-16 17:16:18.945: I/magh(979): org.apache.http.conn.HttpHostConnectException: Connection to http://127.0.0.1:8080 refused

在android模拟器连接本机访问web时报这错,把127.0.0.1改成localhost也是一样的

原因:
 在向本机发送HTTP请求时,有一点必须注意,就是在android 虚拟机中,127.0.0.1为android 虚拟机的IP地址,如果要访问本机,IP地址应该改为10.0.2.2。否则肯定会导致访问不成功!
==========================================================================
【错误信息】
[2011-01-19 16:39:10 - ApiDemos] WARNING: Application does not specify an API level requirement!
[2011-01-19 16:39:10 - ApiDemos] Device API version is 8 (Android 2.2)
原因:
不影响正常运行。在AndroidManifest.xml文件中没有加API的版本号,在<manifest> </manifest> 之间加<uses-sdk android:minSdkVersion="3"></uses-sdk>
[2011-01-19 16:55:04 - ApiDemos] Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE
[2011-01-19 16:55:04 - ApiDemos] Please check logcat output for more details.
[2011-01-19 16:55:05 - ApiDemos] Launch canceled!
该设备没有足够的存储空间来安装应用程序,


【错误信息】
[2011-02-18 11:46:53] Failed to push selection: Is a directory
原因:
原先目录已经有pkg_3.apk的文件夹,再copy一个pkg_3.apk安装文件时出现问题,解决办法,先删除掉pkg_3.apk的文件夹
[2011-03-04 09:25:12 - ActivityMain]: Dx
UNEXPECTED TOP-LEVEL EXCEPTION:
java.lang.IllegalArgumentException: already added: Lorg1/apache/commons/codec/net/RFC1522Codec;
[2011-03-04 09:25:12 - ActivityMain]: Dx at com.android.dx.dex.file.ClassDefsSection.add(ClassDefsSection.java:123)
[2011-03-04 09:25:12 - ActivityMain]: Dx at com.android.dx.dex.file.DexFile.add(DexFile.java:143)
.....
[2011-03-04 09:25:12 - ActivityMain]: Dx1 error; aborting
[2011-03-04 09:25:12 - ActivityMain] Conversion to Dalvik format failed with error 1
原因:


【错误信息】
启动Eclipse时出现:
this android sdk requires android developer toolkit version 10.0.0 or above.
current version is 8.0.1.v201012062107-82219.
please update adt to the latest version

原因:
Eclipse的android开发插件版本过低,应该下载ADT-10.0.0,并且
1. 启动 Eclipse, 然后进入 Help > Install New Software.
2. 在 Available Software 对话框里,点击 Add....


【错误信息】
[2011-03-09 15:21:34 - Info] Failed to install Info.apk on device '?': Unable to open sync connection!
[2011-03-09 15:21:34 - Info] java.io.IOException: Unable to open sync connection!
[2011-03-09 15:21:34 - Info] Launch canceled!
原因:
关闭模拟器和eclipse,执行adb kill-server命令,然后重试一下


【错误信息】
调用Webservice时出现
java.net.SocketException: Permission denied (maybe missing INTERNET permission)
原因:
需要访问到网络,所以,在AndroidManifest.xml中,需要进行如下配置:
<uses-permission android:name="android.permission.INTERNET" />


【错误信息】
org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope (position:START_TAG <{http://schemas.xmlsoap.org/wsdl/}wsdl:definitions targetNamespace='http://bo.webservice.nqbx.nq.com'>@2:603 injava.io.InputStreamReader@44a3a7b0)
原因有可能是以下2个之一:
1)Webservice服务器的Soap版本为1.0,所以客户端指定
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
VER11改为VER10
2)String serviceUrl = "http://200.200.200.11:10000/nqbx/service/InqBxWebService?wsdl";
Url指的是你的webservice的地址.一般都是以***.wsdl或者***.?wsdl结束的...但是.需要注意的是..要去掉后面的.wsdl或者.?wsdl


【错误信息】
在新的线程中 public class HttpThread extends Thread {...}
增加一个弹出窗体:
new AlertDialog.Builder(this).setTitle("数据加载失败").setMessage("请检查网络连接情况")           .setPositiveButton("OK", new DialogInterface.OnClickListener(){            public void onClick(DialogInterface dialoginterface, int i)            {            }            }).show();     
  原因及解决办法:
//不能在线程中操作UI界面
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

修改后:
new AlertDialog.Builder(com.nantsing.infoquery.chuanbo_detail.this).setTitle(" 数据加载失败").setMessage("请检查网络连接情况")           .setPositiveButton("OK", new DialogInterface.OnClickListener(){            public void onClick(DialogInterface dialoginterface, int i)            {            }


【错误信息】
The constructor AlertDialog.Builder(chuanbo_detail.HttpThread) is undefined
原因及解决办法:
在UI主线程之外是无法对UI组件进行控制的。因为你必须在新线程任务完成之后利用各种方法先UI主线程发送消息通知任务完成从而来显示各种提示消息。
线程间通信方法有多种,常用的是用handler来传递消息。
如下:
线程中构造消息:
//构造消息Message message = handle.obtainMessage();Bundle b = new Bundle();b.putString("tag", "1");message.setData(b);handle.sendMessage(message);
另外自定义消息:
        /** * 捕获消息队列 fubin.pan 2011-04-02 */Handler handler = new Handler() {public void handleMessage(Message m) {if (!m.getData().getString("tag").equals("1")){                            ...}else{new AlertDialog.Builder(chuanbo_detail.this).setTitle("数据加载失败").setMessage(" 请检查网络连接情况!")                .setPositiveButton("OK", new DialogInterface.OnClickListener(){                        public void onClick(DialogInterface dialoginterface, int i)                        {                        }          }).show();}}};


【错误信息】
android低版本工程(如1.5)放到高版本环境中(如2.2)可能会上述错误,解决方法如下:
1。 如果不修改android sdk版本,则使用project clean 命令作用于某工程即可。
       (该处理方式只是在高版本中兼容了低版本工程,未真正意义上的升级)
2。 如果修改android sdk版本,则需要以下几个步骤:
       1)修改SDK
             选择工程,build path --> configure build path ---> library 删除引用的低版本SDK,
             然后add External JARs,选择高版本SDK,OK,保存
        2)修改classpath文件
             该文件可能存在该项: <classpathentry kind="lib"   path ="你所指定的高版本的地址"
             把她修改成<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK" />
        3) 修改AndroidManifest.xml
             在AndroidManifest.xml文件中,application标签后添加<uses-sdk android:minSdkVersion="3"></uses-sdk>
        4) 修改default.properties(很重要)
              该文件最后一行(前面没用#的)target=android-3 该成target=android-8,保存。
        再看看你的工程和新建的android 2.2的工程结构就一样了。


【错误信息】
在线程debug(运行没有问题)时调用Webservice时出现:
'JDI thread evaluations' has encountered a problem
Exception processing async thread queue


Exception processing async thread queue
JDI thread evaluations


原因及解决办法:
与运行无关的错误,关掉'expressions'视图就可以了


【错误信息】
打开开源项目JavaEye Android client时出错
http://javaeye-android-client.googlecode.com/svn/trunk/
这是 JavaEye 网站基于 Android 平台的客户端软件,可用以阅读动静、帖子、闲谈, 收躲, RSS 等功用。

[2011-04-19 10:55:11 - JavaEye Android Client] Project has no default.properties file! Edit the project properties to set one.


原因及解决办法:
遇到这种情况,可以创建一个default.properties文件,如果创建之后还是有错误,那么delete这个project,重新import。
编辑default.properties 之后,一般会自动创建 gen 目录, 如果没有,也可尝试手工创建。

✿Adroid Adapter ADB Interface 严重错误
今天在配置完Eclipse和Android SDK开发环境之后,想用华为C8500手机通过USB连接电脑,并在手机上去调试,但莫名其妙出现Adroid Adapter ADB Interface 安装严重错误,在豌豆荚手机精灵安装驱动的时候,也出现这个错误,后面也莫名奇妙的多装几次就好了,还没找到什么原因。


【错误信息】
用手机调试运行出现:
ActivityManager: Warning: Activity not started, its current task has been brought to the front
原因及解决办法:
该手机已经启动了相同名字的应用,关闭之后再试!


【错误信息】
最近(2012-04-05)在打开SDK Manager.exe,更新SDK时,会出现如下错误:

Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml,
reason: Connection timed out: connect
原因及解决办法:
dl-ssl.google.com在大陆封掉了
解决方法就是修改C:\Windows\System32\drivers\etc\hosts文件。添加一行:
74.125.237.1       dl-ssl.google.com
保存,重新启动SDK Manager.exe


【错误信息】
[2012-04-08 17:42:24 - JavaEye Android Client] ------------------------------
[2012-04-08 17:42:24 - JavaEye Android Client] Android Launch!
[2012-04-08 17:42:24 - JavaEye Android Client] The connection to adb is down, and a severe error has occured.
[2012-04-08 17:42:24 - JavaEye Android Client] You must restart adb and Eclipse.
[2012-04-08 17:42:24 - JavaEye Android Client] Please ensure that adb is correctly located at 'C:\android\android-sdk-windows\platform-tools\adb.exe' and can be executed.
原因及解决办法:
查看任务管理器,关闭所有adb.exe
重启eclipse即可


【错误信息】
更新SDK时错误信息:
Site Authentication
Please login to the following ......

原因及解决办法:
Cancel跳过提示


【错误信息】
打开Eclipse 提示安装ADT 17

原因及解决办法:
最新的Android SDK只能安装ADT 17.0.0
可用的下载地址:http://download.csdn.net/detail/merrido/4169460,
这里可不能用常规方法安装这个 ADT 17.0.0.zip 文件, 首先得解压这个文件,将里面的文件夹覆盖掉Eclipse安装目录下的文件夹。
然后再用Help-> install new software->Add -> Name: ADT   Archive:选择ADT 17.0.0.zip


【错误信息】
安装ADT 17.0.0时,提示:
Your original request has been modified.
  "Android DDMS" is already installed, so an update will be performed instead.
  "Android Development Tools" is already installed, so an update will be performed instead.
  "Android Hierarchy Viewer" is already installed, so an update will be performed instead.
  "Android Traceview" is already installed, so an update will be performed instead.
Cannot complete the install because one or more required items could not be found.
  Software being installed: Android Development Tools 17.0.0.v201203161636-291853 (com.android.ide.eclipse.adt.feature.group 17.0.0.v201203161636-291853)
  Missing requirement: Android Development Tools 17.0.0.v201203161636-291853 (com.android.ide.eclipse.adt.feature.group 17.0.0.v201203161636-291853) requires 'org.eclipse.core.runtime 3.6.0' but it could not be found
原因及解决办法:


【错误信息】
Updates ADT 17.0.0时提示:
Cannot complete the install because one or more required items could not be found.
  Software being installed: Android Development Tools 17.0.0.v201203161636-291853 (com.android.ide.eclipse.adt.feature.group 17.0.0.v201203161636-291853)
  Missing requirement: Android Development Tools 17.0.0.v201203161636-291853 (com.android.ide.eclipse.adt.feature.group 17.0.0.v201203161636-291853) requires 'org.eclipse.core.runtime 3.6.0' but it could not be found
原因及解决办法:
requires 'org.eclipse.core.runtime 3.6.0' but it could not be found
requires 'org.eclipse.ui 3.6.0' but it could not be found
eclipse需要升级到3.6.0,我的版本是3.5.2


【错误信息】
[2012-04-09 17:14:49 - Info] ------------------------------
[2012-04-09 17:14:49 - Info] Android Launch!
[2012-04-09 17:14:49 - Info] Connection with adb was interrupted.
[2012-04-09 17:14:49 - Info] 0 attempts have been made to reconnect.
[2012-04-09 17:14:49 - Info] You may want to manually restart adb from the Devices view.
原因及解决办法:
重新启动eclipse


【错误信息】
[2012-04-10 09:45:49 - adb] ADB server didn't ACK
[2012-04-10 09:45:49 - adb] * failed to start daemon *
原因及解决办法:
查看任务管理器,关闭所有adb.exe
重启eclipse


【错误信息】
[2012-04-10 09:53:50 - ApiDemos] ------------------------------
[2012-04-10 09:53:50 - ApiDemos] Android Launch!
[2012-04-10 09:53:50 - ApiDemos] The connection to adb is down, and a severe error has occured.
[2012-04-10 09:53:50 - ApiDemos] You must restart adb and Eclipse.
[2012-04-10 09:53:50 - ApiDemos] Please ensure that adb is correctly located at 'C:\android\android-sdk-windows\platform-tools\adb.exe' and can be executed.
原因及解决办法:
重启eclipse


【错误信息】
安装android sdk时:
-= warning! =- A folder failed to be renamed or moved. On Windows this typically means that a program Is using that Folder (for example Windows Explorer or your anti-virus software.) Please momentarily deactivate your anti-virus software. Please also close any running programs that may be accessing the directory 'C:\android\android-sdk-windows/android-sdk-windows/too!s'. When ready, press YES to try again.

原因及解决办法:
1, 复制 tools目录
为一个新的目录 tools-copy ,此时在android-sdk-windows 目录下有两个目录 tools 和 tools-copy
2, 在tools-copy目录以管理员身份运行 android.bat ,这样就可以正常 update all 了
3.重新运行SDK Manager.exe.问题解决!


【错误信息】
“正在启动JavaEyeApiAccessor“遇到问题。
不能连接至VM

原因及解决办法:
连接不到手机虚拟机
重启拔插手机连接线


【错误信息】
调试的时候:
[2012-04-13 17:46:27 - IpsosAutoAndroid] Failed to install IpsosAutoAndroid.apk on device '?': timeout
[2012-04-13 17:46:27 - IpsosAutoAndroid] Launch canceled!
原因及解决办法:
连接真机调试的时候如果连接太久没响应就会出现timeout
1.在window-》prensent....-》android-》设置ddms的timeout时间。这种是就最有效、最简洁的。
2.delete android里面的 apk,保证速度。不过试过一次后,真机好像变“聪明了”,也出现timeout。
3.Cleaning the project (Project->Clean),不行就重启eclipse或者android,很郁闷的是,重启后运行第一次可以。第二次就开始变慢了,也就是出现timeout

4.关闭eclipse ,然后再重启,就ok


【错误信息】
调用org.ksoap2.*访问webservice时
04-13 10:09:49.565: E/dalvikvm(354): Could not find class 'org.ksoap2.serialization.SoapObject', referenced from method......
04-13 10:09:49.585: E/dalvikvm(354): Could not find class 'org.ksoap2.transport.HttpTransportSE', referenced from method......
【错误信息】
Unable to open stack trace file '/data/anr/traces.txt': Permission denied
原因及解决办法:
Unable to open stack trace file '/data/anr/traces.txt': Permission 多见于这个Activity你没有在AndroidManifest.xml中注册,就会报这样的错误。


【错误信息】
source not found
找不到源
原因及解决办法:
android目录下没有对应的sources文件

如下图,不知道为什么,最新的SDK更新API 14/15中有Sources for Android SDK,而之前的版本的源码就不更新,气愤!

下载对应的SDK Sources后,放到\android-sdk-windows\sources 目录下就OK了!


【错误信息】
Android使用KSOAP2调用WebService时:
java.lang.NoClassDefFoundError: org.ksoap2.serialization.SoapObject
原因及解决办法:
虽然标明上 Java Build Path->Libraries中已经引用了ksoap2-android 包,但是需要order and export中也把该包勾选上


【错误信息】

error: Error: No resource found that matches the given name (at 'layout_toLeftOf' with value'@id/top_send_btn').
header_questionitemlist.xml /IpsosAutoAndroid/res/layout 第 27 行 Android AAPT Problem
原因及解决办法:


【错误信息】
无法解析导入 com.renren.api.connect.android.R
原因及解决办法:
导入android源码有错,R.java文件不能自动生成解决方法

【错误信息】
Eclipse中的DDMS无法打开data文件夹下的内容,也不能往里面写东西
原因及解决办法:
通过软件获取ROOT权限

【错误信息】
Fri May 04 16:27:46 CST 2012
Internal error logged from JDI Debug:
org.eclipse.jdi.TimeoutException: 等待包 8 时发生超时。
at org.eclipse.jdi.internal.connect.PacketReceiveManager.getReply(PacketReceiveManager.java:171)
at org.eclipse.jdi.internal.connect.PacketReceiveManager.getReply(PacketReceiveManager.java:180)
......
原因及解决办法:
重新启动eclipse,不行的话重启机器

【错误信息】
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
原因及解决办法:

如下是有问题的代码:
                Thread t = new Thread() {@Overridepublic void run() {super.run();try {QuestionItemlist = quesHandler.getData();if (QuestionItemlist.size() == 0) {Toast.makeText(questionitemlist2.this,"问卷题目为 空",Toast.LENGTH_LONG).show();} else {Toast.makeText(questionitemlist2.this,"问卷题目已经获 取",Toast.LENGTH_LONG).show();}} catch (Exception e) {e.printStackTrace();}}};t.start();

【错误信息】
java.lang.IllegalArgumentException: The key must be an application-specific resource id.
原因及解决办法:
mRadioButton.setTag(1,sQuestionItem.get(i).getToNext());//设置监听  ToNext:下 一题目mRadioButton.setTag(2,sQuestionItem.get(i).getToEnd());//设置监听  ToEnd: 是否终止 抛出IllegalArgumentException的原因就在于key不唯一,正确代码如下:
mRadioButton.setTag(R.id.tag_tonext,sQuestionItem.get(i).getToNext());// 设置监听  ToNext:下一题目 mRadioButton.setTag(R.id.tag_toend,sQuestionItem.get(i).getToEnd());//设置 监听  ToEnd:是否终止
【错误信息】
点击Debug 运行 结果模拟器总是会弹出Waiting for Debugger 然后程序又可以正常运行
如果你想调试的时候去掉 Waiting for Debugger 提示
原因及解决办法:
重启启动机器就OK

本文出自 “java之路” 博客,请务必保留此出处http://2402766.blog.51cto.com/2392766/1102373

posted @ 2013-05-17 16:57 姚先进 阅读(250) | 评论 (0)编辑 收藏

2013年5月13日

Fedora12下搭建Qt Creator的ARM开发环境 并 移植Qt4.6.2到Micro2440(一)

管理提醒: 本帖被 kasim 执行置顶操作(2010-04-11)
Fedora12下搭建Qt Creator的ARM开发环境 并 移植Qt4.6.2到Micro2440(一)
参考:
环境:虚拟机Fedora12(建议安装Vmware Tools,详细安装方法参照Vmware帮助文档),USB串口,minicom终端。(minicom经常打不开ttyUSB0设备,我的解决方法是,打不开时就将USB串口移除,运行minicom,然后再接上USB串口,此时运行minicom一般都能打开设备)
软件准备:
到http://qt.nokia.com/downloads-cn下载最新版的软件包,当前是:
用于 Linux/X11 32位 的 Qt Creator 1.3.1 二进制软件包qt-creator-linux-x86-opensource-1.3.1.bin(http://qt.nokia.com/downloads/qt-creator-binary-for-linux-x11-32-bit)
用于嵌入式 Linux 的 Qt 库 4.6.2包qt-everywhere-opensource-src-4.6.2.tar.gz(http://qt.nokia.com/downloads/embedded-linux-cpp)
到http://hi.baidu.com/jiyeqian/blog/item/f46d26a2ff3f7da6caefd0d6.html下载arm920t-eabi.tgz(即arm-linux-gcc-4.1.2)(http://qtextended.org/downloads/toolchains/arm920t-eabi.tgz)
到http://www.arm9.net/download.asp下载Root_Qtopia,我用的是友善光盘里的root_qtopia-20100108.tar.gz(http://www.arm123.com.cn/linux/root_qtopia-20100108.tar.gz)
下载tslib1.4,这个忘了在哪下载的了,网上有很多,有些不能用,大家自己找个能用的吧。
将 qt-everywhere-opensource-src-4.6.2.tar.gz 压缩包解压为3份,分别编译 PC ,嵌入式 x86 和 arm 三个版本。
我在root目录下建立tmp文件夹,将qt-everywhere-opensource-src-4.6.2.tar.gz直接解压后复制2分,分别命名为pc、x86、arm。
1. 编译 PC 版:
进入pc目录
#./configure
# gmake
# gmake install
安装过程比较长,没有碰到过错误。
2. 编译嵌入式x86版:
进入x86目录
# ./configure -embedded x86 -qt-gfx-qvfb -qt-kbd-qvfb -qt-mouse-qvfb
# gmake
# gmake install
安装过程比较长,没有碰到过错误。
编译安装PC版中的 qvfb:
进入pc/tools/qvfb/目录
#make
编译完毕,将pc/bin目录下的qvfb文件复制到/usr/local/Trolltech/QtEmbedded-4.6.2/bin目录。
3. 编译嵌入式arm版(需要 arm-linux-gcc 的支持):
使用友善自带的ARM-Linux GCC 4.3.2编译完了,程序移植到开发板上后,出现Segmentation Fault错误,按原文,使用4.1.2正常。
直接将arm920t-eabi.tgz解压缩到根目录,不可以像文章中说的那样“我把它放在:/usr/local/arm/4.1.2/ ”,最起码我放过去后出错了。
把编译器路径加入系统环境变量,运行命令:
#gedit /root/.bashrc
编辑/root/.bashrc文件,在最后一行加上 export PATH=/opt/toolchains/arm920t-eabi/bin:$PATH

编译tslib对触摸屏支持:
下载,tslib1.4.tar.gz,解压后:
# ./configure --prefix=/usr/local/tslib/ --host=arm-linux ac_cv_func_malloc_0_nonnull=yes
# make
# make install
我下载的包解压后没有configure文件,需要运行autogen.sh后才能生成。
设置环境变量,以便编译时找到相关的库:
# export CPLUS_INCLUDE_PATH=/opt/toolchains/arm920t-eabi/arm-angstrom-linux-gnueabi/include/c++:/opt/toolchains/arm920t-eabi/arm-angstrom-linux-gnueabi/include/c++/arm-none-linux-gnueabi
# export PATH=/opt/toolchains/arm920t-eabi/bin:$PATH

修改qt-everywhere-opensource-src-4.6.2/mkspecs/qws/linux-arm-g++/qmake.conf 文件(添加lts参数):
QMAKE_CC                = arm-linux-gcc -lts
QMAKE_CXX               = arm-linux-g++ -lts
QMAKE_LINK              = arm-linux-g++ -lts
QMAKE_LINK_SHLIB        = arm-linux-g++ -lts
这一步必须有,不然肯定出错。
配置:
必须加上“-prefix /usr/local/Trolltech/QtEmbedded-4.6.2-arm ”参数, 不然安装后不在QtEmbedded-4.6.2-arm文件夹下,而是覆盖了QtEmbedded-4.6.2。
# ./configure \
-prefix /usr/local/Trolltech/QtEmbedded-4.6.2-arm \
-opensource \
-confirm-license \
-release -shared \
-embedded arm \
-xplatform qws/linux-arm-g++ \
-depths 16,18,24 \
-fast \
-optimized-qmake \
-pch \
-qt-sql-sqlite \
-qt-libjpeg \
-qt-zlib \
-qt-libpng \
-qt-freetype \
-little-endian -host-little-endian \
-no-qt3support \
-no-libtiff -no-libmng \
-no-opengl \
-no-mmx -no-sse -no-sse2 \
-no-3dnow \
-no-openssl \
-no-webkit \
-no-qvfb \
-no-phonon \
-no-nis \
-no-opengl \
-no-cups \
-no-glib \
-no-xcursor -no-xfixes -no-xrandr -no-xrender \
-no-separate-debug-info \
-nomake examples -nomake tools -nomake docs \
-qt-mouse-tslib -I/usr/local/tslib/include -L/usr/local/tslib/lib

上面划掉的蓝色内容,可以不要的,这样编辑也不会出错(虚拟机搞坏了,不得已重装,配置参数时忘了干上面的工作了,结果发现没出错)。

关于配置参数,参照一下这篇文章吧,可以用configure -embedded –help查看。

http://www.cuteqt.com/blog/?p=582
如果你放弃配置,则使用命令:# gmake confclean
编译:# gmake
安装:# gmake install
安装完成后,在 /usr/local/Trolltech 目录中有三个文件夹:Qt-4.6.2、QtEmbedded-4.6.2、QtEmbedded-4.6.2-arm。
4、移植
我是通过NFS启动的系统,具体操作可以参照友善的手册,在http://www.arm9.net/download.asp有下载,在第5.5.3节通过NFS启动系统。
将Fedora12上  /usr/local/Trolltech/QtEmbedded-4.6.2-arm/lib 中的所有文件复制到/opt/FriendlyARM/mini2440/root_qtopia/usr/local/Trolltech/QtEmbedded-4.6.2-arm/lib目录中(对应目录复制,相当于复制到了开发板对应目录中),其实需要的时候可以裁剪,看原文吧。
将Fedora12上  /usr/local/tslib 中的库复制到/opt/FriendlyARM/mini2440/root_qtopia/usr/local中。即将/usr/local/tslib下的所有文件复制到/opt/FriendlyARM/mini2440/root_qtopia/usr/local文件夹下。
如果运行时还缺少其他的库,复制方法相同。也可以使用arm-angstrom-linux-gnueabi-readelf -a 程序名 | grep "Share",命令查看需要哪些共享库,一起复制过去。
为支持触摸屏,开机自动设置环境变量,在2440的 /etc/profile中追加:
export LD_LIBRARY_PATH=/usr/local/lib:$QTDIR/lib:$LD_LIBRARY_PATH                                                  
export TSLIB_ROOT=/usr/local/lib    
export TSLIB_TSDEVICE=/dev/input/event0
export TSLIB_FBDEVICE=/dev/fb0 
export TSLIB_PLUGINDIR=/usr/local/lib/ts
export TSLIB_CONSOLEDEVICE=none
export TSLIB_CONFFILE=/usr/local/etc/ts.conf
export POINTERCAL_FILE=/etc/pointercal
export TSLIB_CALIBFILE=/etc/pointercal
export QWS_MOUSE_PROTO=Tslib:/dev/input/event0
取消/usr/local/etc/ts.conf中的第一个注释:
# module_raw input (去掉#,并且该行顶格)
我编辑时没有“#”
启动Micro2440运行 /usr/local/bin/ts_calibrate 校正触摸屏。
到此Qt4.6.2的移植暂告一段落,移植还没有完,此时如果在开发板上运行Qt4.6.2-arm编译的程序,则会出现“relocation error: /usr/local/Trolltech/QtEmbedded-4.6.2-arm/lib/libQtGui.so.4: symbol powf, version GLIBCXX_3.4 not defined in file libstdc++.so.6 with link time reference”错误。
今天晚了,明天继续奉上……
tslib-1.4.part1.rar (900 K) 下载次数:1066 tslib-1.4.part2.rar (223 K) 下载次数:936


 Fedora12下搭建Qt Creator的ARM开发环境 并 移植Qt4.6.2到Micro2440(二)

管理提醒: 本帖被 kasim 执行加亮操作(2010-04-11)
Fedora12下搭建Qt Creator的ARM开发环境 并 移植Qt4.6.2到Micro2440(二)
继续……
5、安装Qt-creator-1.3.1
把下载的qt-creator-linux-x86-opensource-1.3.1.bin文件拷到一个目录(如前面的/root/tmp目录),进入目录:
设置qt-creator-linux-x86-opensource-1.3.1.bin文件为可执行
#chmod +x qt-creator-linux-x86-opensource-1.3.1.bin
安装:
# ./ qt-creator-linux-x86-opensource-1.3.1.bin
启动安装界面,默认一路Next即可。
*如果我们下载的是Qt的SDK(qt-sdk-linux-x86-opensource-2010.02.bin),这里可以选择安装Qt的开发环境,这样,在前面安装pc版Qt那步就可以省了,关键是可以省出很多时间的。
6、Qt-creator开发环境的配置
启动Qt-creator。
在Qt-creator菜单栏Tools—〉Options…打开Options窗口。
在Options界面左侧,点击Qt4—〉Qt Versions右侧显示Qt Versions设置界面。
在Qt Versions界面中点击那个蓝色的大“”号图标
在下方Version Name:文本框内输入Qt的版本名,可以随便填,能区分各个版本即可(如pc版取Qt4.6.2-pc、x86版取QtE4.6.2-x86、arm版取QtE4.6.2-arm)。
单击Qmake Location:右侧Browse…按钮,在弹出的“Select QMake Executable”窗口中找到对应版本的qmake程序(按照我们前面安转的,pc版路径:/usr/local/Trolltech/Qt-4.6.2/bin/qmake,x86版路径:/usr/local/Trolltech/QtEmbedded-4.6.2/bin/qmake,arm版路径:/usr/local/Trolltech/QtEmbedded-4.6.2-arm/bin/qmake),单击打开,回到Qt Versions界面。
回到Qt Versions界面,单击Debugging Helper:右侧Rebuild按钮,等待片刻,看到Debugging Helper:后出现一个绿色的“”即可。
同理完成其他版本的添加。
添加完毕,单击OK按钮关闭Options窗口。
到此,Qt-creator配置完毕(我暂时就配置了这些)。
7、一个例子
从usr/local/Trolltech/QtEmbedded-4.6.2/demos下复制books例程到root/tmp文件夹下。
启动Qt-creator,File—〉Open File or Project…,打开root/tmp/books/books.pro。
这里我们分两部分,首先编译x86下的,并运行在qvfb下,再编译arm下的,移到开发板下运行。
7.1、x86下的编译与调试
在Qt-creator界面左侧点击Projects图标,打开工程设置界面。
从上往下,
在Edit Project Settings for Project books——〉Build Settings——〉Edit Build Configuration:单击Add,在下拉列表中选择Using Qt Version “QtE4.6.2-x86”弹出对话框单击Ok按钮,在Edit Build Configuration:下会出现蓝色的Make QtE4.6.3-x86 Release active.字符,单击激活QtE4.6.3-x86 Release。
在Run Settings——〉Edit run configuration:右侧单击Show Details按钮,在打开的下拉列表中Arguments:文本框中添加参数“-qws”。
设置完毕,点击Edit图标,回到编辑界面。
编译:在Build菜单下,先Clean Project “books”,然后Build Project “books”,在右下角Compile Output窗口能看到编译信息(按我们上面这样走来,到此编译不会出问题的)。
运行:
启动终端,# /usr/local/Trolltech/QtEmbedded-4.6.2/bin/qvfb -width 800 -height 480 &,启动Qvfb。
回到Qt-creator,Build——〉Run,运行程序。
切换我们的Qvfb窗口中,是不是看到Books运行的界面了。
调试:Debug——〉Start Debugging——〉Start Debugging,即可启动调试(请保证books路径中没有中文名,即不要把books工程放在了某个含有中文字符的文件夹下,不然无法启动调试)。
此时感觉如果前面编译选项Edit Project Settings for Project books——〉Build Settings——〉Edit Build Configuration:选择Debug项,则调试启动速度比Release时的要快很多。
7.2、arm编译并移植
编译:在Projects设置界面下,选择Using Qt Version “QtE4.6.2-arm”项,余下参数不变,build。
复制编译好的文件(也许还有images文件夹)到2440的NFS文件系统的某个目录下,我直接把books文件夹复制过去了(在Fedora12 文件系统下是/opt/FriendlyARM/mini2440/root_qtopia/home/plg文件夹下)。
运行及错误处理:
在minicom下面,ps一下,找到qpe进程对应的PID,比如1234,然后通过kill 1234杀死Qtopia。
进入books目录,执行./books –qws,此时就会出现前面讲到的“relocation error: /usr/local/Trolltech/QtEmbedded-4.6.2-arm/lib/libQtGui.so.4: symbol powf, version GLIBCXX_3.4 not defined in file libstdc++.so.6 with link time reference”错误。
我的解决办法是进入主机/opt/toolchains/arm920t-eabi/arm-angstrom-linux-gnueabi/lib目录下找到libstdc++.so.6链接的文件libstdc++.so.6.0.8(通过右键属性——〉基本,可以看到链接的文件),复制并重命名为libstdc++.so.6到/opt/FriendlyARM/mini2440/root_qtopia/lib文件夹下,之前别忘了将该文件夹下的libstdc++.so.6移到其它地方或重命名,如libstdc++.so.6.old。
*重命名其实是比较野蛮的方法,可以用ln命令的,参照下面这篇文章……
http://hi.baidu.com/a263238386/blog/item/362f01ce7b11a10a93457eae.html
然后再运行./books –qws,看问题是不是解决了!
这里有个新的问题还没解决,就是在开发版上运行时字非常小,留着以后处理吧。
OK!至此,Fedora12下搭建Qt Creator的ARM开发环境 并 移植Qt4.6.2到Micro2440算告一段落了,留下两个问题:字体非常小的问题、开发板上的远程调试,留待下次解决。
posted @ 2013-05-13 16:19 姚先进 阅读(444) | 评论 (0)编辑 收藏

2013年5月10日

    像风一样沐浴自由,等待木棉花开

离别多时,猛然看到他的文字,迎面而来的是清新和洒脱,放飞了自己,开阔了心境。从心里面为他高兴,又隐隐的疼惜自己,因为一个人还没有放下。
多伤感,多惆怅,多很多的是逃避。

有时候突然豪言壮语,突然壮志凌云,突然觉得一切都可能。但是有时又发现那些东西可有可无,无非是名利,是物质满足,是填补欲望,
没有真正的追求
posted @ 2013-05-10 10:02 姚先进 阅读(214) | 评论 (0)编辑 收藏

2013年4月22日

  package com.example.hoteltest;
    import java.io.ByteArrayOutputStream;  
import java.io.InputStream;  
import java.net.*;  
import java.util.ArrayList;  
import java.util.HashMap;  
import java.util.List;  
import java.util.Map;  
import org.json.JSONArray;  
import org.json.JSONObject;  
import android.util.Log;  
      
    public class JSON {  
      
          
        /**
         * 获取"数组形式"的JSON数据,
         * 数据形式:[{"id":1,"name":"小猪"},{"id":2,"name":"小猫"}]
         * @param path  网页路径
         * @return  返回List
         * @throws Exception
         */  
        public static List<Map<String, String>> getJSONArray(String path) throws Exception {  
            String json = null;  
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();  
            Map<String, String> map = null;  
            URL url = new URL(path);  
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.  
            conn.setConnectTimeout(5 * 1000);   // 单位是毫秒,设置超时时间为5秒  
            conn.setRequestMethod("GET");       // HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET  
            if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败  
                InputStream is = conn.getInputStream(); // 获取输入流  
                byte[] data = readStream(is);   // 把输入流转换成字符数组  
                json = new String(data);        // 把字符数组转换成字符串  
                  
                //数据形式:[{"id":1,"name":"小猪","age":22},{"id":2,"name":"小猫","age":23}]  
                JSONArray jsonArray = new JSONArray(json); //数据直接为一个数组形式,所以可以直接 用android提供的框架JSONArray读取JSON数据,转换成Array  
      
                for (int i = 0; i < jsonArray.length(); i++) {  
                    JSONObject item = jsonArray.getJSONObject(i); //每条记录又由几个Object对象组成  
                    int id = item.getInt("id");     // 获取对象对应的值  
                    String name = item.getString("name");  
      
                    map = new HashMap<String, String>(); // 存放到MAP里面  
                    map.put("id", id + "");  
                    map.put("name", name);  
                    list.add(map);  
                }  
            }  
      
            // ***********测试数据******************  
            for (Map<String, String> list2 : list) {  
                String id = list2.get("id");  
                String name = list2.get("name");  
                Log.i("abc", "id:" + id + " | name:" + name);  
            }  
      
            return list;  
        }  
      
        /**
         * 获取"对象形式"的JSON数据,
         * 数据形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"小猪"},{"id":2,"name":"小猫"}]}
         * @param path  网页路径
         * @return  返回List
         * @throws Exception
         */  
        public static List<Map<String, String>> getJSONObject(String path) throws Exception {  
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();  
            Map<String, String> map = null;  
            URL url = new URL(path);  
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.  
            conn.setConnectTimeout(5 * 1000);   // 单位是毫秒,设置超时时间为5秒  
            conn.setRequestMethod("GET");       // HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET  
            if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败  
                InputStream is = conn.getInputStream(); // 获取输入流  
                byte[] data = readStream(is);   // 把输入流转换成字符数组  
                String json = new String(data); // 把字符数组转换成字符串  
                  
                  
                //数据形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"小猪"},{"id":2,"name":"小猫"}]}  
                JSONObject jsonObject=new JSONObject(json);     //返回的数据形式是一个Object类型,所以可以直接转换成一个Object  
                int page=jsonObject.getInt("page");  
                String type=jsonObject.getString("type");  
                Log.i("abc", "type:" + type + " |page:" + page);   //测试数据  
                  
                JSONArray jsonArray = jsonObject.getJSONArray("hotels");//里面有一个数组数据,可以用getJSONArray获取数组  
                for (int i = 0; i < jsonArray.length(); i++) {  
                    
                    JSONObject item = jsonArray.getJSONObject(i); // 得到每个对象
                    
                    double distance=item.getDouble("distance");
                    String direction=item.getString("direction");
                    int star_rating=item.getInt("star_rating");
                    String name=item.getString("name");
                    double nightly_rate=item.getDouble("nightly_rate");
                    double promoted_nightly_rate=item.getDouble("promoted_nightly_rate");
                    double total_rate=item.getDouble("total_rate");
                    double longitude=item.getDouble("longitude");
                    String key=item.getString("key");
                    double promoted_total_rate=item.getDouble("promoted_total_rate");
                    String latitude=item.getString("latitude");
                    long master_id=item.getLong("master_id");
                    String thumbnail=item.getString("thumbnail");
                    String street_address=item.getString("street_address");
                    double review_score=item.getDouble("review_score");
           
                    map = new HashMap<String, String>(); // 存放到MAP里面  
                    map.put("distance", distance + "");  
                    map.put("direction", direction + "");  
                    map.put("star_rating", star_rating + "");  
                    map.put("name", name + "");  
                    map.put("nightly_rate", nightly_rate + "");  
                    map.put("promoted_nightly_rate", promoted_nightly_rate + "");  
                    map.put("total_rate", total_rate + "");  
                    map.put("key", key + "");  
                    map.put("promoted_total_rate", promoted_total_rate + "");  
                    map.put("latitude", latitude + "");  
                    map.put("master_id", master_id + "");  
                    map.put("thumbnail", thumbnail + "");    
                    map.put("street_address", street_address + "");  
                    map.put("review_score", review_score + "");  
                  
                    
                    list.add(map);  
                }  
            }  
      
            // ***********测试数据******************  
              
            for (Map<String, String> list2 : list) {  
                String distance = list2.get("distance");  
                String direction = list2.get("direction");  
                String star_rating = list2.get("star_rating");  
                String name = list2.get("name");  
                String nightly_rate = list2.get("nightly_rate");  
                String promoted_nightly_rate = list2.get("promoted_nightly_rate");  
                String total_rate = list2.get("total_rate");  
                String key = list2.get("key");  
                String promoted_total_rate = list2.get("promoted_total_rate");  
                String latitude = list2.get("latitude");  
                String master_id = list2.get("master_id");  
                String thumbnail = list2.get("thumbnail");  
                String street_address = list2.get("street_address");  
                String review_score = list2.get("review_score");  
                System.out.println(distance);
                System.out.println(direction);
                System.out.println(star_rating);
                System.out.println(name);
                System.out.println(nightly_rate);
                System.out.println(promoted_nightly_rate);
                System.out.println(total_rate);
                System.out.println(key);
                System.out.println(promoted_total_rate);
                System.out.println(latitude);
                System.out.println(master_id);
                System.out.println(thumbnail);
                System.out.println(street_address);
                System.out.println(review_score);
            }  
      
            return list;  
        }  
          
          
        /**
         * 获取类型复杂的JSON数据
         *数据形式:
            {"name":"小猪",
             "age":23,
             "content":{"questionsTotal":2,
                        "questions": [ { "question": "what's your name?", "answer": "小猪"},{"question": "what's your age", "answer": "23"}]
                       }
            }
         * @param path  网页路径
         * @return  返回List
         * @throws Exception
         */  
        public static List<Map<String, String>> getJSON(String path) throws Exception {  
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();  
            Map<String, String> map = null;  
            URL url = new URL(path);  
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.  
            conn.setConnectTimeout(5 * 1000);   // 单位是毫秒,设置超时时间为5秒  
            conn.setRequestMethod("GET");       // HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET  
            if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败  
                InputStream is = conn.getInputStream(); // 获取输入流  
                byte[] data = readStream(is);   // 把输入流转换成字符数组  
                String json = new String(data); // 把字符数组转换成字符串  
                  
                  
                /*数据形式:
                    {"name":"小猪",
                     "age":23,
                     "content":{"questionsTotal":2,
                                "questions": [ { "question": "what's your name?", "answer": "小猪"},{"question": "what's your age", "answer": "23"}]
                               }
                    }
                */    
                JSONObject jsonObject=new JSONObject(json);     //返回的数据形式是一个Object类型,所以可以直接转换成一个Object  
                String name=jsonObject.getString("name");         
                int age=jsonObject.getInt("age");  
                Log.i("abc", "name:" + name + " | age:" + age); //测试数据  
                  
                JSONObject contentObject=jsonObject.getJSONObject("content");       //获取对象中的对象  
                String questionsTotal=contentObject.getString("questionsTotal");    //获取对象中的一个值  
                Log.i("abc", "questionsTotal:" + questionsTotal);   //测试数据  
                  
                JSONArray contentArray=contentObject.getJSONArray("questions");     //获取对象中的数组  
                for (int i = 0; i < contentArray.length(); i++) {  
                    JSONObject item = contentArray.getJSONObject(i); // 得到每个对象  
                    String question = item.getString("question");   // 获取对象对应的值  
                    String answer = item.getString("answer");  
      
                    map = new HashMap<String, String>(); // 存放到MAP里面  
                    map.put("question", question);  
                    map.put("answer", answer);  
                    list.add(map);  
                }  
            }  
      
            // ***********测试数据******************  
              
            for (Map<String, String> list2 : list) {  
                String question = list2.get("question");  
                String answer = list2.get("answer");  
                Log.i("abc", "question:" + question + " | answer:" + answer);  
            }  
      
            return list;  
        }  
          
          
          
          
        /**
         * 把输入流转换成字符数组
         * @param inputStream   输入流
         * @return  字符数组
         * @throws Exception
         */  
        public static byte[] readStream(InputStream inputStream) throws Exception {  
            ByteArrayOutputStream bout = new ByteArrayOutputStream();  
            byte[] buffer = new byte[1024];  
            int len = 0;  
            while ((len = inputStream.read(buffer)) != -1) {  
                bout.write(buffer, 0, len);  
            }  
            bout.close();  
            inputStream.close();  
      
            return bout.toByteArray();  
        }  
      
    } 
posted @ 2013-04-22 20:21 姚先进 阅读(249) | 评论 (0)编辑 收藏
 

首先说一下Json数据的最基本的特点,Json数据是一系列的键值对的集合,和XML数据来比,Json数据的体积更加小,传输效率高,易解析,不过可读性不高;

      因为这次要从服务器端得到Json数据,并且通过解析之后把解析后的数据显示在Android客户端中,首先部署服务器端代码(直接使用Jsp/Servlet):

       构造的Json数据如下:

     [{"name":"张三","address":"北京","age":20},{"name":"李四","address":"上海","age":30},{"name":"王五","address":"深圳","age":35}]


[一]服务器端(Person.java省略):

     ①:数据构造JsonService.java

  1. <span style="font-size: 16px; ">public class JsonService {
  2.         public static List<Person> getListPerson() {
  3.                 List<Person> mLists = new ArrayList<Person>();
  4.                 mLists.add(new Person("张三", "北京", 20));
  5.                 mLists.add(new Person("李四", "上海", 30));
  6.                 mLists.add(new Person("王五", "深圳", 35));
  7.                 return mLists;
  8.         }</span>
复制代码
   ②:Servlet的代码(包括构造Json数据,没有使用Json数据转换方法)JsonServlet.java
  1. <span style="font-size: 16px; ">public void doGet(HttpServletRequest request, HttpServletResponse response)
  2.                         throws ServletException, IOException {
  3.                 response.setContentType("text/html");
  4.                 response.setCharacterEncoding("UTF-8");
  5.                 PrintWriter out = response.getWriter();
  6.                 List<Person> persons = JsonService.getListPerson();
  7.                 StringBuffer sb = new StringBuffer();
  8.                 sb.append('[');
  9.                 for (Person person : persons) {
  10.                         sb.append('{').append("\"name\":").append("\""+person.getName()+"\"").append(
  11.                                         ",");
  12.                         sb.append("\"address\":").append("\""+person.getAddress()+"\"").append(",");
  13.                         sb.append("\"age\":").append(person.getAge());
  14.                         sb.append('}').append(",");
  15.                 }
  16.                 sb.deleteCharAt(sb.length() - 1);
  17.                 sb.append(']');
  18.                 out.write(new String(sb));
  19.                 out.flush();
  20.                 out.close();
  21.         }</span>
复制代码
  1. <span style="font-size: 16px; ">
  2. </span>
复制代码
  ③:部署到Tomact 浏览器输入http://localhost/JsonWeb/JsonServlet直接访问结果如下: 0_1330066556axYL.gif        至此服务器端代码编码完成,下面进行客户端代码编写;    (二)客户端(Person类,和展示数据的布局文件因为简单省去)
      ①:获取服务器端的Json数据并且解析的工具类JsonParse.java
  必要的需要导入的包省去  
  1. <span style="font-size:18px;">public class JsonParse {
  2.         /**
  3.          * 解析Json数据
  4.          *
  5.          * @param urlPath
  6.          * @return mlists
  7.          * @throws Exception
  8.          */
  9.         public static List<Person> getListPerson(String urlPath) throws Exception {
  10.                 List<Person> mlists = new ArrayList<Person>();
  11.                 byte[] data = readParse(urlPath);
  12.                 JSONArray array = new JSONArray(new String(data));
  13.                 for (int i = 0; i < array.length(); i++) {
  14.                         JSONObject item = array.getJSONObject(i);
  15.                         String name = item.getString("name");
  16.                         String address = item.getString("address");
  17.                         int age = item.getInt("age");
  18.                         mlists.add(new Person(name, address, age));
  19.                 }
  20.                 return mlists;
  21.         }
  22.         /**
  23.          * 从指定的url中获取字节数组
  24.          *
  25.          * @param urlPath
  26.          * @return 字节数组
  27.          * @throws Exception
  28.          */
  29.         public static byte[] readParse(String urlPath) throws Exception {
  30.                 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  31.                 byte[] data = new byte[1024];
  32.                 int len = 0;
  33.                 URL url = new URL(urlPath);
  34.                 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  35.                 InputStream inStream = conn.getInputStream();
  36.                 while ((len = inStream.read(data)) != -1) {
  37.                         outStream.write(data, 0, len);
  38.                 }
  39.                 inStream.close();
  40.                 return outStream.toByteArray();
  41.         }
  42. }</span>
复制代码
②:主Activity类
  1. <pre name="code" class="java">public class MainActivity extends Activity {
  2.         private Button mButton;
  3.         private ListView mListView;
  4.         //使用IP不能使用localhost或者127.0.0.1,因为android模拟器默认绑定这个IP,这里应该访问局域网IP
  5.         private static final String urlPath = "http://10.16.31.207/JsonWeb/JsonServlet";
  6.         private static final String TAG = "MainActivity";
  7.         private List<Person> persons;
  8.         @Override
  9.         public void onCreate(Bundle savedInstanceState) {
  10.                 super.onCreate(savedInstanceState);
  11.                 setContentView(R.layout.main);
  12.                 mButton = (Button) findViewById(R.id.button1);
  13.                 mListView = (ListView) findViewById(R.id.listView1);
  14.                 mButton.setOnClickListener(new MyOnClickListener());
  15.         }

  16.         private class MyOnClickListener implements OnClickListener {
  17.                 @Override
  18.                 public void onClick(View v) {
  19.                         try {
  20.                                 // 得到Json解析成功之后数据
  21.                                 persons = JsonParse.getListPerson(urlPath);
  22.                                 List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
  23.                                 for (int i = 0; i < persons.size(); i++) {
  24.                                         HashMap<String, Object> map = new HashMap<String, Object>();
  25.                                         map.put("name", persons.get(i).getName());
  26.                                         map.put("address", persons.get(i).getAddress());
  27.                                         map.put("age", persons.get(i).getAge());
  28.                                         data.add(map);
  29.                                 }
  30.                                 //初始化适配器,并且绑定数据
  31.                                 SimpleAdapter _Adapter = new SimpleAdapter(MainActivity.this,
  32.                                                 data, R.layout.listview_item, new String[] { "name",
  33.                                                                 "address", "age" }, new int[] { R.id.textView1,
  34.                                                                 R.id.textView2, R.id.textView3 });
  35.                                 mListView.setAdapter(_Adapter);
  36.                         } catch (Exception e) {
  37.                                 Toast.makeText(MainActivity.this, "解析失败", 2000).show();
  38.                                 Log.i(TAG, e.toString());

  39.                         }
  40.                 }
  41.         }
复制代码
至此服务器端和客户端编码介绍,运行android应用结果截图:
0_1330067381FcfP.gif
Json数据解析服务器端加客户端代码.zip (75.08 KB, 下载次数: 1309)



1

查看全部评分

posted @ 2013-04-22 19:11 姚先进 阅读(291) | 评论 (0)编辑 收藏
 
     摘要: 、利用HttpUrlConnection 1 /** 2 * 从指定的URL中获取数组 3 * @param urlPath 4 * @return 5 * @throws Exception 6 */ 7 public static String readParse(String urlPath) throws Excep...  阅读全文
posted @ 2013-04-22 19:10 姚先进 阅读(269) | 评论 (0)编辑 收藏
仅列出标题  下一页