你的位置:首页 > 操作系统

[操作系统]使用Android实现接口信息的留言版显示


      关于这个篇日志,我上周末的时候已经写好了初稿,但是后来电脑安装程序的时候,出了问题重装了。结果没有备份好,这个星期也在忙着学习新的知识,也就把发表的事情搁置了。今天看到,一些同学上交了作业,都没有使用老师指定的接口实现。那么,我来分享一下,我的一点点成果。

     看到标题,顾名思义,我今天只是和大家讲一下如何实现接口信息的显示,不包括添加信息。

     接口帮助文档:http://api.wzhospital.cn/msg/help  

     根据查看接口文档,我们可以知道接口内部的一些信息结构。

     当然,想要查看具体的信息,是通过此链接:http://api.wzhospital.cn/MSG/api/Message/GetList 

     获取以下信息,来验证显示的正确性。

<Messages

<Data>

<Message>

<Content>我的第一个默认留言</Content>

<CreateTime>2015-07-30 08:29:19</CreateTime>

<Messager>林豪</Messager>

<MessagerAge>22</MessagerAge>

<MessagerSex>女</MessagerSex>

<Receiver>林志玲</Receiver>

</Message>

<Message>

<Content>我的第二个默认留言</Content>

<CreateTime>2015-07-30 08:31:19</CreateTime>

<Messager>林志玲</Messager>

<MessagerAge>18</MessagerAge>

<MessagerSex>女</MessagerSex>

<Receiver>刘德华</Receiver>

</Message>

<Message>

<Content>

我的第三个默认留言我的第三个默认留言我的第三个默认留言我的第三个默认留言我的第三个默认留言我的第三个默认留言我的第三个默认留言我的第三个默认留言我的第三个默认留言我的第三个默认留言我的第三个默认留言

</Content>

<CreateTime>2015-07-30 08:33:19</CreateTime>

<Messager>林豪</Messager>

<MessagerAge>22</MessagerAge>

<MessagerSex>人妖</MessagerSex>

<Receiver>林志玲</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>

首先,我先给大家看一下界面效果图(排版难看,大家谅解)。

            1xiaoguo                     222

第一步:先说一下,整个页面是布局。

           这个页面由两部分组成,其一:activity_main.listView.其二:重写了一个list_message.

                                listview                                                     chongxielistview

                                            activity_main.

            关于为什么重写一个.

第二步:根据接口文档,建立实体类。

               wen

                单击 GET api/Message/GetList 将获得接口信息,由于我采用的是json的格式,我只截取这一段代码。

                         json

                     根据信息分析,我创建了一个message.java的实体类。

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

      第三步:我们需要做的是如何获取接口的数据,并且去解析(我将其写于MainActivity.java中)它,那么我们需要新建一个新类,这个我取名为HttpData.java。它的作用就是获取接口中的内容。代码如下:

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;//定义HTTP一个客户端
    private HttpResponse reponse;//定义一个HTTP响应
    private HttpEntity entity;//定义一个HTTP实体
   
    private InputStream in;//定义一个输入流
    private BufferedReader reader;//定义一个字符流;
   
    private StringBuffer data = new StringBuffer("");//定义一个空的字符串缓冲;
   
    private String url = "http://api.wzhospital.cn/MSG/api/Message/GetList";
    //private String url1="http://api.wzhospital.cn/MSG/api/Message/Add";
    private HttpGet get;//GET:请求的数据随HTTP请求头发过去
   
    public StringBuffer getData(){//此方法获取接口的文本内容,并以字符流的形式return
        client = new DefaultHttpClient();
        get = new HttpGet(url);//url定向
       
        try {
            HttpParams params = new HttpParams() {
               
                public HttpParams setParameter(String arg0, Object arg1) {
                    // TODO Auto-generated method stub
                    return null;
                }
               
                public HttpParams setLongParameter(String arg0, long arg1) {
                    // TODO Auto-generated method stub
                    return null;
                }
               
                public HttpParams setIntParameter(String arg0, int arg1) {
                    // TODO Auto-generated method stub
                    return null;
                }
               
                public HttpParams setDoubleParameter(String arg0, double arg1) {
                    // TODO Auto-generated method stub
                    return null;
                }
               
                public 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;
                }
               
                public Object getParameter(String arg0) {
                    // TODO Auto-generated method stub
                    return null;
                }
               
                public long getLongParameter(String arg0, long arg1) {
                    // TODO Auto-generated method stub
                    return 0;
                }
               
                public int getIntParameter(String arg0, int arg1) {
                    // TODO Auto-generated method stub
                    return 0;
                }
               
                public double getDoubleParameter(String arg0, double arg1) {
                    // TODO Auto-generated method stub
                    return 0;
                }
               
                public boolean getBooleanParameter(String arg0, boolean arg1) {
                    // TODO Auto-generated method stub
                    return false;
                }
               
                public HttpParams copy() {
                    // TODO Auto-generated method stub
                    return null;
                }
            };
           
            reponse = client.execute(get);//执行客户端的get操作
            entity = reponse.getEntity();//获取响应中是实例
            in = entity.getContent();//获取实例中的文本内容
            reader = new BufferedReader(new InputStreamReader(in));//读入字符流
            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;   
    }
}

第四步:封装数据集合(listview),通过视图绘制,此处采用的是数据适配器绘制。代码如下:

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 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, Context context){
        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).inflate(R.layout.list_message, null);
        Message 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;
    }

}
第五步:我们来看一看MainActivity.java是如何调用方法获取数据,并解析的。此处额外新开了一个子线程,进行操作。代码如下:

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;  //定义一个自己的适配器,用于绘制
    private Handler handler;//定义一个Handler,Handler 负责在必要时进行信息格式化
    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("接收数据");
                    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());//使用json ,解析数据
                    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("发送数据");
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();
      
    }

}

以上,就是实现接口留言板的显示。有以下几点,是在我写的时候遇到的问题。

1、个别电脑的虚拟机和电脑设置的问题,程序可能跑不起来,建议使用安卓真机。

2、由于我们的程序存在网络访问,需要在网络访问配置文件当中加写权限设置。

3、有关网络方面的东西,都必须写在子线程上,这就是为什么我重新开了一个新的线程。

4、控件的更新必须在主线程上,否则将出错。

5、当我们使用适配器绘制时,其中getCount这个方法必须要写。

 

以上就是本文的全部内容,这是本人第一次写博客,不喜勿喷。欢迎指教。微笑