How to use Android to implement interface real information in the message board display _android

Source: Internet
Author: User
Tags http request stub stringbuffer

Below through the illustrated way to share the following how to use the Android interface real information display in the message board.

See the title, as the name suggests, I just talk to you today about how to implement the display of interface information, excluding the addition of information.

Interface Help Documentation: HTTP://API.WZHOSPITAL.CN/MSG/HELP

According to the view interface document, we can know some information structure inside the interface.

Of course, to see the specific information, is through this link: http://api.wzhospital.cn/MSG/api/Message/GetList

Obtain the following information to verify the correctness of the display.

<messages xmlns:i= "http://www.w3.org/2001/XMLSchema-instance" xmlns= "http://schemas.datacontract.org/2004/07/ Lyb. Models "> <Data> <Message> <Content> My first default message </Content> <createtime>2015-07-30 08:29:19</createtime> <Messager> Lin Hao </Messager> <MessagerAge>22</MessagerAge> < messagersex> women </MessagerSex> <Receiver> Lin Ling </Receiver> </Message> <Message> < content> My second default message </Content> <createtime>2015-07-30 08:31:19</createtime> <Messager> Lin Chi-ling </Messager> <MessagerAge>18</MessagerAge> <MessagerSex> Women </MessagerSex> <receiver
> Andy Lau </Receiver> </Message> <Message> <Content> My third default message my third default message my third default message my third default message my third default message my third. My third default message my third default message my third default message my third default message my third default message </ Content> <createtime>2015-07-30 08:33:19</createtime> <Messager> Lin Hao </Messager> < Messagerage>22</messagerage>
<MessagerSex> Simon </MessagerSex> <Receiver> Lin Ling </Receiver> </Message> <Message> <Content>dd</Content> <createtime>2015-07-30 16:35:57</createtime> <messager>h</ messager> <MessagerAge>0</MessagerAge> <MessagerSex>nn</MessagerSex> <Receiver> mm</receiver> </Message> <Message> <Content>content</Content> <CreateTime> 2015-07-30 16:37:49</createtime> <Messager>me</Messager> <messagerage>18</messagerage > <MessagerSex>male</MessagerSex> <Receiver>you</Receiver> </Message> <message > <Content>12</Content> <createtime>2015-07-30 16:52:42</createtime> <messager>sk </Messager> <MessagerAge>0</MessagerAge> <MessagerSex>le</MessagerSex> <receiver >kd</Receiver> </Message> <Message> <Content>content</Content>; createtime>2015-07-30 17:05:32</createtime> <Messager>me</Messager> <MessagerAge>0< /messagerage> <MessagerSex>youe</MessagerSex> <Receiver>dddd</Receiver> </message > </Data> </Messages>

First of all, I would first give you a look at the interface Effect chart (typesetting ugly, we understand).



The first step: First, the entire page is the layout.

This page consists of two parts: Activity_main.xml, which contains only one listview. Second: Rewrite a list_message.xml.


                                              activity_main.xml                                                                                                         List_message.xml

about why rewriting an. xml file is because the ListView itself is more complex, overriding a handy reference display.

Step two: According to the interface document, establish entity classes.


Click Get api/message/getlist to obtain the interface information, because I am using JSON format, I only intercept this piece of code.


Based on the information analysis, I created a Message.java entity class.

Package Com.example.message.model; Import Android.

