1. 程式人生 > >php做介面+android 請求API介面並展示到ListView例子

php做介面+android 請求API介面並展示到ListView例子

知識點:

php: 處理json問題,unicode轉碼實現

android:ListView使用與效能優化;handler訊息佇列機制;androidHTTP請求,activity知識等等:

效果如下:



檔案結構:


MainActivity主活動介面展示:

ListActivity 跳轉活動介面展示ListView內容

Person 資料填充實體

PersonAdapter ListView資料介面

Util工具類,負責網路請求以及json解析等

Manifest檔案:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.tes.api" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ListActivity">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

</manifest>


主介面兩個按鈕功能:

點選按鈕1獲取textView裡面的id,傳遞id引數,向伺服器發起post請求;獲取結果解析json,展示到按鈕下面的顯示TextView中

點選按鈕2跳轉到第二個意圖,向伺服器發起post請求,將結果填充到ListView中

服務端 api.php:

<?php
header("Content-Type:application/json;charset=utf-8");
$result = [
	"status" => 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<Person> data = (List<Person>) 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<Person> 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<Person> data;
    private static Context context;
    private static int resoureId;

    PersonAdapter(List<Person> 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<item.length();i++){
                  JSONObject tmpObj = item.getJSONObject(i);
                  String name = tmpObj.getString("name");
                  int age = tmpObj.getInt("age");
                  String address = tmpObj.getString("address");
                  JSONObject study = tmpObj.getJSONObject("study");
                  String no = study.getString("no");
                  String teacher = study.getString("teacher");
                  result += "姓名:"+name+" 年紀:"+age+" 地址:"+address+" 學號:"+no+" 老師:"+teacher+"\n";
              }

            }else{
                result = "獲取結果失敗!";
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @解析json儲存為集合
     * @param data
     * @return
     */
    public static List<Person> parseJson2List(String data){
       List<Person> result = new ArrayList<Person>();
        try{
            JSONObject object = new JSONObject(data);
            int status  = object.getInt("status");
            if(status == 200){
                JSONArray item = object.getJSONArray("result");
                for(int i=0;i<item.length();i++){
                    JSONObject tmpObj = item.getJSONObject(i);
                    String name = tmpObj.getString("name");
                    int age = tmpObj.getInt("age");
                    String address = tmpObj.getString("address");
                    JSONObject study = tmpObj.getJSONObject("study");
                    String no = study.getString("no");
                    String teacher = study.getString("teacher");
                    Person person = new Person(name,age,address,no,teacher);
                    result.add(person);
                }

            }else{
                System.out.println("獲取失敗或無資料!");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return result;
    }
}





佈局檔案:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入id"
        android:id="@+id/editText"
        android:layout_gravity="center_horizontal" />

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dip"
        android:layout_marginBottom="5dip">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dip"
            android:layout_marginBottom="20dip"
            android:text="查詢"
            android:layout_weight="1"
            android:id="@+id/button" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dip"
            android:layout_marginBottom="20dip"
            android:text="資料列表"
            android:layout_weight="1"
            android:id="@+id/button2" />

    </LinearLayout>


    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/scrollView"
        android:layout_gravity="center_horizontal" >
        <TextView
            android:layout_width="match_parent"
            android:layout_marginTop="20dip"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text=""
            android:scrollbars="vertical"
            android:hint="顯示結果"
            android:id="@+id/textView" />
    </ScrollView>
</LinearLayout>


activity_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="學生通訊錄"
       android:textColor="#D50203"
        android:textSize="30dip"
        android:layout_gravity="center"
        android:layout_marginBottom="10dip"
        android:id="@+id/textView2" />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_gravity="center_horizontal" />
</LinearLayout>

item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Small Text"
        android:id="@+id/name" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Small Text"
        android:id="@+id/age" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Small Text"
        android:id="@+id/address" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Small Text"
        android:id="@+id/no" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Small Text"
        android:id="@+id/teacher" />
</LinearLayout>