Android Easy Tutorial-66th gun (server-side build and server-side JSON data interaction)

Source: Internet
Author: User

have been learning Android for some time. The server side has a very deep curiosity, decided to the server side of the implementation of some research, here to implement a simple sample, to get the server side of the JSON data, the sample is very easy to learn from the beginning learning to use.

Server Side

First we build the server side, the server side uses the STRUCT2 architecture, the people who are unfamiliar with the architecture can take a little time to see the relevant video on the web, the server side is implemented with MyEclipse.

Create a new webproject. Here to introduce the struct2 correlation, by clicking on the new WebProject mail-"MyEclipse options-" Project facets-> Select Install Struct2 related to it.

Take a look at the relevant code:

Struts.xml:

<?xml version= "1.0" encoding= "GBK"?> <!  DOCTYPE struts public          "-//apache software foundation//dtd struts Configuration 2.0//en"          "/http Struts.apache.org/dtds/struts-2.0.dtd ">      <struts>          <package name=" struts2 "extends=" Struts-default "namespace="/">      <action name=" Getjson "class=" com.shao.action.JSONAction "method=" JSON " >       <result  name= "Success" >index.jsp</result>      </action>          </package>      </struts>  


Xml:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-app_3_0.xsd "version=" 3.0 ">  <display-name>test2</display-name >  <filter>    <filter-name>struts2</filter-name>    <filter-class> Org.apache.struts2.dispatcher.ng.filter.strutsprepareandexecutefilter</filter-class>  </filter>  <filter-mapping>    <filter-name>struts2</filter-name>    <url-pattern>*.action </url-pattern>  </filter-mapping></web-app>


Here are the Jsonaction.java:

