如何将这些方法放入异步任务?

时间:2011-07-20 17:23:37

标签: android

我试图在asynctask中运行这些方法,因此它不会阻塞我的主UI。

有人可以举例说明如何做到这一点吗?

07-20 17:36:44.550: ERROR/AndroidRuntime(589): Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.


public void getImages() throws IOException{

    DefaultHttpClient httpclient = new DefaultHttpClient();

    HttpGet httppost = new HttpGet("https://sites.google.com/site/theitrangers/images/webImages.txt");
    HttpResponse response;

        response = httpclient.execute(httppost);


            HttpEntity ht = response.getEntity();

            BufferedHttpEntity buf = new BufferedHttpEntity(ht);

            InputStream is = buf.getContent();


            BufferedReader r = new BufferedReader(new InputStreamReader(is));

            StringBuilder total = new StringBuilder();
            String line;
            while ((line = r.readLine()) != null) {
                total.append(line + "\n");

              imageUrl = total.toString();
            }

            }
            public void getImage2() throws IOException{

                DefaultHttpClient httpclient = new DefaultHttpClient();

                HttpGet httppost = new HttpGet("https://sites.google.com/site/theitrangers/images/webImage2.txt");
                HttpResponse response;

                    response = httpclient.execute(httppost);


                        HttpEntity ht = response.getEntity();

                        BufferedHttpEntity buf = new BufferedHttpEntity(ht);

                        InputStream is = buf.getContent();


                        BufferedReader r = new BufferedReader(new InputStreamReader(is));

                        StringBuilder total = new StringBuilder();
                        String line;
                        while ((line = r.readLine()) != null) {
                            total.append(line + "\n");

                          imageUrl2 = total.toString();

                        }

}
            public class ImageAdapter extends BaseAdapter {
                /** The parent context */
                private Context myContext;public ImageAdapter() {
                    // TODO Auto-generated constructor stub
                }
                /** URL-Strings to some remote images. */

                private String[] myRemoteImages = {imageUrl,imageUrl2};






                /** Simple Constructor saving the 'parent' context. */
                public ImageAdapter(Context c) { this.myContext = c; }

                public ImageAdapter(MyTask myTask) {
                    // TODO Auto-generated constructor stub
                }

                /** Returns the amount of images we have defined. */
                public int getCount() { return this.myRemoteImages.length; }

                /* Use the array-Positions as unique IDs */
                public Object getItem(int position) { return position; }
                public long getItemId(int position) { return position; }

                /** Returns a new ImageView to
                * be displayed, depending on
                * the position passed. */
                public View getView(int position, View convertView, ViewGroup parent) {
                ImageView i = new ImageView(this.myContext);

                try {
                                /* Open a new URL and get the InputStream to load data from it. */
                                URL aURL = new URL(myRemoteImages[position]);
                                URLConnection conn = aURL.openConnection();
                                conn.connect();
                                InputStream is = conn.getInputStream();  
                                /* Buffered is always good for a performance plus. */
                                BufferedInputStream bis = new BufferedInputStream(is);
                                /* Decode url-data to a bitmap. */
                                Bitmap bm = BitmapFactory.decodeStream(bis);
                                bis.close();
                                is.close();

                                /* Apply the Bitmap to the ImageView that will be returned. */
                                i.setImageBitmap(bm);
                        } catch (IOException e) {

                                Log.e("DEBUGTAG", "Remtoe Image Exception", e);
                        }

                /* Image should be scaled as width/height are set. */
                i.setScaleType(ImageView.ScaleType.FIT_CENTER);
                /* Set the Width/Height of the ImageView. */
                i.setLayoutParams(new Gallery.LayoutParams(150, 150));
                return i;
                }

                /** Returns the size (0.0f to 1.0f) of the views
                * depending on the 'offset' to the center. */
                public float getScale(boolean focused, int offset) {
                /* Formula: 1 / (2 ^ offset) */
                return Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset)));
                }
                }






                private class MyTask extends AsyncTask<Void, Void, Void>{

                protected void onPreExecute(){

                    String imageUrl = null;
                       String imageUrl2 = null;
                }

                @Override
                protected Void doInBackground(Void... arg0) {

                     try {
                            getImages();
                            getImage2();
                        } catch (IOException e) {
                            Log.e("MainMenu retreive image", "Image Retreival failed");
                            e.printStackTrace();
                        }
                        ((Gallery) findViewById(R.id.gallery))
                        .setAdapter(new ImageAdapter(this));
                    return null;
                }

}

}

2 个答案:

答案 0 :(得分:1)

This guide将解释您开始使用AsyncTask所需的一切。

总结:

  • 将网络提取/耗时代码放在doInBackground
  • 处理onPostExecute
  • 中UI线程上的输出

答案 1 :(得分:1)

您得到的错误是“只有创建视图层次结构的原始线程才能触及其视图。”

这个错误是因为你在另一个线程中处理UI,所以要解决这个问题,你只需要像这样更新UI。

Activityname.this.runOnUiThread(new Runnable() {

        @Override
        public void run() {

            update the UI here......

        }
    });