2013年9月12日

          試了N多方法,貌似在終端執(zhí)行命令:
          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 姚先進 閱讀(255) | 評論 (0)編輯 收藏

          2013年9月11日

           與association一樣,collection元素也有兩種形式,現(xiàn)介紹如下:
          一、嵌套的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>

                運行程序結(jié)果如下: 

                 與以前的寫法相比,這種寫法的缺點是學生實體映射被嵌入到教師實體映射中,因此學生實體映射不能被重用。

          二、嵌套的select語句

                這種方式是使用一條單獨的select語句來加載關聯(lián)的實體(在本例中就是學生實體),然后在collection元素中引用此select語句(注:此方法會產(chǎn)生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列的值作為參數(shù)  

          19.             傳遞給將要引用到的下述的getStudents的select語句,此屬性不可少。  

          20.             引用的形式為:命名空間.select語句id-->

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

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

          23. </resultMap>

          24. </mapper>

                 在這里把根據(jù)指導教師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. <!--根據(jù)指導教師id查詢學生信息-->

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

          19. resultMap="studentResultMap">

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

          21. </select>

          22. </mapper>

                執(zhí)行結(jié)果如下:

          posted @ 2013-09-11 13:44 姚先進 閱讀(415) | 評論 (0)編輯 收藏

          2013年9月10日

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

          在執(zhí)行數(shù)據(jù)庫操作時需要先判斷指定的數(shù)據(jù)是否存在,如果不存在則插入,存在則更新

          最開始使用的是三條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+?;  

          但是有個前提就是:什么時候會執(zhí)行update語句?在SQL語句中并沒有條件。

          后來在網(wǎng)上看到的,執(zhí)行update語句的條件是insert語句的執(zhí)行會造成唯一鍵的重復。

          所以,在創(chuàng)建表的時候還要加上唯一鍵的約束

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

          這樣就能達到目的。

          posted @ 2013-09-10 18:56 姚先進 閱讀(920) | 評論 (0)編輯 收藏

          2013年7月29日

          JSP:include的flush屬性的作用

          分類: 其他 2012-04-06 10:51 2572人閱讀 評論(2) 收藏 舉報
          includejspservlet服務器瀏覽器
          JSPinclude 另一個文件時有個很偏的屬性,叫flush,默認為 false。

          在同一個 JSP 中,如果不斷 include 自己(源文件),在邏輯上會形成死循環(huán)。若默認情況下,服務器會等待該文件被讀到底端,然后才輸出到客戶端,并且銷毀該次訪問的 request 和 response。而當把flush 屬性賦為真值時,在緩存累積了一定數(shù)據(jù)時,服務器會先提供一部分數(shù)據(jù)給瀏覽器,并等待后續(xù)內(nèi)容。

          由此可以得出結(jié)論,在簡單頁面中,該屬性不納入考慮,而在頁面包含大量數(shù)據(jù)時,為縮短客戶端延遲,可將一部分內(nèi)容先行輸出。該屬性在 Servlet 中也有對應的應用。
          posted @ 2013-07-29 20:54 姚先進 閱讀(491) | 評論 (1)編輯 收藏

          2013年5月17日

           大家都在為項目開發(fā)成功而喜悅,但可不知成功的路上是會經(jīng)常出錯的,下面是我碰到的一些錯誤集合!

          【錯誤信息】

          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也是一樣的

          原因:
           在向本機發(fā)送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
          原因:
          原先目錄已經(jīng)有pkg_3.apk的文件夾,再copy一個pkg_3.apk安裝文件時出現(xiàn)問題,解決辦法,先刪除掉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時出現(xiàn):
          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開發(fā)插件版本過低,應該下載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,執(zhí)行adb kill-server命令,然后重試一下


          【錯誤信息】
          調(diào)用Webservice時出現(xiàn)
          java.net.SocketException: Permission denied (maybe missing INTERNET permission)
          原因:
          需要訪問到網(wǎng)絡,所以,在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結(jié)束的...但是.需要注意的是..要去掉后面的.wsdl或者.?wsdl


          【錯誤信息】
          在新的線程中 public class HttpThread extends Thread {...}
          增加一個彈出窗體:
          new AlertDialog.Builder(this).setTitle("數(shù)據(jù)加載失敗").setMessage("請檢查網(wǎng)絡連接情況")           .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(" 數(shù)據(jù)加載失敗").setMessage("請檢查網(wǎng)絡連接情況")           .setPositiveButton("OK", new DialogInterface.OnClickListener(){            public void onClick(DialogInterface dialoginterface, int i)            {            }


          【錯誤信息】
          The constructor AlertDialog.Builder(chuanbo_detail.HttpThread) is undefined
          原因及解決辦法:
          在UI主線程之外是無法對UI組件進行控制的。因為你必須在新線程任務完成之后利用各種方法先UI主線程發(fā)送消息通知任務完成從而來顯示各種提示消息。
          線程間通信方法有多種,常用的是用handler來傳遞消息。
          如下:
          線程中構(gòu)造消息:
          //構(gòu)造消息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("數(shù)據(jù)加載失敗").setMessage(" 請檢查網(wǎng)絡連接情況!")                .setPositiveButton("OK", new DialogInterface.OnClickListener(){                        public void onClick(DialogInterface dialoginterface, int i)                        {                        }          }).show();}}};


          【錯誤信息】
          android低版本工程(如1.5)放到高版本環(huán)境中(如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的工程結(jié)構(gòu)就一樣了。


          【錯誤信息】
          在線程debug(運行沒有問題)時調(diào)用Webservice時出現(xiàn):
          '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 網(wǎng)站基于 Android 平臺的客戶端軟件,可用以閱讀動靜、帖子、閑談, 收躲, RSS 等功用。

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


          原因及解決辦法:
          遇到這種情況,可以創(chuàng)建一個default.properties文件,如果創(chuàng)建之后還是有錯誤,那么delete這個project,重新import。
          編輯default.properties 之后,一般會自動創(chuàng)建 gen 目錄, 如果沒有,也可嘗試手工創(chuàng)建。

          ?Adroid Adapter ADB Interface 嚴重錯誤
          今天在配置完Eclipse和Android SDK開發(fā)環(huán)境之后,想用華為C8500手機通過USB連接電腦,并在手機上去調(diào)試,但莫名其妙出現(xiàn)Adroid Adapter ADB Interface 安裝嚴重錯誤,在豌豆莢手機精靈安裝驅(qū)動的時候,也出現(xiàn)這個錯誤,后面也莫名奇妙的多裝幾次就好了,還沒找到什么原因。


          【錯誤信息】
          用手機調(diào)試運行出現(xiàn):
          ActivityManager: Warning: Activity not started, its current task has been brought to the front
          原因及解決辦法:
          該手機已經(jīng)啟動了相同名字的應用,關閉之后再試!


          【錯誤信息】
          最近(2012-04-05)在打開SDK Manager.exe,更新SDK時,會出現(xiàn)如下錯誤:

          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,
          這里可不能用常規(guī)方法安裝這個 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

          原因及解決辦法:
          連接不到手機虛擬機
          重啟拔插手機連接線


          【錯誤信息】
          調(diào)試的時候:
          [2012-04-13 17:46:27 - IpsosAutoAndroid] Failed to install IpsosAutoAndroid.apk on device '?': timeout
          [2012-04-13 17:46:27 - IpsosAutoAndroid] Launch canceled!
          原因及解決辦法:
          連接真機調(diào)試的時候如果連接太久沒響應就會出現(xiàn)timeout
          1.在window-》prensent....-》android-》設置ddms的timeout時間。這種是就最有效、最簡潔的。
          2.delete android里面的 apk,保證速度。不過試過一次后,真機好像變“聰明了”,也出現(xiàn)timeout。
          3.Cleaning the project (Project->Clean),不行就重啟eclipse或者android,很郁悶的是,重啟后運行第一次可以。第二次就開始變慢了,也就是出現(xiàn)timeout

          4.關閉eclipse ,然后再重啟,就ok


          【錯誤信息】
          調(diào)用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調(diào)用WebService時:
          java.lang.NoClassDefFoundError: org.ksoap2.serialization.SoapObject
          原因及解決辦法:
          雖然標明上 Java Build Path->Libraries中已經(jīng)引用了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文件夾下的內(nèi)容,也不能往里面寫東西
          原因及解決辦法:
          通過軟件獲取ROOT權(quán)限

          【錯誤信息】
          Fri May 04 16:27:46 CST 2012
          Internal error logged from JDI Debug:
          org.eclipse.jdi.TimeoutException: 等待包 8 時發(fā)生超時。
          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,"問卷題目已經(jīng)獲 取",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());//設置監(jiān)聽  ToNext:下 一題目mRadioButton.setTag(2,sQuestionItem.get(i).getToEnd());//設置監(jiān)聽  ToEnd: 是否終止 拋出IllegalArgumentException的原因就在于key不唯一,正確代碼如下:
          mRadioButton.setTag(R.id.tag_tonext,sQuestionItem.get(i).getToNext());// 設置監(jiān)聽  ToNext:下一題目 mRadioButton.setTag(R.id.tag_toend,sQuestionItem.get(i).getToEnd());//設置 監(jiān)聽  ToEnd:是否終止
          【錯誤信息】
          點擊Debug 運行 結(jié)果模擬器總是會彈出Waiting for Debugger 然后程序又可以正常運行
          如果你想調(diào)試的時候去掉 Waiting for Debugger 提示
          原因及解決辦法:
          重啟啟動機器就OK

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

          posted @ 2013-05-17 16:57 姚先進 閱讀(274) | 評論 (0)編輯 收藏

          2013年5月13日

          Fedora12下搭建Qt Creator的ARM開發(fā)環(huán)境 并 移植Qt4.6.2到Micro2440(一)

          管理提醒: 本帖被 kasim 執(zhí)行置頂操作(2010-04-11)
          Fedora12下搭建Qt Creator的ARM開發(fā)環(huán)境 并 移植Qt4.6.2到Micro2440(一)
          參考:
          環(huán)境:虛擬機Fedora12(建議安裝Vmware Tools,詳細安裝方法參照Vmware幫助文檔),USB串口,minicom終端。(minicom經(jīng)常打不開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,這個忘了在哪下載的了,網(wǎng)上有很多,有些不能用,大家自己找個能用的吧。
          將 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編譯完了,程序移植到開發(fā)板上后,出現(xiàn)Segmentation Fault錯誤,按原文,使用4.1.2正常。
          直接將arm920t-eabi.tgz解壓縮到根目錄,不可以像文章中說的那樣“我把它放在:/usr/local/arm/4.1.2/ ”,最起碼我放過去后出錯了。
          把編譯器路徑加入系統(tǒng)環(huán)境變量,運行命令:
          #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后才能生成。
          設置環(huán)境變量,以便編譯時找到相關的庫:
          # 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參數(shù)):
          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 ”參數(shù), 不然安裝后不在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

          上面劃掉的藍色內(nèi)容,可以不要的,這樣編輯也不會出錯(虛擬機搞壞了,不得已重裝,配置參數(shù)時忘了干上面的工作了,結(jié)果發(fā)現(xiàn)沒出錯)。

          關于配置參數(shù),參照一下這篇文章吧,可以用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啟動的系統(tǒng),具體操作可以參照友善的手冊,在http://www.arm9.net/download.asp有下載,在第5.5.3節(jié)通過NFS啟動系統(tǒng)。
          將Fedora12上  /usr/local/Trolltech/QtEmbedded-4.6.2-arm/lib 中的所有文件復制到/opt/FriendlyARM/mini2440/root_qtopia/usr/local/Trolltech/QtEmbedded-4.6.2-arm/lib目錄中(對應目錄復制,相當于復制到了開發(fā)板對應目錄中),其實需要的時候可以裁剪,看原文吧。
          將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",命令查看需要哪些共享庫,一起復制過去。
          為支持觸摸屏,開機自動設置環(huán)境變量,在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的移植暫告一段落,移植還沒有完,此時如果在開發(fā)板上運行Qt4.6.2-arm編譯的程序,則會出現(xiàn)“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”錯誤。
          今天晚了,明天繼續(xù)奉上……
          tslib-1.4.part1.rar (900 K) 下載次數(shù):1066 tslib-1.4.part2.rar (223 K) 下載次數(shù):936


           Fedora12下搭建Qt Creator的ARM開發(fā)環(huán)境 并 移植Qt4.6.2到Micro2440(二)

          管理提醒: 本帖被 kasim 執(zhí)行加亮操作(2010-04-11)
          Fedora12下搭建Qt Creator的ARM開發(fā)環(huán)境 并 移植Qt4.6.2到Micro2440(二)
          繼續(xù)……
          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文件為可執(zhí)行
          #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的開發(fā)環(huán)境,這樣,在前面安裝pc版Qt那步就可以省了,關鍵是可以省出很多時間的。
          6、Qt-creator開發(fā)環(huán)境的配置
          啟動Qt-creator。
          在Qt-creator菜單欄Tools—〉Options…打開Options窗口。
          在Options界面左側(cè),點擊Qt4—〉Qt Versions右側(cè)顯示Qt Versions設置界面。
          在Qt Versions界面中點擊那個藍色的大“”號圖標
          在下方Version Name:文本框內(nèi)輸入Qt的版本名,可以隨便填,能區(qū)分各個版本即可(如pc版取Qt4.6.2-pc、x86版取QtE4.6.2-x86、arm版取QtE4.6.2-arm)。
          單擊Qmake Location:右側(cè)Browse…按鈕,在彈出的“Select QMake Executable”窗口中找到對應版本的qmake程序(按照我們前面安轉(zhuǎn)的,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:右側(cè)Rebuild按鈕,等待片刻,看到Debugging Helper:后出現(xiàn)一個綠色的“”即可。
          同理完成其他版本的添加。
          添加完畢,單擊OK按鈕關閉Options窗口。
          到此,Qt-creator配置完畢(我暫時就配置了這些)。
          7、一個例子
          從usr/local/Trolltech/QtEmbedded-4.6.2/demos下復制books例程到root/tmp文件夾下。
          啟動Qt-creator,F(xiàn)ile—〉Open File or Project…,打開root/tmp/books/books.pro。
          這里我們分兩部分,首先編譯x86下的,并運行在qvfb下,再編譯arm下的,移到開發(fā)板下運行。
          7.1、x86下的編譯與調(diào)試
          在Qt-creator界面左側(cè)點擊Projects圖標,打開工程設置界面。
          從上往下,
          在Edit Project Settings for Project books——〉Build Settings——〉Edit Build Configuration:單擊Add,在下拉列表中選擇Using Qt Version “QtE4.6.2-x86”彈出對話框單擊Ok按鈕,在Edit Build Configuration:下會出現(xiàn)藍色的Make QtE4.6.3-x86 Release active.字符,單擊激活QtE4.6.3-x86 Release。
          在Run Settings——〉Edit run configuration:右側(cè)單擊Show Details按鈕,在打開的下拉列表中Arguments:文本框中添加參數(shù)“-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運行的界面了。
          調(diào)試:Debug——〉Start Debugging——〉Start Debugging,即可啟動調(diào)試(請保證books路徑中沒有中文名,即不要把books工程放在了某個含有中文字符的文件夾下,不然無法啟動調(diào)試)。
          此時感覺如果前面編譯選項Edit Project Settings for Project books——〉Build Settings——〉Edit Build Configuration:選擇Debug項,則調(diào)試啟動速度比Release時的要快很多。
          7.2、arm編譯并移植
          編譯:在Projects設置界面下,選擇Using Qt Version “QtE4.6.2-arm”項,余下參數(shù)不變,build。
          復制編譯好的文件(也許還有images文件夾)到2440的NFS文件系統(tǒng)的某個目錄下,我直接把books文件夾復制過去了(在Fedora12 文件系統(tǒng)下是/opt/FriendlyARM/mini2440/root_qtopia/home/plg文件夾下)。
          運行及錯誤處理:
          在minicom下面,ps一下,找到qpe進程對應的PID,比如1234,然后通過kill 1234殺死Qtopia。
          進入books目錄,執(zhí)行./books –qws,此時就會出現(xiàn)前面講到的“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,看問題是不是解決了!
          這里有個新的問題還沒解決,就是在開發(fā)版上運行時字非常小,留著以后處理吧。
          OK!至此,F(xiàn)edora12下搭建Qt Creator的ARM開發(fā)環(huán)境 并 移植Qt4.6.2到Micro2440算告一段落了,留下兩個問題:字體非常小的問題、開發(fā)板上的遠程調(diào)試,留待下次解決。
          posted @ 2013-05-13 16:19 姚先進 閱讀(475) | 評論 (0)編輯 收藏

          2013年5月10日

              像風一樣沐浴自由,等待木棉花開

          離別多時,猛然看到他的文字,迎面而來的是清新和灑脫,放飛了自己,開闊了心境。從心里面為他高興,又隱隱的疼惜自己,因為一個人還沒有放下。
          多傷感,多惆悵,多很多的是逃避。

          有時候突然豪言壯語,突然壯志凌云,突然覺得一切都可能。但是有時又發(fā)現(xiàn)那些東西可有可無,無非是名利,是物質(zhì)滿足,是填補欲望,
          沒有真正的追求
          posted @ 2013-05-10 10:02 姚先進 閱讀(237) | 評論 (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 {  
                
                    
                  /**
                   * 獲取"數(shù)組形式"的JSON數(shù)據(jù),
                   * 數(shù)據(jù)形式:[{"id":1,"name":"小豬"},{"id":2,"name":"小貓"}]
                   * @param path  網(wǎng)頁路徑
                   * @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對象,我們可以從網(wǎng)絡中獲取網(wǎng)頁數(shù)據(jù).  
                      conn.setConnectTimeout(5 * 1000);   // 單位是毫秒,設置超時時間為5秒  
                      conn.setRequestMethod("GET");       // HttpURLConnection是通過HTTP協(xié)議請求path路徑的,所以需要設置請求方式,可以不設置,因為默認為GET  
                      if (conn.getResponseCode() == 200) {// 判斷請求碼是否是200碼,否則失敗  
                          InputStream is = conn.getInputStream(); // 獲取輸入流  
                          byte[] data = readStream(is);   // 把輸入流轉(zhuǎn)換成字符數(shù)組  
                          json = new String(data);        // 把字符數(shù)組轉(zhuǎn)換成字符串  
                            
                          //數(shù)據(jù)形式:[{"id":1,"name":"小豬","age":22},{"id":2,"name":"小貓","age":23}]  
                          JSONArray jsonArray = new JSONArray(json); //數(shù)據(jù)直接為一個數(shù)組形式,所以可以直接 用android提供的框架JSONArray讀取JSON數(shù)據(jù),轉(zhuǎn)換成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);  
                          }  
                      }  
                
                      // ***********測試數(shù)據(jù)******************  
                      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數(shù)據(jù),
                   * 數(shù)據(jù)形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"小豬"},{"id":2,"name":"小貓"}]}
                   * @param path  網(wǎng)頁路徑
                   * @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對象,我們可以從網(wǎng)絡中獲取網(wǎng)頁數(shù)據(jù).  
                      conn.setConnectTimeout(5 * 1000);   // 單位是毫秒,設置超時時間為5秒  
                      conn.setRequestMethod("GET");       // HttpURLConnection是通過HTTP協(xié)議請求path路徑的,所以需要設置請求方式,可以不設置,因為默認為GET  
                      if (conn.getResponseCode() == 200) {// 判斷請求碼是否是200碼,否則失敗  
                          InputStream is = conn.getInputStream(); // 獲取輸入流  
                          byte[] data = readStream(is);   // 把輸入流轉(zhuǎn)換成字符數(shù)組  
                          String json = new String(data); // 把字符數(shù)組轉(zhuǎn)換成字符串  
                            
                            
                          //數(shù)據(jù)形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"小豬"},{"id":2,"name":"小貓"}]}  
                          JSONObject jsonObject=new JSONObject(json);     //返回的數(shù)據(jù)形式是一個Object類型,所以可以直接轉(zhuǎn)換成一個Object  
                          int page=jsonObject.getInt("page");  
                          String type=jsonObject.getString("type");  
                          Log.i("abc", "type:" + type + " |page:" + page);   //測試數(shù)據(jù)  
                            
                          JSONArray jsonArray = jsonObject.getJSONArray("hotels");//里面有一個數(shù)組數(shù)據(jù),可以用getJSONArray獲取數(shù)組  
                          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);  
                          }  
                      }  
                
                      // ***********測試數(shù)據(jù)******************  
                        
                      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數(shù)據(jù)
                   *數(shù)據(jù)形式:
                      {"name":"小豬",
                       "age":23,
                       "content":{"questionsTotal":2,
                                  "questions": [ { "question": "what's your name?", "answer": "小豬"},{"question": "what's your age", "answer": "23"}]
                                 }
                      }
                   * @param path  網(wǎng)頁路徑
                   * @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對象,我們可以從網(wǎng)絡中獲取網(wǎng)頁數(shù)據(jù).  
                      conn.setConnectTimeout(5 * 1000);   // 單位是毫秒,設置超時時間為5秒  
                      conn.setRequestMethod("GET");       // HttpURLConnection是通過HTTP協(xié)議請求path路徑的,所以需要設置請求方式,可以不設置,因為默認為GET  
                      if (conn.getResponseCode() == 200) {// 判斷請求碼是否是200碼,否則失敗  
                          InputStream is = conn.getInputStream(); // 獲取輸入流  
                          byte[] data = readStream(is);   // 把輸入流轉(zhuǎn)換成字符數(shù)組  
                          String json = new String(data); // 把字符數(shù)組轉(zhuǎn)換成字符串  
                            
                            
                          /*數(shù)據(jù)形式:
                              {"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);     //返回的數(shù)據(jù)形式是一個Object類型,所以可以直接轉(zhuǎn)換成一個Object  
                          String name=jsonObject.getString("name");         
                          int age=jsonObject.getInt("age");  
                          Log.i("abc", "name:" + name + " | age:" + age); //測試數(shù)據(jù)  
                            
                          JSONObject contentObject=jsonObject.getJSONObject("content");       //獲取對象中的對象  
                          String questionsTotal=contentObject.getString("questionsTotal");    //獲取對象中的一個值  
                          Log.i("abc", "questionsTotal:" + questionsTotal);   //測試數(shù)據(jù)  
                            
                          JSONArray contentArray=contentObject.getJSONArray("questions");     //獲取對象中的數(shù)組  
                          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);  
                          }  
                      }  
                
                      // ***********測試數(shù)據(jù)******************  
                        
                      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;  
                  }  
                    
                    
                    
                    
                  /**
                   * 把輸入流轉(zhuǎn)換成字符數(shù)組
                   * @param inputStream   輸入流
                   * @return  字符數(shù)組
                   * @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 姚先進 閱讀(279) | 評論 (0)編輯 收藏
           

          首先說一下Json數(shù)據(jù)的最基本的特點,Json數(shù)據(jù)是一系列的鍵值對的集合,和XML數(shù)據(jù)來比,Json數(shù)據(jù)的體積更加小,傳輸效率高,易解析,不過可讀性不高;

                因為這次要從服務器端得到Json數(shù)據(jù),并且通過解析之后把解析后的數(shù)據(jù)顯示在Android客戶端中,首先部署服務器端代碼(直接使用Jsp/Servlet):

                 構(gòu)造的Json數(shù)據(jù)如下:

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


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

               ①:數(shù)據(jù)構(gòu)造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的代碼(包括構(gòu)造Json數(shù)據(jù),沒有使用Json數(shù)據(jù)轉(zhuǎn)換方法)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直接訪問結(jié)果如下: 0_1330066556axYL.gif        至此服務器端代碼編碼完成,下面進行客戶端代碼編寫;    (二)客戶端(Person類,和展示數(shù)據(jù)的布局文件因為簡單省去)
                ①:獲取服務器端的Json數(shù)據(jù)并且解析的工具類JsonParse.java
            必要的需要導入的包省去  
          1. <span style="font-size:18px;">public class JsonParse {
          2.         /**
          3.          * 解析Json數(shù)據(jù)
          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中獲取字節(jié)數(shù)組
          24.          *
          25.          * @param urlPath
          26.          * @return 字節(jié)數(shù)組
          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,這里應該訪問局域網(wǎng)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解析成功之后數(shù)據(jù)
          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.                                 //初始化適配器,并且綁定數(shù)據(jù)
          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應用結(jié)果截圖:
          0_1330067381FcfP.gif
          Json數(shù)據(jù)解析服務器端加客戶端代碼.zip (75.08 KB, 下載次數(shù): 1309)



          1

          查看全部評分

          posted @ 2013-04-22 19:11 姚先進 閱讀(343) | 評論 (0)編輯 收藏
           
               摘要: 、利用HttpUrlConnection 1 /** 2 * 從指定的URL中獲取數(shù)組 3 * @param urlPath 4 * @return 5 * @throws Exception 6 */ 7 public static String readParse(String urlPath) throws Excep...  閱讀全文
          posted @ 2013-04-22 19:10 姚先進 閱讀(292) | 評論 (0)編輯 收藏
          僅列出標題  下一頁
           
          主站蜘蛛池模板: 丰宁| 绥棱县| 兴城市| 丹凤县| 新巴尔虎左旗| 天峨县| 西林县| 永定县| 平武县| 江孜县| 大荔县| 吴忠市| 汽车| 宁河县| 类乌齐县| 伊吾县| 邯郸市| 吴忠市| 大方县| 长宁县| 建瓯市| 格尔木市| 宽城| 沁阳市| 如皋市| 清镇市| 清流县| 沙河市| 栾川县| 旬邑县| 金华市| 克拉玛依市| 南部县| 高阳县| 方城县| 达日县| 吕梁市| 晋中市| 南召县| 邵阳县| 周口市|