Android uses json for network data exchange

Source: Internet
Author: User

As a lightweight data exchange format, JSON is popular with its advantages such as easy reading and writing, easy resolution, and fast transmission speed. Recently, I learned how to retrieve data from the service end on Android, and Json is useful. Well, let's start with the topic.

1. Prepare the server

First, we need a server. I use Tomcat. I will not describe the installation process of Tomcat here. The server configuration process is as follows.

We can find the server in File-new-other, next and find tomcat7.0 in Apache. Here I change the server name to Myserve and click finish.

 

After completing the appeal step, you can see that the Servers project appears in Package Explorer. There is a Myserver-config in it, and this is the server I previously configured.

Step 2. Create a Web project. Find the Dynamic web Project in new-other-Web and click next. Here I name the Project ServletText. Remember to change the Target runtime to Tomcat7.0.

Don't rush to finish. After you click "next" twice, you can see that a box is not checked. It indicates whether to generate the web. for xml, you can select whether or not to meet the actual needs of the project. We will ignore it here and click fiish.

In this way, we can find the SerletText project in Package Explorer. In src, we first set up a Package com. example. servlet, and how to prepare the web data. Let's take a look at my project architecture.

First, we need to import some jar packages of json and servlet. The json jar package can be downloaded from the Internet. The servlet jar package can first find the Tomcat installation folder, which can be directly found in Tomcat's libs.

The code for creating a User class is very simple.

User 1 package com. example. servlet; 2 3 public class User {4 5 private String name; 6 private int age; 7 public User () {} 8 public String getName () {9 return name; 10} 11 public void setName (String name) {12 this. name = name; 13} 14 public int getAge () {15 return age; 16} 17 public void setAge (int age) {18 this. age = age; 19} 20 21 22}

 

How can we create another Servlet class named ServletDemo. The Code is as follows.

