Android – how do I add threads?
•
Android
This continues from this post's question
I can't imagine how to add a separate thread from the main UI thread to collect data from the server. I've never been a thread before. I think this instance in my constructed class is more advanced than any example I can find
Any help and revision of my course will be appreciated
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));
}
Please refer to the answers below
resolvent:
You should simply use asynctask
This is a good tutorial on how to use it tutorial
The following is an example of downloading a web page and returning the results to the main UI
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
@Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码