Android开发使用json实现服务器与客户端数据的交互功能示例
本文实例讲述了Android开发使用json实现服务器与客户端数据的交互功能。分享给大家供大家参考,具体如下:
第一步:写一个远程查询工具类,使用单例模式
/**
*查询远程服务器的工具
*@authorchen.lin
*
*/
publicclassQueryUtils{
//privatestaticfinalStringTAG="CommonUtils";
privatestaticQueryUtilsinstance;
privateSharedPreferencessp;
privateQueryUtils(Contextcontext){
sp=context.getSharedPreferences(Constant.CONFIG,Context.MODE_PRIVATE);
}
publicstaticQueryUtilsgetInstance(Contextcontext){
if(instance==null){
synchronized(QueryUtils.class){
if(instance==null){
instance=newQueryUtils(context);
}
}
}
returninstance;
}
/**
*请求服务器得到返回值
*
*@paramkeyword
*@return
*@throwsException
*/
publicStringqueryServer(Stringkeyword,StringreqType,Stringservlet)throwsException{
StringreturnValue=null;
//使用Map封装请求参数
Mapmap=newHashMap();
map.put("reqType",reqType);
map.put("localIP",sp.getString(Constant.NETIP,""));
if(!TextUtils.isEmpty(keyword)){
map.put("keyword",keyword);
}
Stringurl="http://"+sp.getString(Constant.NETURL,"")+"/ymerp/"+servlet;
returnValue=postRequest(url,map);
returnreturnValue;
}
}
/**
*请求远程服务器,并封装参数信息
*@paramurl
*@paramrawParams
*@return
*@throwsException
*/
publicstaticStringpostRequest(Stringurl,MaprawParams)throwsException{
//创建HttpPost对象。
HttpPostpost=newHttpPost(url);
//如果传递参数个数比较多的话可以对传递的参数进行封装
Listparams=newArrayList();
for(Stringkey:rawParams.keySet()){
//封装请求参数
params.add(newBasicNameValuePair(key,rawParams.get(key)));
}
//Logger.i(TAG,"params------------------->"+params);
//设置请求参数
post.setEntity(newUrlEncodedFormEntity(params,"UTF-8"));
HttpParamshttpParameters=newBasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,3000);
HttpConnectionParams.setSoTimeout(httpParameters,15000);
DefaultHttpClienthttpClient=newDefaultHttpClient(httpParameters);
//发送POST请求
HttpResponsehttpResponse=httpClient.execute(post);
//如果服务器成功地返回响应
Stringresult=null;
if(httpResponse.getStatusLine().getStatusCode()==200){
//获取服务器响应字符串
result=EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
Logger.i(TAG,"result-------->"+result);
}
returnresult;
}
第二步:使用软引用把远程得到的数据缓存到手机,如果服务器有数据更新,重新查询
/**
*使用这个需要注意,一切都必须与服务器上的字段一一对应,大小写一致为了保持一致,所有的实体都必须小写,远程数据库上的字段也得小写
*
*@authorchen.lin
*
*/
@SuppressWarnings({"unchecked","deprecation"})
publicclassBaseManager{
privatestaticBaseManagerinstance;
privateQueryUtilsqueryUtils;
privateSharedPreferencessp;
privateContextcontext;
privateBaseManager(Contextcontext){
this.context=context;
queryUtils=QueryUtils.getInstance(context);
sp=context.getSharedPreferences(Constant.CONFIG,Context.MODE_PRIVATE);
}
publicstaticBaseManagergetInstance(Contextcontext){
if(instance==null){
synchronized(BaseManager.class){
if(instance==null){
instance=newBaseManager(context);
}
}
}
returninstance;
}
privatestaticMap>LISTCACHE;//
static{
//16M,如果不足<16M(模拟器)
//32M,真机
if(MemoryManager.hasAcailMemory()){
LISTCACHE=newHashMap>();
}else{
LISTCACHE=newSoftMap>();
}
}
privatestaticMapDOCCACHE;//
static{
//16M,如果不足<16M(模拟器)
//32M,真机
if(MemoryManager.hasAcailMemory()){
DOCCACHE=newHashMap();
}else{
DOCCACHE=newSoftMap();
}
}
publicListqueryListByCache(Classclazz,Stringkey,StringreqType,Stringservlet)throwsException{
Listlist=null;
//一旦创建过,重用
//判断是否创建了——曾经创建过的界面需要存储
if(LISTCACHE!=null&&LISTCACHE.containsKey(key)){
//创建了,重用
list=(List)LISTCACHE.get(key);
if(list==null||list.isEmpty()){
//有时候查询的数据过大,viewcache中放置不了那么多数据,就会被垃圾回收站回收,得重新查询远程数据库
list=getListFromServer(clazz,key,reqType,servlet);
LISTCACHE.put(key,list);
}
}else{
//否则,创建
list=getListFromServer(clazz,key,reqType,servlet);
LISTCACHE.put(key,list);
}
returnlist;
}
publicListgetListFromServer(Classclazz,Stringkeyword,StringreqType,Stringservlet)
throwsException{
Listlist=newArrayList();
StringreturnValue=queryUtils.queryServer(keyword,reqType,servlet);
if(!TextUtils.isEmpty(returnValue)){
Gsongson=newGson();
JsonParserjsonParser=newJsonParser();
JsonArrayjsonArray=jsonParser.parse(returnValue).getAsJsonArray();
if(jsonArray!=null){
Tt=null;
//循环记录数(多少条)
for(JsonElementjson:jsonArray){
if(json!=null){
t=gson.fromJson(json,clazz);
list.add(t);
}
}
}
}
returnlist;
}
publicTqueryDocByCache(Classclazz,Stringkey,StringreqType,Stringservlet)throwsException{
Tt=null;
//一旦创建过,重用
//判断是否创建了——曾经创建过的界面需要存储
if(DOCCACHE!=null&&DOCCACHE.containsKey(key)){
//创建了,重用
t=(T)DOCCACHE.get(key);
if(t==null){
//有时候查询的数据过大,viewcache中放置不了那么多数据,就会被垃圾回收站回收,得重新查询远程数据库
t=getDocFromServer(clazz,key,reqType,servlet);
DOCCACHE.put(key,t);
}
}else{
//否则,创建
t=getDocFromServer(clazz,key,reqType,servlet);
DOCCACHE.put(key,t);
}
returnt;
}
publicTgetDocFromServer(Classclazz,Stringkeyword,StringreqType,Stringservlet)throwsException{
StringreturnValue=queryUtils.queryServer(keyword,reqType,servlet);
if(!TextUtils.isEmpty(returnValue)){
Gsongson=newGson();
Tt=gson.fromJson(returnValue,clazz);
returnt;
}
returnnull;
}
/**
*查询判断客户是否已经添加
*
*@paramkeyword
*@paramdialog
*@return
*@throwsException
*/
publicbooleanisAccountExist(Stringkeyword)throwsException{
StringreturnValue=queryUtils.queryServer(keyword,"queryaccountExist","AccountDocumentServlet");
if(!TextUtils.isEmpty(returnValue)&&"true".equals(returnValue.trim())){
returntrue;
}
returnfalse;
}
/**
*更新服务器上的数据
*@paramcontext
*@paramparams
*@paramservlet
*@return
*@throwsException
*/
publicvoidupdateServer(finalRequestParamsparams,Stringservlet){
AsyncHttpClientclient=newAsyncHttpClient();
Stringurl="http://"+sp.getString(Constant.NETURL,"")+"/ymerp/"+servlet;
client.post(url,params,newAsyncHttpResponseHandler(){
@Override
publicvoidonSuccess(intstatusCode,Header[]headers,byte[]responseBody){
try{
StringreturnValue=newString(responseBody);
JSONObjectjsonObject=newJSONObject(returnValue);
if("success".equalsIgnoreCase(jsonObject.getString("result"))){
if(params.has("sendread")){
Logger.i("update","更新成功!");
}else{
Toast.makeText(context,"更新成功!",Toast.LENGTH_SHORT).show();
}
}else{
if(params.has("sendread")){
Logger.i("update","更新失败!");
}else{
Toast.makeText(context,"更新失败!",Toast.LENGTH_SHORT).show();
}
}
}catch(JSONExceptione){
e.printStackTrace();
Toast.makeText(context,"json格式数据有误!",Toast.LENGTH_SHORT).show();
}
}
@Override
publicvoidonFailure(intstatusCode,Header[]headers,byte[]responseBody,Throwableerror){
Toast.makeText(context,"网络错误!错误信息:"+error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
第三步:使用事例-客户信息查询
publicclassSearchActivityextendsCommonActivityimplementsOnClickListener{
privateBaseManagermManager;
privateListViewmListView;
privateButtonmBtnQuery;
privateQueryAccountAdaptermAdapter;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
//初始化组件
initView();
//进出动画效果
overridePendingTransition(R.anim.push_bottom_in,R.anim.push_bottom_out);
}
}
privatevoidinitView(){
mManager=BaseManager.getInstance(this);
mListView=(ListView)findViewById(R.id.lv_search);
mButton=(Button)findViewById(R.id.bt_query);
mButton.setOnClickListener(this);
mAdapter=newQueryAccountAdapter(this,mAccounts);
mListView.setAdapter(mAdapter);
}
@Override
publicvoidonClick(Viewv){
if(v==mBtnQuery){
mAccounts=mManager.getListFromServer(Account.class,query,"queryAccountByKey","QueryServlet");
}
}
}
客户实体类:
/**
*客户信息
*
*@authorchen.lin
*@createtime20150217
*/
publicclassAccountimplementsSerializable{
/**
*
*/
privatestaticfinallongserialVersionUID=1L;
privateStringid;
privateStringsname;//客户名称
privateStringscode;//客户编码
privateStringcontact;//联系人
privateStringidcontact;//联系人id
privateStringemtype;//客户分类
privateStringxsly;//客户来源
privateStringxsbh;//线索编号
privateStringxs;//线索名称
privateStringidlead;//线索id
privateStringleadscode;
privateStringidzh;//相关展会
privateStringsrcpath;//来源途径
privateStringemindustry;//行业
privateStringidarea;//行政区域
privateStringsaddress;//客户地址
privateStringshdz;//收货地址
privateStringcclx;//乘车路线
privateStringspostcode;//邮编
privateStringstel;//手机
privateStringtelcode;//电话号码
privateStringsfax;//传真
privateStringsemail;//邮箱
privateStringswebsite;//站点主页
privateStringiddep;//负责人部门
privateStringidowner;//负责人
privateStringcreated;//新建时间
privateStringcreatedby;//新建人
privateStringupdated;//编辑时间
privateStringupdatedby;//编辑人
publicStringgetIdcontact(){
returnidcontact;
}
publicvoidsetIdcontact(Stringidcontact){
this.idcontact=idcontact;
}
publicStringgetContact(){
returncontact;
}
publicvoidsetContact(Stringcontact){
this.contact=contact;
}
publicStringgetIdlead(){
returnidlead;
}
publicvoidsetIdlead(Stringidlead){
this.idlead=idlead;
}
publicStringgetLeadscode(){
returnleadscode;
}
publicvoidsetLeadscode(Stringleadscode){
this.leadscode=leadscode;
}
publicStringgetTelcode(){
returntelcode;
}
publicvoidsetTelcode(Stringtelcode){
this.telcode=telcode;
}
publicStringgetId(){
returnid;
}
publicvoidsetId(Stringid){
this.id=id;
}
publicStringgetSname(){
returnsname;
}
publicvoidsetSname(Stringsname){
this.sname=sname;
}
publicStringgetScode(){
returnscode;
}
publicvoidsetScode(Stringscode){
this.scode=scode;
}
publicStringgetEmtype(){
returnemtype;
}
publicvoidsetEmtype(Stringemtype){
this.emtype=emtype;
}
publicStringgetXsly(){
returnxsly;
}
publicvoidsetXsly(Stringxsly){
this.xsly=xsly;
}
publicStringgetXsbh(){
returnxsbh;
}
publicvoidsetXsbh(Stringxsbh){
this.xsbh=xsbh;
}
publicStringgetXs(){
returnxs;
}
publicvoidsetXs(Stringxs){
this.xs=xs;
}
publicStringgetIdzh(){
returnidzh;
}
publicvoidsetIdzh(Stringidzh){
this.idzh=idzh;
}
publicStringgetSrcpath(){
returnsrcpath;
}
publicvoidsetSrcpath(Stringsrcpath){
this.srcpath=srcpath;
}
publicStringgetEmindustry(){
returnemindustry;
}
publicvoidsetEmindustry(Stringemindustry){
this.emindustry=emindustry;
}
publicStringgetIdarea(){
returnidarea;
}
publicvoidsetIdarea(Stringidarea){
this.idarea=idarea;
}
publicStringgetSaddress(){
returnsaddress;
}
publicvoidsetSaddress(Stringsaddress){
this.saddress=saddress;
}
publicStringgetShdz(){
returnshdz;
}
publicvoidsetShdz(Stringshdz){
this.shdz=shdz;
}
publicStringgetCclx(){
returncclx;
}
publicvoidsetCclx(Stringcclx){
this.cclx=cclx;
}
publicStringgetSpostcode(){
returnspostcode;
}
publicvoidsetSpostcode(Stringspostcode){
this.spostcode=spostcode;
}
publicStringgetStel(){
returnstel;
}
publicvoidsetStel(Stringstel){
this.stel=stel;
}
publicStringgetSfax(){
returnsfax;
}
publicvoidsetSfax(Stringsfax){
this.sfax=sfax;
}
publicStringgetSemail(){
returnsemail;
}
publicvoidsetSemail(Stringsemail){
this.semail=semail;
}
publicStringgetSwebsite(){
returnswebsite;
}
publicvoidsetSwebsite(Stringswebsite){
this.swebsite=swebsite;
}
publicStringgetIddep(){
returniddep;
}
publicvoidsetIddep(Stringiddep){
this.iddep=iddep;
}
publicStringgetIdowner(){
returnidowner;
}
publicvoidsetIdowner(Stringidowner){
this.idowner=idowner;
}
publicStringgetCreated(){
returncreated;
}
publicvoidsetCreated(Stringcreated){
this.created=created;
}
publicStringgetCreatedby(){
returncreatedby;
}
publicvoidsetCreatedby(Stringcreatedby){
this.createdby=createdby;
}
publicStringgetUpdated(){
returnupdated;
}
publicvoidsetUpdated(Stringupdated){
this.updated=updated;
}
publicStringgetUpdatedby(){
returnupdatedby;
}
publicvoidsetUpdatedby(Stringupdatedby){
this.updatedby=updatedby;
}
publicAccount(Stringid,Stringsname,Stringscode,Stringidowner){
this.id=id;
this.sname=sname;
this.scode=scode;
this.idowner=idowner;
}
publicAccount(Stringid,Stringsname,Stringscode,Stringemtype,Stringxsly,Stringxsbh,Stringxs,
Stringidzh,Stringsrcpath,Stringemindustry,Stringidarea,Stringsaddress,Stringshdz,Stringcclx,
Stringspostcode,Stringstel,Stringsfax,Stringsemail,Stringswebsite,Stringiddep,Stringidowner,
Stringcreated,Stringcreatedby,Stringupdated,Stringupdatedby){
this.id=id;
this.sname=sname;
this.scode=scode;
this.emtype=emtype;
this.xsly=xsly;
this.xsbh=xsbh;
this.xs=xs;
this.idzh=idzh;
this.srcpath=srcpath;
this.emindustry=emindustry;
this.idarea=idarea;
this.saddress=saddress;
this.shdz=shdz;
this.cclx=cclx;
this.spostcode=spostcode;
this.stel=stel;
this.sfax=sfax;
this.semail=semail;
this.swebsite=swebsite;
this.iddep=iddep;
this.idowner=idowner;
this.created=created;
this.createdby=createdby;
this.updated=updated;
this.updatedby=updatedby;
}
publicAccount(){
super();
}
}
第四步:服务器端queryAccountByKey就是从客户端传过来的值
/**
*
*@authorchen.lin
*/
publicclassQueryServletextendsHttpServlet{
@Override
protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
processRequest(request,response);
}
@Override
protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriterout=response.getWriter();
StringreqType=request.getParameter("reqType");
StringlocalIP=request.getParameter("localIP");
EJBClientLocal.setServerip(localIP);
/**
*根据关键字查询服务单
*/
if(reqType!=null&&"queryAccountByKey".equalsIgnoreCase(reqType)){
//根据查询关键字查找对应用户列表
Stringkeyword=request.getParameter("keyword");
System.out.println("keyword----------------------:"+keyword);
try{
Listlist=EJBClientLocal.getMetaCRMIntegratedSessionBeanLocal().queryAccountByKey(keyword);
System.out.println("queryAccountByKeylist:"+list);
if(list!=null){
JSONArrayjson=JSONArray.fromObject(list);
//输出响应
out.println(json.toString());
out.flush();
}
}catch(Exceptionex){
System.out.println("queryAccountByKeyerror:"+ex.getMessage());
}
}
}
@Override
publicStringgetServletInfo(){
return"Shortdescription";
}
}
第五步:查询数据库
@Stateless
publicclassMetaCRMIntegratedSessionBeanimplementsMetaCRMIntegratedSessionBeanRemote,MetaCRMIntegratedSessionBeanLocal{
@Resource
SessionContextctx;
@PersistenceContext(unitName="meta_crm_ejbPU")
privateEntityManagerem;
privateDBMSqlServer2005dbm=null;
privateStatementstatement=null;
privatePreparedStatementpStatement=null;
SimpleDateFormatyyyymmdd=newSimpleDateFormat("yyyy-MM-dd");
@AroundInvoke
publicObjectlog(InvocationContextctx)
throwsException{
StringclassName=ctx.getTarget().getClass().getName();
StringmothodName=ctx.getMethod().getName();
Stringtarget=className+"."+mothodName+"()";
System.out.println("开始调用"+target+"方法");
longstart=System.currentTimeMillis();
try{
ObjectlocalObject1=ctx.proceed();
longtime;
returnlocalObject1;
}catch(Exceptione){
returnnull;
}finally{
longtime=System.currentTimeMillis()-start;
System.out.print(target+"方法执行完毕用时"+time+"ms");
}
}
/**
*查询客户信息
*@paramkeyword
*@return
*/
publicListqueryAccountByKey(Stringkeyword){
Listlist=newArrayList();
Stringsql="selectacc.id,acc.sname,acc.scode,"
+"con.snameascontact,emp1.snameascreatedby,acc.created,acc.saddress,con.id"
+"fromaccountacc"
+"leftjoinorg_employeeemp1onemp1.id=acc.createdby"//申请人名称
+"leftjoincontactcononacc.id=con.idaccount"//联系人
+"where1=1";
if(keyword!=null){
System.out.println("keyword----------------------->"+keyword);
sql+="andacc.snamelike'%"+keyword+"%'";
sql+="oremp1.snamelike'%"+keyword+"%'";
}
sql+="orderbyacc.createddesc";
System.out.println("sql----------------------->"+sql);
Connectionconn=getConn();
ResultSetrs=null;
Statementst=null;
try{
st=conn.createStatement();
rs=st.executeQuery(sql);
SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-ddhh:mm:ss");
while(rs.next()){
JSONObjectjsonObject=newJSONObject();
jsonObject.put("id",rs.getObject(1)!=null?rs.getObject(1):"");
jsonObject.put("sname",rs.getObject(2)!=null?rs.getObject(2):"");
jsonObject.put("scode",rs.getObject(3)!=null?rs.getObject(3):"");
jsonObject.put("contact",rs.getObject(4)!=null?rs.getObject(4):"");
jsonObject.put("createdby",rs.getObject(5)!=null?rs.getObject(5):"");
setTime(rs,sdf,jsonObject,"created",6);
jsonObject.put("saddress",rs.getObject(7)!=null?rs.getObject(7):"");
jsonObject.put("idcontact",rs.getObject(8)!=null?rs.getObject(8):"");
list.add(jsonObject);
}
}catch(SQLExceptionex){
ex.printStackTrace();
}finally{
dbm.closeConn();
}
returnlist;
}
}
PS:这里再为大家推荐几款比较实用的json在线工具供大家参考使用:
在线JSON代码检验、检验、美化、格式化工具:
http://tools.jb51.net/code/json
JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat
在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson
json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.jb51.net/code/jsoncodeformat
C语言风格/HTML/CSS/json代码格式化美化工具:
http://tools.jb51.net/code/ccode_html_css_json
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android操作json格式数据技巧总结》、《Android数据库操作技巧总结》、《Android编程之activity操作技巧总结》、《Android文件操作技巧汇总》、《Android开发入门与进阶教程》、《Android资源操作技巧汇总》、《Android视图View技巧总结》及《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。