您的位置:首页 > 移动开发 > Android开发

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

2016-06-25 18:06 681 查看
知识点:

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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息