在显示进度对话框时,我有以下代码要执行(向数据库添加一行):
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://192.168.1.38/hu/Addpost.php?username="+username+"&fname="+firstname+"&lname="+lastname+"&dop="+now+"&content="+post3+"&type="+post_type2+"");
try
{
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("FirstN",firstname));
nameValuePairs.add(new BasicNameValuePair("LastN",lastname));
nameValuePairs.add(new BasicNameValuePair("Content",post1));
nameValuePairs.add(new BasicNameValuePair("type",post_type));
nameValuePairs.add(new BasicNameValuePair("Dateofp",now));
nameValuePairs.add(new BasicNameValuePair("username",username));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
if(response.getStatusLine().getStatusCode()==200)
{
entity=response.getEntity();
if(entity !=null)
{
Toast.makeText(getBaseContext(),"POST SUCCESFULLY ADDED",Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getBaseContext(),"ERROR RERTY OR CHECK YOUR CONNECTION",Toast.LENGTH_LONG).show();
}
wholepost.setText("");
}
catch(Exception ex)
{Toast.makeText(getBaseContext(),"CONNECTION ERROR",Toast.LENGTH_LONG).show();}
我已经尝试过AsyncTask和线程,但没有任何效果,有时它可以工作但是在添加帖子后显示了进度对话框,请问有什么帮助吗?
答案 0 :(得分:0)
要做到这一点,你需要使用AyncTask,因为Mounzer说。要进行progressBar,您将不得不上传数据,返回并更新progressBar,加载更多数据等。
幸运的是,AsyncTask使这很容易。这个非常简单的例子计为1000 并在每次迭代时使用TextView发布结果。您可以轻松地将其更改为progressBar并将您的http post代码放在doInBVackground()
中protected class InitTask extends AsyncTask<Integer, String, Void> {
// add the thread ID and count to the list
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
TextView tv = new TextView(mContext);
mThreadOutput.addView(tv);
tv.setText(values[0]);
}
// do the thread work. at each iteration, set the progress to be
// updated by the UI thread
protected Void doInBackground(Integer... params ) {
for (int i = 0; i < 1000; i++) {
String s = "Thread " + params[0] + ": " + i;
publishProgress( s );
}
return null;
}
}