php做接口+android 请求API接口并展示到ListView例子

知识点:

php: 处理json问题,unicode转码实现

android:ListView使用与性能优化;handler消息队列机制;androidHTTP请求,activity知识等等:

效果如下:


php做接口+android 请求API接口并展示到ListView例子_第1张图片php做接口+android 请求API接口并展示到ListView例子_第2张图片

php做接口+android 请求API接口并展示到ListView例子_第3张图片


文件结构:


php做接口+android 请求API接口并展示到ListView例子_第4张图片



MainActivity主活动界面展示:

ListActivity 跳转活动界面展示ListView内容

Person 数据填充实体

PersonAdapter ListView数据接口

Util工具类,负责网络请求以及json解析等



Manifest文件:





    
        
            
                
                
            
        
        
            
                
                
            
        
    
    




主界面两个按钮功能:

点击按钮1获取textView里面的id,传递id参数,向服务器发起post请求;获取结果解析json,展示到按钮下面的显示TextView中

点击按钮2跳转到第二个意图,向服务器发起post请求,将结果填充到ListView中



服务端 api.php:


 200,
	"msg" => "获取成功",
	"result" => [
       ["name"=>"zfeig","age"=>26,"address"=>"广州市天河区车陂天桥11号","study"=>["no"=>"0610832110","teacher"=>"李贤良"]],
       ["name"=>"lisi","age"=>27,"address"=>"四川省成都市高新区226号","study"=>["no"=>"0610832110","teacher"=>"何洁"]],
       ["name"=>"王大崔","age"=>25,"address"=>"浙江省杭州市西湖大道120号","study"=>["no"=>"0610732110","teacher"=>"刘德华"]],
       ["name"=>"刘晓花","age"=>23,"address"=>"福建省厦门市厦门大学路13号","study"=>["no"=>"0610632110","teacher"=>"王明"]],
       ["name"=>"lisi","age"=>27,"address"=>"四川省成都市高新区226号","study"=>["no"=>"0610832110","teacher"=>"何洁"]],
       ["name"=>"王大崔","age"=>25,"address"=>"浙江省杭州市西湖大道120号","study"=>["no"=>"0610732110","teacher"=>"刘德华"]],
       ["name"=>"刘晓花","age"=>23,"address"=>"福建省厦门市厦门大学路13号","study"=>["no"=>"0610632110","teacher"=>"王明"]]
	]
];


function encodeCN($result){

	foreach ($result as $k => $v) {
		if(is_array($v)){
           $result[$k] = encodeCN($v);       
		}else{
			$result[$k] = urlencode($v);
		}
	}

	return $result;
}

$result = encodeCN($result);

echo urldecode(json_encode($result));

?>

MainActivity.java


package com.example.tes.api;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements View.OnClickListener {
     private static EditText text;
     private static Button btn;
     private static Button listBtn;
     private static TextView tv;
     private static String info;
     private static ProgressDialog pd;
     private final String ADDR = "http://192.168.145.162:8000/api.php";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.button);
        listBtn = (Button) findViewById(R.id.button2);
        tv = (TextView) findViewById(R.id.textView);
        text = (EditText) findViewById(R.id.editText);
        btn.setOnClickListener(this);
        listBtn.setOnClickListener(this);
    }

    Handler hander = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what  == 1){
                pd.dismiss();
                info  = msg.obj.toString();
                tv.setText(info);
            }
        }
    };

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.button :
                 String id =text.getText().toString();
                if(id.equals(null) || id.equals("")){
                    Toast.makeText(this,"请输入id号",Toast.LENGTH_LONG).show();
                }else{

                    pd = new ProgressDialog(MainActivity.this);
                    pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                    pd.setMessage("wait...");
                    pd.show();

                    final String Id = id;
                    new Thread(){
                        @Override
                        public void run() {
                            String msg =  Util.httpPost(ADDR,Integer.parseInt(Id));
                            msg = Util.parseJson2String(msg);
                            Util.sendMsg(hander,new Message(),msg);
                        }
                    }.start();
                }
                break;
            case R.id.button2:
                Intent it = new Intent(MainActivity.this,ListActivity.class);
                startActivity(it);
                break;
        }
    }




}

ListActivity.java

package com.example.tes.api;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Iterator;
import java.util.List;
public class ListActivity extends Activity {
    private static String ADDR ="http://192.168.145.162:8000/api.php";
    private ListView lv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        lv = (ListView) findViewById(R.id.listView);
        initData();
    }
    Handler hander = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what  == 1){
                List data = (List) msg.obj;
                String info =  list2str(data);
                Toast.makeText(ListActivity.this,"消息:"+info, Toast.LENGTH_LONG).show();
                lv.setAdapter(new PersonAdapter(data,ListActivity.this,R.layout.item));
            }
        }
    };
    public  void initData(){
        new Thread(){
            @Override
            public void run() {
                super.run();
                String msg =  Util.httpPost(ADDR, 1);
                List data = Util.parseJson2List(msg);
                Util.sendMsg(hander, new Message(), data);
            }
        }.start();
    }
    public  String  list2str(List list){
        StringBuilder sb = new StringBuilder();
        Iterator it = list.iterator();
        while(it.hasNext()){
            Person pr = (Person) it.next();
            String name =pr.getName();
            int age =pr.getAge();
            String address = pr.getAddress();
            String no = pr.getNo();
            String teacher =pr.getTeacher();
            sb.append("姓名:"+name+" ");
            sb.append("年纪:"+age+" ");
            sb.append("地址:"+address+" ");
            sb.append("学号:"+no+"\n");
        }
        return sb.toString();
    }
}