Package com.shao.action;  Import java.io.IOException;  Import java.util.ArrayList;    Import java.util.List;  Import Javax.servlet.http.HttpServletRequest;    Import Javax.servlet.http.HttpServletResponse;  Import Org.apache.struts2.interceptor.ServletRequestAware;    Import Org.apache.struts2.interceptor.ServletResponseAware;  Import Com.google.gson.Gson;  Import Com.opensymphony.xwork2.ActionSupport;    Import Com.shao.domain.Music;      public class Jsonaction extends Actionsupport implements Servletrequestaware, Servletresponseaware {/**      * */private static final long serialversionuid = -3604892179657815531l;      private HttpServletRequest request;      Private HttpServletResponse response;      Private String format;      Public String GetFormat () {return format;      The public void SetFormat (String format) {this.format = format;  } @Override public void Setservletrequest (HttpServletRequest request) {        This.request = Request;      } @Override public void Setservletresponse (HttpServletResponse response) {this.response = response;          } public void json () {list<music> List = new arraylist<music> ();          Gson Gson = new Gson ();          Music M1 = new Music ();          M1.setid (1);          M1.setauthor ("Jay Chou");          M1.setname ("grandmother");          M1.settime ("04:04");          List.add (M1);          Music m2 = new Music ();          M2.setid (2);          M2.setauthor ("Jay Chou");          M2.setname ("Orcs");          M2.settime ("04:05");          List.add (m2);          Music m3 = new Music ();          M3.setid (3);          M3.setauthor ("Jay Chou");          M3.setname ("ukulele");          M3.settime ("02:55");          List.add (m3);  Java.lang.reflect.Type Type = new com.google.gson.reflect.typetoken<list<music>> () {}.gettype ();  Specifies the type String Beanlisttojson = Gson.tojson (List,type); List converted to JSON String System.out.println ("gson-->" +beanlisttojson);               try {response.setcharacterencoding ("UTF-8");            This.response.getWriter (). write (Beanlisttojson);            } catch (IOException e) {e.printstacktrace ();   }        }  }


Finally, the Music class: (This class is also required in Android programs)

Package com.shao.domain;    public class Music {            private Integer ID;            private String name;            Private String time;          Private String  author;          Public Integer getId () {              return ID;          }          public void SetId (Integer id) {              this.id = ID;          }          Public String GetName () {              return name;          }          public void SetName (String name) {              this.name = name;          }          Public String GetTime () {              return time;          }          public void SetTime (String time) {              this.time = time;          }          Public String Getauthor () {              return author;          }          public void Setauthor (String author) {              this.author = author;          }   


OK, the following choose project right: Run As->myeclipse Server application:

?

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity /center "/>

Note that the port of this project is selected by 8888,yayun to represent the native.

At this point in the browser address bar type: http://yayun:8888/Test2/getjson.action

Occurrences such as the following:

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity /center "/>

Describes the server-side build success.

In addition, this system JSON parsing used to Gson jar package, to own import Oh, download Gson introduced into the project, the Android side also need this jar package.

Mobile side

The mobile end is implemented with eclipse

The first is jsonclientactivity:

Package Com.test.demo;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.InputStream;import Java.io.inputstreamreader;import Java.net.httpurlconnection;import Java.net.malformedurlexception;import Java.net.url;import java.util.arraylist;import java.util.hashmap;import Java.util.list;import java.util.Map;import Com.example.testandroid.r;import Android.app.activity;import Android.os.bundle;import Android.os.Handler;import Android.os.message;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.Button ; Import Android.widget.listview;import Android.widget.simpleadapter;public class Jsonclientactivity extends Activity {Private Button update;private ListView listview;private String jsonresult;private Handler handler=new Handler () {public void Handlemessage (Android.os.Message msg) {jsonresult= (String) msg.obj;};}; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.main); update = (Button) Findviewbyid (r.id.update), ListView = (ListView) Findviewbyid (R.id.list); Update.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {String urlstr = "http://192.168.0.103:8888/Test2/ Getjson.action "; Getjson (URLSTR); String Jstring=jsonresult; list<music> list = Gsonutil.getlistfromjson (jstring); SYSTEM.OUT.PRINTLN (list); if (list! = null) {System.out.println (list); list<map<string, object>> data = Getadapterdata (list); Simpleadapter adapter = new Simpleadapter (jsonclientactivity.this, data, r.layout.list,new string[] {"Name", "Author", " Time "}, new int[] {r.id.name, r.id.author, r.id.time}); Listview.setadapter (adapter);}});} Private list<map<string, object>> getadapterdata (List list) {list<map<string, object>> data =  New arraylist<map<string, object>> (); for (int i = 0; i < list.size (); i++) {map<string, object> Map = New hashmap<string, object> (); Music music = (music) list.get (i); map. Put ("name", Music.getname ()), Map.put ("Author", Music.getauthor ()), Map.put ("Time", Music.gettime ());d Ata.add (map) ;} return data;} /** * Asynchronously gets the JSON string * @param URL */public void Getjson (final String URL) {New Thread (new Runnable () {@Overri depublic void Run () {URL Urlstring;try {urlstring = new URL (URL); HttpURLConnection httpurlconnection= (httpurlconnection) urlstring.openconnection (); Httpurlconnection.setconnecttimeout (+); Httpurlconnection.setdoinput (true); Httpurlconnection.setrequestmethod ("GET"); Httpurlconnection.connect (); InputStream inputstream= Httpurlconnection.getinputstream (); InputStreamReader inputstreamreader=new InputStreamReader (InputStream); BufferedReader bufferedreader=new BufferedReader (InputStreamReader); StringBuilder stringbuilder=new StringBuilder (); String Line;while ((Line=bufferedreader.readline ())!=null) {stringbuilder.append (line);} System.out.println (New String ()); Message message=new message (); Message.obj=new String (Stringbuilder.tostring ()); handler. sendMessage (message);}       catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();}              }}). Start (); } }


Then the tool class:

Package Com.test.demo;    Import Java.util.list;import Com.google.gson.Gson;    public class Gsonutil {      public  static  list<music>  Getlistfromjson (String json) {          Java.lang.reflect.Type Type = new com.google.gson.reflect.typetoken<list<music>> () {          }.gettype ();          Gson Gson = new Gson ();          list<music>  List  = Gson.fromjson (JSON, type);          return list;     }  


The layout class is very easy to write. Be able to download the source code yourself. To execute the Android program:

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity /center "/>

Perform unsuccessful attention to network permissions.

Source code Download:

Server Side

Android side

?

Welcome to follow me and my platform, thank you


?

?

Android Easy Tutorial-66th gun (server-side build and server-side JSON data interaction)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.