r.string;
 public class Message {private String content;
 Private String Creatime;
 Private String Messager;
 Private String messagerage;
 Private String Messagersex;
 
 Private String reciver;
 Public String getcontent () {return content;
 public void SetContent (String content) {this.content=content;
 Public String Getcreatime () {return creatime;
 public void Setcreatime (String creatime) {this.creatime=creatime;
 Public String Getmessager () {return messager;
 public void Setmessager (String messager) {This.messager=messager;
 Public String Getmessagerage () {return messagerage;
 public void Setmessagerage (String messagerage) {this.messagerage=messagerage;
 Public String Getmessagersex () {return messagersex;
 public void Setmessagersex (String messagersex) {this.messagersex=messagersex;
 Public String Getreceiver () {return reciver; public void Setreceiver (String reCiver) {this.reciver=reciver; Public String ToString () {return "content:" +content+ ", Creatime:" +creatime+ ", Messager:" +messager+ ", Messagerage:" +
 Messagerage+ ", Messagersex:" +messagersex+ ", Reciver:" +reciver;

 }
}

Step three: What we need to do is get the interface data and parse (I write it in Mainactivity.java) it, then we need to create a new class, which I name Httpdata.java. Its function is to get the content in the interface. The code is as follows:

Package com.example.message;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;

Import Java.io.InputStreamReader;
Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import org.apache.http.client.ClientProtocolException;
Import org.apache.http.client.HttpClient;
Import Org.apache.http.client.methods.HttpGet;
Import Org.apache.http.client.methods.HttpPost;
Import org.apache.http.impl.client.DefaultHttpClient;

Import Org.apache.http.params.HttpParams; public class Httpdata {private httpclient client;//define HTTP a client private HttpResponse reponse;//define an HTTP response private HTTP Entity entity;//defines an HTTP entity private InputStream in;//defines an input flow private BufferedReader reader;//defines a character stream; private String Buffer data = new StringBuffer ("");//define an empty string buffer; private string url = "Http://api.wzhospital.cn/MSG/api/Message/GetLis
 T ";
 Private String url1= "HTTP://API.WZHOSPITAL.CN/MSG/API/MESSAGE/ADD";
 Private HttpGet Get;//get: Requested data with HTTP request hair past
 Public StringBuffer GetData () {//This method obtains the textual content of the interface and return the client = new Defaulthttpclient () in the form of a stream of characters; get = new HttpGet (URL);//url directed try {httpparams params = new Httpparams () {public Httpparams setparameter (strin
  G arg0, Object arg1) {//TODO auto-generated method stub return null;
  Httpparams Setlongparameter (String arg0, long arg1) {//TODO auto-generated method stub return null;
  Httpparams Setintparameter (String arg0, int arg1) {//TODO auto-generated method stub return null; Httpparams Setdoubleparameter (String arg0, double arg1) {//TODO auto-generated method stub return
  Null Httpparams Setbooleanparameter (String arg0, Boolean arg1) {//TODO auto-generated method stub return
  Null
  public boolean removeparameter (String arg0) {//TODO auto-generated method stub return false; public boolean isparametertrue (String arg0) {//TODO auto-generated method sTub return false;
  public boolean isparameterfalse (String arg0) {//TODO auto-generated method stub return false;
  The public Object getparameter (String arg0) {//TODO auto-generated the method stub return null;
  Public long Getlongparameter (String arg0, long arg1) {//TODO auto-generated a stub return 0;
  public int Getintparameter (String arg0, int arg1) {//TODO auto-generated a stub return 0;
  Public double Getdoubleparameter (String arg0, double arg1) {//TODO auto-generated a stub return 0; public boolean getbooleanparameter (String arg0, Boolean arg1) {//TODO auto-generated a stub return FAL
  Se
  Public httpparams Copy () {//TODO auto-generated method stub return null;
  
  }
  }; Reponse = Client.execute (GET)//EXECUTE client get operation entity = Reponse.getentity ();//Fetch response is instance in = Entity.getcontent ();//Fetch the text in the instance This content reader = new BufferedReader (new InputStreamReader (in));Read the character stream string line = "";
  while (line = Reader.readline ())!= null) {data.append (line);
  
 } return data;
 catch (Clientprotocolexception e) {//TODO auto-generated catch block E.printstacktrace ();
 catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
 } return data;

 }
}

Step Fourth: Encapsulate the Data collection (ListView), drawing from the view, where data adapter drawing is used.

The code is as follows:

Package com.example.message;
Import java.util.List;

Import Java.util.zip.Inflater;

Import Com.example.message.model.Message;
Import Android.content.Context;
Import Android.view.LayoutInflater;
Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.widget.BaseAdapter;
Import Android.widget.RelativeLayout;

Import Android.widget.TextView;
 public class DataAdapter extends baseadapter{private list<message> messages;
 
 private context;
 Private TextView v_content;
 Private TextView V_time;
 Private TextView V_messger;
 Private TextView v_messgerage;
 Private TextView V_messgersex;
 
 Private TextView V_receiver;
 Public DataAdapter (list<message> messages) {this.messages = messages;
 This.context = context;
 public int GetCount () {return messages.size ();
 Public Object getitem (int arg0) {return messages.get (arg0);
 public long getitemid (int arg0) {//TODO auto-generated method stub return arg0; Public VieW getview (int arg0, View arg1, ViewGroup arg2) {relativelayout layout = (relativelayout) layoutinflater.from (context). In
 Flate (r.layout.list_message, NULL);
 
 
 msg = (message) getitem (arg0);
 V_content = (TextView) Layout.findviewbyid (r.id.content);
 V_time = (TextView) Layout.findviewbyid (r.id.createtime);
 V_messger = (TextView) Layout.findviewbyid (R.id.meassger);
 V_receiver = (TextView) Layout.findviewbyid (r.id.receiver);
 V_messgerage= (TextView) Layout.findviewbyid (r.id.messagerage);
 
 
 v_messgersex= (TextView) Layout.findviewbyid (r.id.messagersex);
 V_content.settext (Msg.getcontent ());
 V_time.settext (Msg.getcreatime ());
 V_messger.settext (Msg.getmessager ());
 V_receiver.settext (Msg.getreceiver ());
 V_messgerage.settext (Msg.getmessagerage ());
 
 V_messgersex.settext (Msg.getmessagersex ());
 return layout;

 }

}

Fifth step: Let's take a look at how Mainactivity.java calls methods to get the data and parse it. A new child thread is opened here to operate. The code is as follows:

Package com.example.message;
Import Android.os.Bundle;
Import Android.os.Handler;
Import android.app.Activity;

Import Android.view.Menu; 
Import Java.io.FileOutputStream; 
Import Java.io.InputStream;
Import java.util.ArrayList; 

Import java.util.List;
Import Org.json.JSONArray;
Import org.json.JSONException;
 
Import Org.json.JSONObject; 
Import android.app.Activity; 
Import Android.content.Context; 
Import Android.os.Bundle; 
Import Android.util.Log; 
Import Android.view.View; 
Import Android.widget.Button;
 
Import Android.widget.ListView; 

Import Com.example.message.model.Message; 
 public class Mainactivity extends activity {private list<message> messages = new arraylist<message> (); Private DataAdapter Myadapter;
 
 Define a own adapter that is used to draw private Handler handler;//define a Handler,handler responsible for information formatting when necessary private ListView ListView; 
 public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
 Setcontentview (R.layout.activity_main); ListView = (ListView) Findviewbyid (R.id.listview); Handler = new Handler () {public void Handlemessage (Android.os.Message msg) {if (Msg.what = 0x123) {System.out.
   println ("Receive data");
   for (message g:messages) {System.out.println (g.getcontent ());
   } myadapter = new DataAdapter (messages, mainactivity.this);
  Listview.setadapter (Myadapter);
  
 }
  }; 
 }; New Thread (New Runnable () {public void run () {//TODO auto-generated method stub httpdata data = new Httpdata ()
  ;
  StringBuffer str = Data.getdata ();
  System.out.println (Str.tostring ());
  LOG.V ("msg", str.tostring ()); try {Jsonobject object = new Jsonobject (str.tostring ());//use JSON to parse data jsonarray msg = (Jsonarray) object.get ("Data"
   );
   for (int i=0; i<msg.length (); i++) {Jsonobject o = msg.getjsonobject (i);
   Message message = new Message ();
   Message.setcontent (o.getstring ("Content"));
   Message.setcreatime (o.getstring ("Createtime"));
   Message.setmessager (o.getstring ("Messager")); Message. Setmessagerage (O.getstring ("Messagerage"));
   Message.setmessagersex (o.getstring ("Messagersex"));
   Message.setreceiver (o.getstring ("Receiver"));
   Messages.add (message);
   } android.os.Message handlermsg = new Android.os.Message ();
   Handlermsg.what = 0x123;
   Handler.sendmessage (HANDLERMSG);
  SYSTEM.OUT.PRINTLN ("Send data");
  catch (Jsonexception e) {//TODO auto-generated catch block E.printstacktrace ();
 
 }}). Start ();

 }

}

Above, is the realization of the interface message board display. The following are some of the problems I encountered while I was writing.

1, individual computer virtual machine and computer set up problems, the program may not run up, the proposed use of An Zuojin machine.

2. Because our program has network access, you need to write permission settings in the network access configuration file.

3, on the network aspects of things, must be written on the child thread, which is why I reopened a new thread.

4, the update of the control must be on the main thread, otherwise there will be an error.

5, when we use the adapter to draw, where getcount this method must be written.

The above is the entire content of this article, I hope you like.

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.