Simple tutorial for Android-66th gun (server-side construction and server-side Json Data Interaction)

Source: Internet
Author: User

Simple tutorial for Android-66th gun (server-side construction and server-side Json Data Interaction)

After learning about Android for a while, I was very curious about the server and decided to conduct some research on the implementation of the server. Here I have implemented a simple small example to get the json data of the server, the example is simple and suitable for beginners to learn and use.

Server

First, we set up the server. The server uses the struct2 architecture. If you are not familiar with this architecture, you can take a moment to watch the relevant videos on MOOC. Here, we use myeclipse to implement the server.

Create a web project. here you need to introduce struct2. Click the newly created web project email-myeclipse option-project facets-> select struct2 for installation.

Take a look at the relevant code:

Struts. xml:

         
           
               
   
    index.jsp
                   
        
   


Web. xml:

 
   
  
   Test2
    
      
   
    struts2
       
   
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
     
    
      
   
    struts2
       
   
    *.action
     
  
 


The following is 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 attributes, ServletResponseAware {/*****/private static final long serialVersionUID =-response; private HttpServletRequest request; private HttpServletResponse response; private String format; public String getFormat () {return format;} 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
 
  
List = new ArrayList
  
   
(); Gson gson = new Gson (); Music m1 = new Music (); m1.setId (1); m1.setAuthor ("Jay Chou"); m1.setName ("grandma "); m1.setTime ("04:04"); list. add (m1); Music m2 = new Music (); m2.setId (2); m2.setAuthor ("Jay Chou"); m2.setName ("Half Orcs"); m2.setTime ("04:05 "); list. add (m2); Music m3 = new Music (); m3.setId (3); m3.setAuthor ("Jay Chou"); m3.setName ("wukeli"); m3.setTime "); list. add (m3); java. lang. reflect. type type = new com. google. gson. reflect. typeToken
   
    
> (){}. GetType (); // specify the type String beanListToJson = gson. toJson (list, type); // list is converted into a json string System. out. println ("GSON -->" + beanListToJson); try {response. setCharacterEncoding ("UTF-8"); this. response. getWriter (). write (beanListToJson);} catch (IOException e) {e. printStackTrace ();}}}
   
  
 


Music CLASS: (this class is also required in Android)

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;          }   } 


Right-click the project and choose run as> myeclipse server application:

 

Note: The port number for this project is 8888, and yayun indicates the local machine.

Enter http: // yayun: 8888/Test2/getjson. action in the address bar of the browser.

The following figure is displayed:

This indicates that the server is successfully built. In addition, the system uses the Gson jar package for json parsing. You must import the jar package by yourself. Download Gson and introduce it to the project. This jar package is also required for Android.

Mobile Terminal

Implementation on Mobile End using eclipse

First, 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
 
  
List = GsonUtil. getListFromJson (jString); System. out. println (list); if (list! = Null) {System. out. println (list); List
  
   
> 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
   
    
> GetAdapterData (List list) {List
    
     
> Data = new ArrayList
     
      
> (); For (int I = 0; I <list. size (); I ++) {Map
      
        Map = new HashMap
       
         (); Music music = (Music) list. get (I); map. put ("name", music. getName (); map. put ("author", music. getAuthor (); map. put ("time", music. getTime (); data. add (map);} return data;}/*** obtain the json String asynchronously * @ param url */public void getJson (final String url) {new Thread (new Runnable () {@ Overridepublic void run () {URL urlString; try {urlString = new URL (url); HttpURLConnection httpURLConnection = (HttpURLConnection) urlS Tring. openConnection (); httpURLConnection. setConnectTimeout (5000); 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
 
    getListFromJson(String json){          java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken
  
   >() {          }.getType();          Gson gson = new Gson();          List
   
      list  = gson.fromJson(json, type);          return list;     }  } 
   
  
 


The layout class is easy to write and you can download the source code on your own. Run the Android program:

Pay attention to network permissions when the operation fails.

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.