1

Наследую AsyncTask и переопределяю методы onPostExecute, onPreExecute, doInBackground. После вызова doInBackground не следует вызов onPostExecute в UI потоке. isCancelled() все это время возвращает false. Может дело в UI потоке (в самой Activity)?

Код

class MainActivity

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        InternetImageAdapter adapter = new InternetImageAdapter(this);
        ListView lv = ((ListView) findViewById(R.id.elementsListView));
        lv.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

class InternetImageAdapter

public class InternetImageAdapter extends BaseAdapter {

    private AsyncImageLoader imageLoader;
    private HashMap<String, String> urls;
    private Context context;

    public InternetImageAdapter(Context context) {
        super();
        this.context = context;
        imageLoader = new AsyncImageLoader(context);
        urls = new HashMap<String, String>();
        urls.put("img25", "https://www.dropbox.com/s/bufrchggsob2j6t/WRC-1.jpg");
    }

    @Override
    public int getCount() {
        return urls.size();
    }

    @Override
    public Object getItem(int position) {
        return urls.values().toArray()[position];
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @SuppressLint("NewApi")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {    
        View view = null;
        LayoutInflater inflater = (LayoutInflater) getContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.list_image_item, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.imageView);

        if (imageView != null) {
            String key = (String) urls.keySet().toArray()[position];
            String url = urls.get(key);

            imageLoader.setImageViewReference(key, imageView);
            imageLoader.start(url);
        }
        return view;
    }

    private Context getContext() {
        return context;
    }
}

class AsyncDataLoader

public abstract class AsyncDataLoader<T> extends
        AsyncTask<String, Void, AsyncTaskResult<T>> {

    protected Context context;
    protected BaseLoaderStrategy<T> dataLoader;
    private static final int MAX_READ_TIMEOUT = 10000; // ms
    private static final int MAX_CONNECT_TIMEOUT = 15000; // ms

    public AsyncDataLoader(Context context, BaseLoaderStrategy<T> dataLoader) {
        super();
        this.context = context;
        this.dataLoader = dataLoader;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected AsyncTaskResult<T> doInBackground(String ... params) {
        AsyncTaskResult<T> resultData = null;

        if(!isCancelled()) {
            resultData = new AsyncTaskResult<T>();
            try {
                if (!checkConnection()) {
                    throw new LoadDataException("Cannot get connection");
                }
                List<T> dataList = loadData(params[0]);
                resultData.setData(dataList);
            } catch (LoadDataException e) {
                resultData.setError(e);
            } 
        }
        return resultData;
    }

    @Override
    protected void onPostExecute(AsyncTaskResult<T> result) {
        super.onPostExecute(result);
        if(result != null) {
            if (result.getError() == null) {
                onSuccess(result.getData());
            } else {
                onError(result.getError());
            }
        }
    }

    protected abstract void onError(Exception error);
    protected abstract void onSuccess(List<T> data);

    private List<T> loadData(String streamUrl) throws LoadDataException {
        InputStream is = null;
        List<T> resultData = null;

        try {
            URL url = new URL(streamUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(MAX_CONNECT_TIMEOUT);
            conn.setReadTimeout(MAX_READ_TIMEOUT);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();

            is = conn.getInputStream();

            if (is != null) {
                resultData = dataLoader.loadData(is);
            } else {
                throw new LoadDataException();
            }

        } catch (MalformedURLException e) {
            throw new LoadDataException(e);
        } catch (IOException e) {
            throw new LoadDataException(e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    throw new LoadDataException(e);
                }
            }
        }
        return resultData;
    }

    public void start(String url) {
        if (Build.VERSION.SDK_INT > 10) {
            executeOnExecutor(THREAD_POOL_EXECUTOR, url);
        } else {
            execute(url);
        }
    }

    private boolean checkConnection() {
        ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        } else {
            return false;
        }
    }
}

class AsyncImageLoader

public class AsyncImageLoader extends AsyncDataLoader<Bitmap> {

    private ImageView imageView;
    private String imageKey;

    private LruCache<String, Bitmap> lruCache;
    private static int MB = 1024 * 1024;

    public AsyncImageLoader(Context context) {
        super(context, new ImageLoaderStrategy());

        ActivityManager activityMngr = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        int memClass = activityMngr.getMemoryClass();

        lruCache = new LruCache<String, Bitmap>(memClass * MB) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes() * value.getWidth();
            }

            @Override
            protected void entryRemoved(boolean evicted, String key,
                    Bitmap oldValue, Bitmap newValue) {    
                if (evicted) {
                    oldValue.recycle();
                }
                if (newValue != null) {
                    newValue.recycle();
                }
            }
        };
    }

    public void setImageViewReference(String imageKey, ImageView imageView) {
        this.imageKey = imageKey;
        this.imageView = imageView;
    }

    @Override
    protected void onPreExecute() {
        Bitmap bitmap = lruCache.get(imageKey);

        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
            cancel(true);
        }
    }

    @Override
    public void onError(Exception error) {
    }

    @Override
    public void onSuccess(List<Bitmap> data) {
        if (data.size() > 0) {
            Bitmap bitmap = data.get(0);

            lruCache.put(imageKey, bitmap);
            imageView.setImageBitmap(bitmap);
        }
    }
}

1 ответ 1

2

Вызывать doInBackground не надо

Надо делать примерно так:

YourAsyncTask task = new YourAsyncTask();
task.execute();

Либо, если я неправильно понял ваш вопрос, неплохо увидеть код и тогда будет легче что-то подсказать

2
  • нет, я вызываю как вы и писали. выложил код 13 ноя 2012 в 9:35
  • По-моему у меня когда-то была похожая проблема и была она в методе getView(...) у адаптера (попробуйте посмотреть хотя бы сколько раз у вас вызывается этот метод и проследите его работу)
    – misha_m
    13 ноя 2012 в 10:42

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.