文章列表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开发之自动布局显示网络请求内容

    在上一篇博客中详细的介绍了IOS开发中的相对布局和绝对布局,随着手机屏幕尺寸的改变,在App开发中为了适应不同尺寸的手机屏幕,用自动布局来完成我们想要实现的功能和效果显得尤为重要.本人更喜欢使用相对布 ...

  2. php模拟数据库常用操作效果

    test.php <?php header("Content-type:text/html;charset='utf8'"); error_reporting(E_ALL); ...

  3. 探秘Tomcat——启动篇

    tomcat作为一款web服务器本身很复杂,代码量也很大,但是模块化很强,最核心的模块还是连接器Connector和容器Container.具体请看下图: 从图中可以看出 a. 高亮的两块是Conne ...

  4. Kooboo CMS 无聊随笔(2)

    上次写了一篇博客 http://www.cnblogs.com/kmsfan/p/Kooboo_CMS_suibi.html 作为这个系列的开篇,简单的介绍了一下Kooboo CMS的一些基本情况和界 ...

  5. MVC发布后项目存在于根目录中的子目录中时的css与js、图片路径问题

    加载固定资源js与css <script src="@Url.Content("~/Scripts/js/jquery.min.js")" type=&q ...

  6. GUI 和 GUILayout 的区别

    GUI 和 GUILayout 的区别 A~ GUI是Unity中的基础控件类,其中包含了常用的GUI控件,列如Button,Label,PasswordField,slider,Window等等~ ...

  7. 3.Code-First 约定(EF Code-First系列)

    前面,我们已经了解了Code-First利用领域类,怎么为我们创建数据库的简单示例.现在我们来学习一下Code-First约定吧. 什么是约定 约定说白了,就是基于一套规矩办事,这里就是基于你定义好的 ...

  8. javascript作用域中令你意想不到的问题

    大多数类c的语言,由一对花括号封闭的代码块就是一个作用域.但是javascript的作用域则是通过函数来定义.在一个函数中定义的变量只对这个函数内部可见,我们称为函数作用域. 1.在函数中引用一个变量 ...

  9. Gitlab使用总结

    Gitlab日常开发流程 1. 从某一功能分支新建一个自己的开发分支 二. 将master分支clone到本地 mkdir git-test cd git-test\ git clone http:/ ...

  10. WP7 手机软件纪念 - 稍后读软件

    在本月换机之际,决定写篇博客纪念一下我在 WP7 手机上开发的一个稍后读软件.这个工具开发完成后,两年间,我的 WP7 手机 80% 的用途,都发挥在了它身上. 这个软件其实是一个离线阅读工具,非常类 ...