文章列表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);
?>

  

Android 异步任务,通过PHP访问数据库,多线程,线程间通讯的更多相关文章

  1. iOS开发多线程-线程间通讯

    一.NSThread 线程间的通讯 - (void)demoAboutNSThread { NSLog(@"demoAboutNSThread %@", [NSThread cur ...

  2. java 并发性和多线程 -- 读感 (二 线程间通讯,共享内存的机制)

    参考文章:http://ifeve.com/java-concurrency-thread-directory/ 其中的竞态,线程安全,内存模型,线程间的通信,java ThreadLocal类小节部 ...

  3. 【转】JAVA 并发性和多线程 -- 读感 (二 线程间通讯,共享内存的机制)

    原文地址:https://www.cnblogs.com/edenpans/p/6020113.html 参考文章:http://ifeve.com/java-concurrency-thread-d ...

  4. 黑马程序员——JAVA基础之多线程的线程间通讯等

    ------- android培训.java培训.期待与您交流! ---------- 线程间通讯: 其实就是多个线程在操作同一个资源,但是动作不同. wait(); 在其他线程调用此对象的notif ...

  5. Android查缺补漏(IPC篇)-- 进程间通讯基础知识热身

    本文作者:CodingBlock 文章链接:http://www.cnblogs.com/codingblock/p/8479282.html 在Android中进程间通信是比较难的一部分,同时又非常 ...

  6. Java:多线程<三>死锁、线程间通讯

    死锁: 同步嵌套同步,而且使用的锁不是同一把锁时就可能出现死锁 class Test implements Runnable { private boolean flag; Test(boolean ...

  7. Android查缺补漏(IPC篇)-- 进程间通讯之Socket简介及示例

    本文作者:CodingBlock 文章链接:http://www.cnblogs.com/codingblock/p/8425736.html 进程间通讯篇系列文章目录: Android查缺补漏(IP ...

  8. Android查缺补漏(IPC篇)-- 进程间通讯之AIDL详解

    本文作者:CodingBlock 文章链接:http://www.cnblogs.com/codingblock/p/8436529.html 进程间通讯篇系列文章目录: Android查缺补漏(IP ...

  9. Android异步载入全解析之使用多线程

    异步载入之使用多线程 初次尝试 异步.异步,事实上说白了就是多任务处理.也就是多线程执行.多线程那就会有各种问题,我们一步步来看.首先.我们创建一个class--ImageLoaderWithoutC ...

随机推荐

  1. IOS开发之自定义Button(集成三种回调模式)

    前面在做东西的时候都用到了storyboard,在今天的代码中就纯手写代码自己用封装个Button.这个Button继承于UIView类,在封装的时候用上啦OC中的三种回调模式:目标动作回调,委托回调 ...

  2. php对表格进行批量操作如全选反选删除功能

    <!DOCTYPE> <html> <head> <meta http-equiv="content-type" content=&quo ...

  3. 简析将shp导入Oracle并利用geoserver将导入的数据发布

    文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/. 1.环境准备 1.1 软件准备 首先要安装有支持空间数据的Oracle ...

  4. Windows Server 2008 下解析二级域名的方法

    昨天去了客户那里部署网站,用的是客户那边的windows server 2008. 本文主要以总结问题点的形式来说. 问题1:本机的数据库是SQL SERVER 2008R2,客户那边的数据库是SQL ...

  5. ECMAScript 5中属性的特性值

    这是<JavaScript高级程序设计(第三版)>第六章相关内容的总结. ECMAScript中有两种属性:数据属性和访问器属性.每种属性都有四个特性值. 数据属性的四个特性值: [[Co ...

  6. HTML基本元素(一)

    HTML基本元素(一) 1.换行符 <br /> Ps:br 是换行(Break)的缩写,文本会在这个标签的地方换行. 实例: 第一行<br />第二行 2.段落 <p& ...

  7. 我有几个NUMA节点

    在SQL Server交流会,经常被问到的一个问题,SQL Server在几个NUMA节点上运行.因此,在今天的文章里,我想向你展示下几个方法和技术,找出你的SQL Server有几个NUMA节点. ...

  8. HTTP首部

    前面有几篇博文介绍了HTTP协议.HTTP请求方法详解.Javascript中Cookie的那些事儿.HTTPS,今天我们来聊一聊关于HTTP首部的那些事儿 HTTP协议的请求和响应报文中肯定包含HT ...

  9. CSS技巧(一):清除浮动

    什么是CSS清除浮动? 在非IE浏览器(如Firefox)下,当容器的高度为auto,且容器的内容中有浮动(float为left或right)的元素,在这种情况下,容器的高度不能自动伸长以适应内容的高 ...

  10. C# 热敏打印机 Socket 网络链接 打印 图片 (二)

    IPAddress ip = IPAddress.Parse("192.168.1.212"); IPEndPoint iport = );//9100为小票打印机指定端口 Soc ...