这是从this post's Question继续。如何添加线程?
我无法计算如何从主UI线程添加单独的线程来完成从服务器收集数据的工作。我之前从来没有做过线程,我认为这个实例在我构建的类中使得它比我可以找到的任何示例更先进一点。
任何帮助和我班的修改稿将不胜感激。
Thank_you!
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
setContentView(R.layout.list_view2);
/**
* Get the query string from last activity and pass it to this
* activity-----------------------------------------------------
*/
String p = null;
if (extras != null) {
p = extras.getString(PHP_KEY);
}
loadQuery(p);
}
void loadQuery(String p) {
String qO = getIntent().getStringExtra("QUERY_ORDER");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/App/php/" +
p + qO + ".php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
setListAdapter(new QueryAdapter(this, result));
}
见下
你应该看看:HTTP://developer.android.com/reference/android/os/Handler.html这是管理出来的UI线程的最简单的方法和将结果或数据传输到UI线程。 – 2012-01-06 22:10:27
Thnx。我做了,我不能想出一个方法来实现它到我的代码W/O编译错误。 @Jeremy D – CelticParser 2012-01-06 22:13:32
@JeremyD我不知道。我认为http://developer.android.com/reference/android/os/AsyncTask.html实际上更容易。你总是保证在主线程中运行onPostExecute()。处理程序在创建它的线程中运行。 – AedonEtLIRA 2012-01-06 22:14:46