Person.java

package com.example.tes.api;

/**
 * Created by no1 on 2016/6/25.
 */
public class Person {
    private String name;
    private int age;
    private String address;
    private String no;
    private String teacher;

    public Person(String name, int age, String address, String no, String teacher) {
        this.name = name;
        this.age = age;
        this.address = address;
        this.no = no;
        this.teacher = teacher;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getNo() {
        return no;
    }

    public void setNo(String no) {
        this.no = no;
    }

    public String getTeacher() {
        return teacher;
    }

    public void setTeacher(String teacher) {
        this.teacher = teacher;
    }
}


PersonAdapter.java


package com.example.tes.api;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;

public class PersonAdapter extends BaseAdapter {
    private List data;
    private static Context context;
    private static int resoureId;

    PersonAdapter(List data,Context context,int resoureId){
        this.context = context;
        this.data = data;
        this.resoureId = resoureId;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return  data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        Person person = data.get(position);
        if(convertView == null){
            convertView = LayoutInflater.from(context).inflate(resoureId,null);//找到lv布局
            viewHolder = new ViewHolder(convertView);//找到布局下面的组件并缓存起来
            convertView.setTag(viewHolder);//缓存组件对象

        }else{
            viewHolder = (ViewHolder) convertView.getTag();//获取组件对象
        }
        //组件对象填充数据
        viewHolder.name.setText(person.getName());
        viewHolder.age.setText("年纪:"+person.getAge()+"");
        viewHolder.address.setText("家庭住址:"+person.getAddress());
        viewHolder.no.setText("学号:"+person.getNo());
        viewHolder.teacher.setText("班主任:"+person.getTeacher());
        return convertView;
    }

    public  class ViewHolder{
        private TextView name;
        private TextView age;
        private TextView address;
        private TextView no;
        private TextView teacher;
        ViewHolder(View contentView){
            this.name = (TextView) contentView.findViewById(R.id.name);
            this.age = (TextView) contentView.findViewById(R.id.age);
            this.address = (TextView) contentView.findViewById(R.id.address);
            this.no = (TextView) contentView.findViewById(R.id.no);
            this.teacher = (TextView) contentView.findViewById(R.id.teacher);
        }
    }
}


Util.java

package com.example.tes.api;

import android.os.Handler;
import android.os.Message;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class Util {
    /**
     * @发送消息到消息队列中
     * @param hander
     * @param msg
     * @param data
     */
    public static void sendMsg(Handler hander,Message msg,String data){
        msg.what =1;
        msg.obj = data;
        hander.sendMessage(msg);
    }
    /**
     * @发送消息到消息队列中
     * @param hander
     * @param msg
     * @param data
     */
    public static void sendMsg(Handler hander,Message msg,List data){
        msg.what =1;
        msg.obj = data;
        hander.sendMessage(msg);
    }

    /**
     * @获取post请求
     * @param url
     * @param id
     * @return
     */
    public static String httpPost(String url,int id){
        String params = "act=1";
        params = params +"&vid="+id;
        String data = null;
        HttpURLConnection conn = null;
        try{
            //get request
            URL address = new URL(url);
            conn = (HttpURLConnection) address.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(params.getBytes().length));
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.getOutputStream().write(params.getBytes());//将参数写入输出流
            //get outinput
            StringBuilder sb = new StringBuilder();
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String msg = "";
            while((msg = br.readLine())!=null){
                sb.append(msg);
            }
            data = sb.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(conn != null){
                conn.disconnect();
            }
        }
        System.out.println("获取结果为:" + data);
        return data;
    }

    /**
     * @get请求
     * @param url
     * @return
     */
    public static String httpGet(String url){
        String data = null;
        HttpURLConnection conn = null;
        try{
            URL address = new URL(url);
            conn = (HttpURLConnection) address.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            StringBuilder sb = new StringBuilder();
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String msg = "";
            while((msg = br.readLine())!=null){
                sb.append(msg);
            }
            data = sb.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(conn != null){
                conn.disconnect();
            }
        }
        return data;
    }

    /**
     * @解析json存为字符串
     * @param data
     * @return
     */
    public static String  parseJson2String(String data){
        String result = "";
        try{
            JSONObject object = new JSONObject(data);
            int status  = object.getInt("status");
            if(status == 200){
                JSONArray item = object.getJSONArray("result");
              for(int i=0;i parseJson2List(String data){
       List result = new ArrayList();
        try{
            JSONObject object = new JSONObject(data);
            int status  = object.getInt("status");
            if(status == 200){
                JSONArray item = object.getJSONArray("result");
                for(int i=0;i


布局文件:

activity_main.xml



    

    
        


activity_list.xml




    

    

item.xml




    

    

    

    

    




你可能感兴趣的:(andriod)