Servletdemo 1 package com. example. servlet; 2 3 import java. io. IOException; 4 import java. io. printWriter; 5 import java. util. arrayList; 6 import java. util. list; 7 8 import javax. servlet. servletException; 9 import javax. servlet. annotation. webServlet; 10 import javax. servlet. http. httpServlet; 11 import javax. servlet. http. httpServletRequest; 12 import javax. servlet. http. httpServletResponse; 13 14 import net. sf. json. JSONArray; 15 import net. sf. json. JSONObject; 16 17 18 @ WebServlet ("/Servletdemo") 19 public class Servletdemo extends HttpServlet {20 private static final long serialVersionUID = 1L; 21 private List <User> list; 22 23 public Servletdemo () {24 super (); 25 // TODO Auto-generated constructor stub26} 27 28 protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {29 // TODO Auto-generated method stub30 response. setContentType ("text/plain"); 31 response. setCharacterEncoding ("UTF-8"); 32 PrintWriter printWriter = response. getWriter (); // print data on the Web end with PrintWriter 33 34 setuser (); 35 JSONArray array = new JSONArray (); 36 for (User object: list) 37 {38 JSONObject jsonObject = new JSONObject (); 39 try 40 {41 jsonObject. put ("name", object. getName (); 42 jsonObject. put ("age", object. getAge (); 43 44} 45 catch (Exception e) 46 {47 // TODO: handle exception48 49} 50 array. add (jsonObject); 51 52} 53 printWriter. println (array. toString (); 54 printWriter. flush (); 55 printWriter. close (); 56} 57/** Add the User object to the list */58 private void setuser () 59 {60 list = new ArrayList <User> (); 61 for (int I = 0; I <3; I ++) 62 {63 User user = new User (); 64 user. setName ("Zhang San" + I); 65 user. setAge (I * 10); 66 list. add (user); 67} 68 69} 70 71 protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {72 // TODO Auto-generated method stub73 doGet (request, request, response); 74} 75 76}

After you have prepared these items, you will have to deploy the ServletDemo on the server. Right-click ServletDemo (not the entire project of ServletText), run as -- run on server, and then click next-finish. You can see that the content has been printed on http: // localhost: 8080/ServletText/Servletdemo. Now, the server is ready.

2. Android receives and parses Json

First, we create an Android project named JsonAnalysis. Here we will do some easy-to-forget things first.

Add the network access permission to AndroidManifest.

    <uses permissionandroid:name="android.permission.INTERNET"/>

Import the following jar package in lib.

After completing these steps, we start to make the layout. The layout is also quite simple. Just put a Textview in.

<?xml version= "1.0"  encoding= "utf-8" ?>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"       android:orientation="vertical"       android:layout_width="fill_parent"       android:layout_height="fill_parent" >       <TextView android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/text"/>      </LinearLayout>  

Next we will start to implement the function. I wrote a tool-type HttpUtils here, because I do not have any web basics, it takes a lot of effort here. In this class, you can also set something like the network timeout parameter, but I skipped it and only did some necessary work. In addition, the variable length string StringBuilder is used to return data.

1 package com. example. jsonanalysis; 2 3 import java. io. bufferedReader; 4 import java. io. inputStreamReader; 5 6 import org. apache. http. httpEntity; 7 import org. apache. http. httpResponse; 8 import org. apache. http. client. httpClient; 9 import org. apache. http. client. methods. httpGet; 10 import org. apache. http. impl. client. defaultHttpClient; 11 12 13 public class HttpUtils {14 15 16 17 public static String ge TData (String url) throws Exception {18 19 20 StringBuilder stb = new StringBuilder (); 21 HttpClient httpClient = new DefaultHttpClient (); 22 HttpGet get = new HttpGet (url ); 23 HttpResponse httpResponse = httpClient.exe cute (get); 24 HttpEntity httpEntity = httpResponse. getEntity (); 25 26 if (httpEntity! = Null) {27 28 BufferedReader reader = new BufferedReader (new InputStreamReader (httpEntity. getContent (); 29 30 String line = null; 31 32 while (line = reader. readLine ())! = Null) {33 34 stb. append (line); 35 36} 37 38 return stb. toString (); 39 40} 41 42 return null; 43} 44}HttpUtils

At last, you need to pay attention to some small details in the main activity.

1. Access the local address.

Many people say that the access backend address is not 127.0.0.2, but 10.0.2.2. In fact, this is not the case. I did not understand this very well. I tried both of them at the beginning and found that none of them worked. Then, enter ipconfig in cmd to find the correct access address. The access address here is http: // 192.168.2.4: 8080/ServletText/Servletdemo.

2. Data Acquisition

After Android, you cannot initiate network requests in the main thread. You can use asynchronous requests or start another thread. Here is another thread in the main thread.

New Thread (new Runnable () {@ Override public void run () {// code for getting data}). start ();

The following is the main activity code.

1 package com. example. jsonanalysis; 2 3 import org. json. JSONArray; 4 import org. json. JSONObject; 5 6 import android. OS. bundle; 7 import android. app. activity; 8 import android. view. menu; 9 import android. widget. textView; 10 11 public class MainActivity extends Activity {12 13 private TextView textview; 14 private static String url = "http: // 192.168.2.4: 8080/ServletText/Servletdemo "; 15 @ Override16 protected void onCreate (Bundle savedInstanceState) {17 super. onCreate (savedInstanceState); 18 setContentView (R. layout. activity_main); 19 textview = (TextView) findViewById (R. id. text); 20 new Thread (new Runnable () {21 22 @ Override23 public void run () {24 // TODO Auto-generated method stub25 try {26 String str1 = HttpUtils. getData (url); 27 StringBuilder str2 = new StringBuilder (); 28 JSONArray array = new JSONArray (str1); 29 for (int I = 0; I <array. length (); I ++) 30 {31 JSONObject obj = array. getJSONObject (I); 32 str2.append ("age :"). append (obj. getInt ("age ")). append (""); 33 str2.append ("name :"). append (obj. getString ("name ")). append ("\ n"); 34 str2.append ("---------------------- \ n"); 35} 36 textview. setText (str2.toString (); 37 38} catch (Exception e) 39 {40 // TODO Auto-generated catch block41 e. printStackTrace (); 42 43} 44} 45 }). start (); 46} 47 48 @ Override49 public boolean onCreateOptionsMenu (Menu menu) {50 // Inflate the menu; this adds items to the action bar if it is present.51 getMenuInflater (). inflate (R. menu. main, menu); 52 return true; 53} 54 55}Main-activity

The following figure shows that the data has been obtained successfully.

Hope to help some people who are learning this and have the same problem.

 

 

 

 

 

 

 

 

 

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.