php.android.mysql,Android通过PHP访问MySQL数据库

In this post I'm going to describe how we can read data from MySQL database and show them in a Android list view. To fetch data here I used a PHP script which encodes data into json format.

This project has three main parts.

1. MySQL database

2. PHP web service

3.Android web service client

1. MySQL database.

My database has only one table named "emp_info" and it has two columns. "employee name" and "employee no". "employee no" is the primary key.

f5277966cb56f1b3848b6291460ac63d.png

2.PHP web service

Use following PHP script to fetch data from the database and to encode data in to json format.

3.Android web service client.

This part is bit complected. Android activity is a combination of Async Task json and list view. If you are not familiar with those stuff look following tutorials.

Here is the code for main Android activity.

package com.example.mysqlphp;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import org.apache.http.HttpResponse;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

import android.os.AsyncTask;

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import android.widget.ListView;

import android.widget.SimpleAdapter;

import android.widget.Toast;

public class MainActivity extends Activity {

private String jsonResult;

private String url = "http://XXXXXX/employee_details.php"; //XXXXXX为Ip地址

private ListView listView;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

listView = (ListView) findViewById(R.id.listView1);

accessWebService();

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.main, menu);

return true;

}

// Async Task to access the web

private class JsonReadTask extends AsyncTask{

@Override

protected String doInBackground(String... params) {

HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost(params[0]);

try {

HttpResponse response = httpclient.execute(httppost);

jsonResult = inputStreamToString(

response.getEntity().getContent()).toString();

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

private StringBuilder inputStreamToString(InputStream is) {

String rLine = "";

StringBuilder answer = new StringBuilder();

BufferedReader rd = new BufferedReader(new InputStreamReader(is));

try {

while ((rLine = rd.readLine()) != null) {

answer.append(rLine);

}

} catch (IOException e) {

// e.printStackTrace();

Toast.makeText(getApplicationContext(),

"Error..." + e.toString(), Toast.LENGTH_LONG).show();

}

return answer;

}

@Override

protected void onPostExecute(String result) {

ListDrwaer();

}

}// end async task

public void accessWebService() {

JsonReadTask task = new JsonReadTask();

// passes values for the urls string array

task.execute(new String[] { url });

}

// build hash set for list view

public void ListDrwaer() {

List> employeeList = new ArrayList>();

try {

JSONObject jsonResponse = new JSONObject(jsonResult);

JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");

for (int i = 0; i < jsonMainNode.length(); i++) {

JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

String name = jsonChildNode.optString("employee name");

String number = jsonChildNode.optString("employee no");

String outPut = name + "-" + number;

employeeList.add(createEmployee("employees", outPut));

}

} catch (JSONException e) {

Toast.makeText(getApplicationContext(), "Error" + e.toString(),

Toast.LENGTH_SHORT).show();

}

SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,

android.R.layout.simple_list_item_1,

new String[] { "employees" }, new int[] { android.R.id.text1 });

listView.setAdapter(simpleAdapter);

}

private HashMapcreateEmployee(String name, String number) {

HashMapemployeeNameNo = new HashMap();

employeeNameNo.put(name, number);

return employeeNameNo;

}

}

Add Internet permission to AndroidManifest.xml

Code for main activity layout.

运行结果如图所示:

c51ab28e95322244dce0b487fdf36f32.png

转载网址:http://codeoncloud.blogspot.com/2013/07/android-mysql-php-json-tutorial.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值