文章列表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. Deferred在jQuery和Angular中的使用与简单实现

    Deferred在jQuery和Angular中的使用与简单实现 Deferred是在jQuery1.5版本中加入的,并且jQuery使用它完全重写了AJax,以前也只是偶尔使用.但是上次在使用Ang ...

  2. php通过判断来源主机头进行防盗链

    check.php <html> <body> <form action="test.php" method="post"> ...

  3. GCD 扫盲篇

    GCD有四个概念:串行队列.并行队列.同步.异步四者. 如下简介: 这里不仅给出了不确定性,而且也给出了确定性.对于初学者而言,有时候因为那些不确定的东西所造成的疑问会像没有闸却在疾驰的汽车一样让人惊 ...

  4. Oracle普通表->分区表转换(9亿数据量)

    背景介绍: 环境:Linux 5.5 + Oracle 10.2.0.4 某普通表T,由于前期设计不当没有分区,如今几年来的数据量已达9亿+, 空间占用大约350G,在线重定义为分区表不现实,故采取申 ...

  5. (十九)WebGIS中I查询的原理及设计(包含AGS、GeoServer、Supermap)

    文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/. 1.背景 我们在使用arcmap时,经常会用到被称为I查询的工具.具体 ...

  6. 关于客户端接口分页sql语句

    今天突然翻到为客户端写分页数据的sql,发现其实逻辑不对.列表是按照id降序的 当时这样写的: #翻上一页: select 字段 from 表 where id>lastId order by ...

  7. SQL Server 2014里的性能提升

    在这篇文章里我想小结下SQL Server 2014引入各种惊艳性能提升!! 缓存池扩展(Buffer Pool Extensions) 缓存池扩展的想法非常简单:把页文件存储在非常快的存储上,例如S ...

  8. 创建ASP.NET Core MVC应用程序(4)-添加CRUD动作方法和视图

    创建ASP.NET Core MVC应用程序(4)-添加CRUD动作方法和视图 创建CRUD动作方法及视图 参照VS自带的基架(Scaffold)系统-MVC Controller with view ...

  9. 记一个简单的sql查询

    在我们做各类统计和各类报表的时候,会有各种各样的查询要求.条件 这篇主要记录一个常见的统计查询 要求如下: 统计一段时间内,每天注册人数,如果某天没有人注册则显示为0 现在建个简单的表来试试 建表语句 ...

  10. [Asp.net 5] Configuration-新一代的配置文件

    微软新一代asp.net(vnext),也叫asp.net 5,开源代码都放在网址https://github.com/aspnet下. 本文介绍的是Configuration工程,下载路径为http ...