活动指示器不适用于异步任务

时间:2014-06-30 11:40:20

标签: android android-activity android-asynctask uiactivityindicatorview

当我使用asynctask方法时,活动指示器不起作用。 AsyncTask方法用于从URL下载图像并放入手机内存。以下是我的代码

btnSubmit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            AsyncCallWS aws = new AsyncCallWS();

            try {
                retData = aws.execute().get();
                Log.d(TAG, "STATUS is " + retData);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // Close the window and go back to login page
            Intent intent = new Intent(launchar.this, arcamera.class);
            intent.putExtra("url", url_);
            intent.putExtra(Strings.USERNAME, mUsername);
            intent.putExtra(Strings.PASSWORD, mPassword);
            intent.putExtra(Strings.COMP_ID, mCompId);
            startActivity(intent);


        }
    });

我的异步方法如下:

 private class AsyncCallWS extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        // Call the service

        HttpConnectionHelper helper = new HttpConnectionHelper(
                Constants.SERVICE_GETAR_URL);
        final String REQUEST_DATA = String.format(
                "<ReqData xmlns=\"http://www.ceolution.com/phone\"> "
                        + "<key>%s|%s|%s</key>" + "</ReqData>", mUsername,
                mPassword, mCompId);
        try {
            helper.setRequestMethod(HttpPost.METHOD_NAME);
            helper.setPostData(REQUEST_DATA);
            helper.setHeader("Content-Type", "application/xml");

            int code = helper.getResponseCode();
            if (Constants.LOG_ENABLED) {
                Log.i(TAG, "Response code = " + code);
            }
            if (code == HttpURLConnection.HTTP_OK) {
                String data = helper.getResponseData();
                if (Constants.LOG_ENABLED) {
                    Log.v(TAG, "Response Data - " + data);
                }
                ARParser par = new ARParser();
                String data_ = par.ParseAR(data);
                Log.i(TAG, "RETURN DATA IS " + data_);

                // Get Object

                BufferedReader br = new BufferedReader(new StringReader(
                        data_));
                InputSource is = new InputSource(br);

                // Create XML Parser
                ARXMLFormatter parser = new ARXMLFormatter();

                SAXParserFactory factory = SAXParserFactory.newInstance();
                SAXParser sp = factory.newSAXParser();
                XMLReader reader = sp.getXMLReader();
                reader.setContentHandler(parser);
                reader.parse(is);

                myData = parser.itemList;

                if (myData != null) {

                    String OutputData = "";
                    Location itemLocation = null;
                    for (Item item : myData) {
                        if (item != null) {
                            itemLocation = new Location("");
                            itemLocation.setLatitude(Double
                                    .parseDouble(item.getLat()));
                            itemLocation.setLongitude(Double
                                    .parseDouble(item.getLg()));

                            if (location != null) {
                                float distanceInMeters = itemLocation
                                        .distanceTo(location);
                                Log.d(TAG, "distanceInMeters is "
                                        + distanceInMeters);

                                if (distanceInMeters <= Double
                                        .parseDouble(item.getR())) {
                                    // Must have to clean the directory
                                    // before
                                    // writing data
                                    File savefilepath1 = new File(
                                            COURSE_ZIP_FILE_PATH);
                                    cleanDirectory(savefilepath1);

                                    Image realData = null;
                                    String imageName = "";
                                    for (int k = 0; k < 8; k++) {
                                        realData = null;
                                        imageName = "";
                                        switch (k) {
                                        case 0: {
                                            realData = item.getN();
                                            imageName = "n.png";

                                            break;
                                        }
                                        case 1: {
                                            realData = item.getE();
                                            imageName = "e.png";
                                            break;
                                        }
                                        case 2: {
                                            realData = item.getS();
                                            imageName = "s.png";
                                            break;
                                        }
                                        case 3: {
                                            realData = item.getW();
                                            imageName = "w.png";
                                            break;
                                        }
                                        case 4: {
                                            realData = item.getNe();
                                            imageName = "ne.png";
                                            break;
                                        }
                                        case 5: {
                                            realData = item.getNw();
                                            imageName = "nw.png";
                                            break;
                                        }
                                        case 6: {
                                            realData = item.getSe();
                                            imageName = "se.png";
                                            break;
                                        }
                                        case 7: {
                                            realData = item.getSw();
                                            imageName = "sw.png";
                                            break;
                                        }
                                        }
                                        url_[k] = realData.getL();
                                        boolean status = false;
                                        if (realData.getU() != ""
                                                && realData.getU() != null)
                                            status = DownloadFile(
                                                    realData.getU()
                                                            .replace(
                                                                    "http",
                                                                    "https"),
                                                    imageName);
                                        Log.d(TAG, "Download status is "
                                                + status);
                                    }

                                    Log.d(TAG,
                                            "This is the item to processed");
                                    return "SUCCESS";
                                }

                                OutputData = OutputData + item.toString();
                            } else
                                return "GPSISSUE";
                        } else
                            Log.e("Items", "No details");
                    }

                    Log.d(TAG, "OutputData data is " + OutputData);
                }

                return "NODATA";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return "ERROR";
        }
        return "NODATA";
    }

XML文件位于

之下
 <FrameLayout

    android:id="@+id/laucnh_layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true" >

 <ImageView
        android:id="@+id/btnSubmit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:background="@drawable/launch"
        android:onClick="@string/onClick"
          android:scaleType="center" />
</FrameLayout>

即使我试图将活动指标放在onPreExecute()中,onPostExecute()也不起作用。

我不确定可能是什么原因。

请帮忙。

1 个答案:

答案 0 :(得分:0)

您必须将asyncTask中的更新发布到UI。这是一个例子。因此,在onProgressUpdate函数中,您可以更新UI。我希望这会有所帮助。

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }