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);
?>
Android 异步任务,通过PHP访问数据库,多线程,线程间通讯的更多相关文章
- iOS开发多线程-线程间通讯
一.NSThread 线程间的通讯 - (void)demoAboutNSThread { NSLog(@"demoAboutNSThread %@", [NSThread cur ...
- java 并发性和多线程 -- 读感 (二 线程间通讯,共享内存的机制)
参考文章:http://ifeve.com/java-concurrency-thread-directory/ 其中的竞态,线程安全,内存模型,线程间的通信,java ThreadLocal类小节部 ...
- 【转】JAVA 并发性和多线程 -- 读感 (二 线程间通讯,共享内存的机制)
原文地址:https://www.cnblogs.com/edenpans/p/6020113.html 参考文章:http://ifeve.com/java-concurrency-thread-d ...
- 黑马程序员——JAVA基础之多线程的线程间通讯等
------- android培训.java培训.期待与您交流! ---------- 线程间通讯: 其实就是多个线程在操作同一个资源,但是动作不同. wait(); 在其他线程调用此对象的notif ...
- Android查缺补漏(IPC篇)-- 进程间通讯基础知识热身
本文作者:CodingBlock 文章链接:http://www.cnblogs.com/codingblock/p/8479282.html 在Android中进程间通信是比较难的一部分,同时又非常 ...
- Java:多线程<三>死锁、线程间通讯
死锁: 同步嵌套同步,而且使用的锁不是同一把锁时就可能出现死锁 class Test implements Runnable { private boolean flag; Test(boolean ...
- Android查缺补漏(IPC篇)-- 进程间通讯之Socket简介及示例
本文作者:CodingBlock 文章链接:http://www.cnblogs.com/codingblock/p/8425736.html 进程间通讯篇系列文章目录: Android查缺补漏(IP ...
- Android查缺补漏(IPC篇)-- 进程间通讯之AIDL详解
本文作者:CodingBlock 文章链接:http://www.cnblogs.com/codingblock/p/8436529.html 进程间通讯篇系列文章目录: Android查缺补漏(IP ...
- Android异步载入全解析之使用多线程
异步载入之使用多线程 初次尝试 异步.异步,事实上说白了就是多任务处理.也就是多线程执行.多线程那就会有各种问题,我们一步步来看.首先.我们创建一个class--ImageLoaderWithoutC ...
随机推荐
- iOS开发之WebView
做iOS的应用也有一段时间了,在之前的demo中一直没有机会用到WebView,今天就查缺补漏一下,使用一下WebView.最早接触WebView是在Android中接触的,iOS中的WebView的 ...
- Oracle层次查询
Oracle层次查询的语法如下: 下面根据两道“烧脑”的题具体来体现: 1. 根据时间先后顺序,十二星座的英文名称用逗号串起来为'Aries,Taurus,Gemini,Cancer,Leo,Virg ...
- 虚拟目录webconfig的配置
昨天需要新建一个虚拟目录放在以前的一个站点下,新建了应用池,配好了环境置顶路径,虚拟目录页建立成功 ,但是程序一直是报错.这个程序我在测试服务器上是测过的,新建了一个站点是可以正常访问的,排除了程序问 ...
- Java ConcurrentHashMap Example and Iterator--转
原文地址:http://www.journaldev.com/122/java-concurrenthashmap-example-iterator#comment-27448 Today we wi ...
- iOS OC语言: Block底层实现原理
先来简单介绍一下BlockBlock是什么?苹果推荐的类型,效率高,在运行中保存代码.用来封装和保存代码,有点像函数,Block可以在任何时候执行. Block和函数的相似性:(1)可以保存代码(2) ...
- 开启SharePoint Server 2013 中的“微博”功能——新闻源
熟悉SharePoint的朋友在2013之前的版本可以使用社区协作下的记事板.应用程序下的通知,来进行消息的发布,而且更有这两者的完美结合体讨论板,可供使用着根据站点属性进行添加而对现在的快消息时代, ...
- svn 几个常用命令(持续更新)
1:获取某个版本号(3583)下的代码 svn co http://tech.yoai.com:8300/c ...
- gradle学习笔记
一直想着花时间学习下gradle,今天有空.入门一下.参考:极客学院gradle使用指南,官方文档:gradle-2.12/docs/userguide/installation.html,以及百度阅 ...
- linux源码分析(二)-启动过程
前置:这里使用的linux版本是4.8,x86体系. 这篇是 http://home.ustc.edu.cn/~boj/courses/linux_kernel/1_boot.html 的学习笔记. ...
- 图片上传插件ImgUploadJS:用HTML5 File API 实现截图粘贴上传、拖拽上传
一 . 背景及效果 当前互联网上传文件最多的就是图片文件了,但是传统web图片的截图上传需要:截图保存->选择路径->保存后再点击上传->选择路径->上传->插入. 图片 ...