Android 异步任务,通过PHP访问数据库,多线程,线程间通讯

Android 异步任务,通过PHP访问数据库,多线程,线程间通讯

Android 异步任务,通过PHP访问数据库,多线程,线程间通讯

文章列表MainActivity.java

package com.eric.asynctask;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject; import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast; public class MainActivity extends Activity {
final static String EXTRA_POST_ID = "com.eric.asynctask.POST_ID";
String extra_post_id;
String url = "http://www.zhangjianghome.net/android/title-select.php";
int offset = 0;
int num = 30;
ListView titleList;
SimpleAdapter adapter;
ArrayList<HashMap<String, String>> list; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); ConnectivityManager connMgr = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadTitleListTask().execute(offset, num);
} else {
Toast.makeText(MainActivity.this,
"No network connection available.", Toast.LENGTH_SHORT)
.show();
}
} @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;
} private class DownloadTitleListTask extends
AsyncTask<Integer, Void, String> { @Override
protected String doInBackground(Integer... arg0) {
// TODO Auto-generated method stub
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> formEntity = new ArrayList<NameValuePair>();
formEntity.add(new BasicNameValuePair("offset", String
.valueOf(arg0[0])));
formEntity.add(new BasicNameValuePair("num", String
.valueOf(arg0[1])));
httpPost.setEntity(new UrlEncodedFormEntity(formEntity,
HTTP.UTF_8));
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String strResult = EntityUtils.toString(httpResponse
.getEntity());
return strResult;
} else {
Toast.makeText(MainActivity.this, "http请求失败",
Toast.LENGTH_SHORT).show();
return null;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
} protected void onPostExecute(String result) {
adapter = getAdapterFromJSONString(result);
titleList = (ListView) MainActivity.this
.findViewById(R.id.ListView1);
titleList.setAdapter(adapter);
titleList
.setOnItemClickListener(new AdapterView.OnItemClickListener() { @SuppressWarnings("unchecked")
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
// TODO Auto-generated method stub
HashMap<String, String> map = (HashMap<String, String>) ((ListView) parent)
.getItemAtPosition(position);
extra_post_id = map.get("ID").toString();
Intent intent = new Intent();
intent.setClass(MainActivity.this,
DetailActivity.class);
intent.putExtra(EXTRA_POST_ID, extra_post_id);
MainActivity.this.startActivity(intent);
}
});
}
} private SimpleAdapter getAdapterFromJSONString(String JSONString) {
list = new ArrayList<HashMap<String, String>>();
try {
JSONArray jsonArray = new JSONArray(JSONString);// JSONArray的元素必须全为JSONObject
for (int i = 0; i < jsonArray.length() - 1; i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonObject = jsonArray.getJSONObject(i);
map.put("ID", jsonObject.getString("ID"));
map.put("post_title", jsonObject.optString("post_title"));
map.put("post_date", jsonObject.optString("post_date"));
map.put("post_content", jsonObject.optString("jsonObject"));
list.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new SimpleAdapter(
MainActivity.this,
list,
R.layout.list_item,
new String[] { "ID", "post_title", "post_date", "post_content" },
new int[] { R.id.post_id, R.id.post_title, R.id.post_date,
R.id.post_content });
}
}

  列表视图的每一项布局:list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" > <TextView
android:id="@+id/post_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textColor="@color/buue" /> <TextView
android:id="@+id/post_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" /> </LinearLayout> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" > <TextView
android:id="@+id/post_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" /> <TextView
android:id="@+id/post_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:visibility="gone" /> </LinearLayout> </LinearLayout>

  文章详情DetailActivity.java

package com.eric.asynctask;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject; import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast; public class DetailActivity extends Activity {
TextView postContentView;
String str_url = "http://www.zhangjianghome.net/android/content-select.php";
private final static int handler_flag = 0x1234;
private Handler HttpHandler;
String postID; @SuppressLint("HandlerLeak")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail); Intent intent = this.getIntent();
postID = intent.getStringExtra(MainActivity.EXTRA_POST_ID);
postContentView = (TextView) this.findViewById(R.id.textView1);// 竟然是这个id搞错了,草。。。 ConnectivityManager connMgr = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new Thread(new HttpRunnable()).start();
HttpHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case handler_flag:
postContentView.setText("文章ID:"
+ getJSONFromString(msg.obj.toString())
.optString("ID")
+ "\n"
+ "文章标题:"
+ getJSONFromString(msg.obj.toString())
.optString("post_title")
+ "\n"
+ "发表日期:"
+ getJSONFromString(msg.obj.toString())
.optString("post_date")
+ "\n"
+ "文章内容:"
+ getJSONFromString(msg.obj.toString())
.optString("post_content"));
break;
default:
break;
}
super.handleMessage(msg);
}
};
} else {
Toast.makeText(DetailActivity.this,
"No network connection available.", Toast.LENGTH_SHORT)
.show();
} } @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.detail, menu);
return true;
} private String getResultStringHttp(String ID) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(str_url + "?ID=" + ID);
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String strResult = EntityUtils.toString(httpResponse
.getEntity());
return strResult;
} else {
return null;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
} class HttpRunnable implements Runnable {
@Override
public void run() {
do {
String str_result = getResultStringHttp(postID);
//Thread.sleep(1000); Message msg = Message.obtain();
msg.what = handler_flag;
msg.obj = str_result;
DetailActivity.this.HttpHandler.sendMessage(msg);
} while (Thread.interrupted() == false);
}
} private JSONObject getJSONFromString(String jsonString) {
try {
JSONObject jsonObject;
jsonObject = new JSONObject(jsonString);
return jsonObject;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
} }

  php访问数据库:

<?php
$con = mysql_connect("localhost", "db163810_f", "1e6969e2");
if (!$con)
{
die('不能建立连接: ' . mysql_error());
}
$db_selected = mysql_select_db("db163810",$con);
mysql_query("SET NAMES 'utf8'");
if (!$db_selected)
{
die ("这个数据库不能被选: " . mysql_error());
}
$sql = "SELECT `ID` , `post_date` , `post_title` , `post_content` FROM `wp_posts` where `post_status`='publish' order by `post_date` desc LIMIT ".$_REQUEST["offset"].",".$_REQUEST["num"];
$result = mysql_query($sql,$con);
echo "[";
while($row = mysql_fetch_assoc($result))
{
//print_r(json_encode($row));
//print(json_encode($row));
//print_r($row);
//echo "<br/><br/>";
//print($row);
echo json_encode($row);
echo ",";
}
echo "{\"EOF\":\"EOF\"}]";
mysql_close($con);
?>

  

上一篇:ADO.NET 访问数据库


下一篇:如何通过JDBC访问数据库