0

我有以下代码我想在显示进度对话框时执行(向数据库添加一行):

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 和线程,但没有任何效果,有时它可以工作,但在添加帖子后会显示进度对话框,请问有什么帮助吗?

4

1 回答 1

0

要做到这一点,您需要像 Mounzer 所说的那样使用 AyncTask。要做一个progressBar,你将不得不上传一些数据,回来更新你的progressBar,加载更多数据等等。

幸运的是,AsyncTask 使这很容易做到。这个非常简单的示例计数到 1000,并且在每次迭代时使用 TextView 发布结果。您可以轻松地将其更改为 progressBar 并将您的 http 邮政编码放入 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;


        }

}
于 2013-03-29T22:08:06.307 回答