我使用AsyncTask
类来连接数据库。根据数据,我将创建动态EditText
,Checkbox
,而不涉及XML文件。
lView = new LinearLayout(this);
- 我在这里遇到了错误!
有没有办法在doInBackground
方法中调用UI线程!
提前致谢!!
@Override
protected String doInBackground(String... param) {
HashMap<String, bean> map = new HashMap<String, bean>();
try {
url = new URL("http://localhost/app/alldata.php");
} catch (MalformedURLException e) {
Toast.makeText(getApplicationContext(), "URL Exception", Toast.LENGTH_LONG).show();
e.printStackTrace();
return null;
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("user_id", "user_id")
.appendQueryParameter("dpt_id","dptid");
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
int response_code = conn.getResponseCode();
lView = new LinearLayout(this);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return null;
}
答案 0 :(得分:3)
您可以从publishProgress()
方法调用doInBackground
并覆盖将在UI线程上调用的onProgressUpdate
。
显然,这是用于进步的用法。您应该明确区分一个工作单元作为背景,然后在onPostExecute
中正常处理。
答案 1 :(得分:1)
如果您真的想与主UI线程进行通信,可以使用:
runOnUiThread(new Runnable() {
@Override
public void run() {
//place your code here
}
});
答案 2 :(得分:0)
更优雅的方法是传递回调函数,以便在AsyncTask
完成其工作时,它可以调用Activity
中的方法调用,然后您可以在那里进行必要的更改。
我建议保留这样的界面。
public interface HttpResponseListener {
void httpResponseReceiver(String result);
}
现在,在Activity
中,您需要实现此侦听器,并且在执行AsyncTask
时,您还需要将侦听器传递给AsyncTask
。
public YourActivity extends Activity implements HttpResponseListener {
// ... Other functions
@Override
public void httpResponseReceiver(String result) {
int response_code = (int) Integer.parseInt(result);
// Take necessary actions here
lView = new LinearLayout(this);
}
}
现在,在您的AsyncTask
中,您需要先将变量作为Activity
的聆听者。
public class HttpRequestAsyncTask extends AsyncTask<Void, Void, String> {
// Declare the listener here
public HttpResponseListener mHttpResponseListener;
@Override
protected String doInBackground(String... param) {
HashMap<String, bean> map = new HashMap<String, bean>();
try {
url = new URL("http://localhost/app/alldata.php");
} catch (MalformedURLException e) {
Toast.makeText(getApplicationContext(), "URL Exception", Toast.LENGTH_LONG).show();
e.printStackTrace();
return null;
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("user_id", "user_id")
.appendQueryParameter("dpt_id","dptid");
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
// int response_code = conn.getResponseCode(); // Return the result to onPostExecute
// lView = new LinearLayout(this); // Remove this from here
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return conn.getResponseCode() + "";
}
// Set the result here
@Override
protected void onPostExecute(final String result) {
mHttpResponseListener.httpResponseReceiver(result);
}
}
现在,从Activity
开始AsyncTask
启动HttpRequestAsyncTask mHttpRequestAsyncTask = new HttpRequestAsyncTask();
mHttpRequestAsyncTask.mHttpResponseListener = YourActivity.this;
// Start your AsyncTask
mHttpRequestAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
,您需要首先像这样分配侦听器。
{{1}}
希望有所帮助!