【问题标题】:Fatal Exception: Exception in do in background method (AsyncTask)致命异常:后台方法中的异常(AsyncTask)
【发布时间】:2014-12-29 13:18:14
【问题描述】:

我的应用程序从列表中的服务器加载图像时遇到问题。我的应用程序在列表中显示 5 张图片。问题是应用程序何时应该加载第六张图片。这有点奇怪,因为应用程序加载了 5 张图片。这是我的延迟加载图像适配器

public class FlowerAdapter extends ArrayAdapter<Flower> {

private Context context;
private List<Flower> flowerList;

public FlowerAdapter(Context context, int resource, List<Flower> objects) {
    super(context, resource, objects);
    this.context = context;
    this.flowerList = objects;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = 
            (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.item_flower, parent, false);

    //Display flower name in the TextView widget
    Flower flower = flowerList.get(position);
    TextView tv = (TextView) view.findViewById(R.id.textView1);
    tv.setText(flower.getPhoto());

    //Display flower photo in ImageView widget
    if (flower.getBitmap() != null) {
        ImageView image = (ImageView) view.findViewById(R.id.imageView1);
        image.setImageBitmap(flower.getBitmap());
    }
    else {
        FlowerAndView container = new FlowerAndView();
        container.flower = flower;
        container.view = view;

        ImageLoader loader = new ImageLoader();
        loader.execute(container);
    }


    return view;
}

class FlowerAndView {
    public Flower flower;
    public View view;
    public Bitmap bitmap;
}

private class ImageLoader extends AsyncTask<FlowerAndView, Void, FlowerAndView> {

    @Override
    protected FlowerAndView doInBackground(FlowerAndView... params) {

        FlowerAndView container = params[0];
        Flower flower = container.flower;

        try {
            String imageUrl = MainActivity.PHOTOS_BASE_URL + flower.getPhoto();
            InputStream in = (InputStream) new URL(imageUrl).getContent();
            Bitmap bitmap = BitmapFactory.decodeStream(in);
            flower.setBitmap(bitmap);
            in.close();
            container.bitmap = bitmap;
            return container;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(FlowerAndView result) {
        ImageView image = (ImageView) result.view.findViewById(R.id.imageView1);
        image.setImageBitmap(result.bitmap);
        result.flower.setBitmap(result.bitmap);
    }

}

}

这是我的活动代码

public class MainActivity extends ListActivity {

public static final String PHOTOS_BASE_URL = 
    "http://autoskola.1e29g6m.xip.io/images/";

TextView output;
ProgressBar pb;
List<MyTask> tasks;

List<Flower> flowerList;

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

    pb = (ProgressBar) findViewById(R.id.progressBar1);
    pb.setVisibility(View.INVISIBLE);

    tasks = new ArrayList<>();
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_get_data) {
        if (isOnline()) {
            requestData("http://autoskola.1e29g6m.xip.io/webservices/files.php");
        } else {
            Toast.makeText(this, "Network isn't available", Toast.LENGTH_LONG).show();
        }
    }
    return false;
}

private void requestData(String uri) {
    MyTask task = new MyTask();
    task.execute(uri);
}

protected void updateDisplay() {
    //Use FlowerAdapter to display data
    FlowerAdapter adapter = new FlowerAdapter(this, R.layout.item_flower, flowerList);
    setListAdapter(adapter);
}

protected boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    } else {
        return false;
    }
}

private class MyTask extends AsyncTask<String, String, List<Flower>> {

    @Override
    protected void onPreExecute() {
        if (tasks.size() == 0) {
            pb.setVisibility(View.VISIBLE);
        }
        tasks.add(this);
    }

    @Override
    protected List<Flower> doInBackground(String... params) {

        String content = HttpManager.getData(params[0]);
        flowerList = FlowerJSONParser.parseFeed(content);

        return flowerList;
    }

    @Override
    protected void onPostExecute(List<Flower> result) {

        tasks.remove(this);
        if (tasks.size() == 0) {
            pb.setVisibility(View.INVISIBLE);
        }

        if (result == null) {
            Toast.makeText(MainActivity.this, "Web service not available", Toast.LENGTH_LONG).show();
            return;
        }

        flowerList = result;
        updateDisplay();

    }

}

}

这就是我的应用程序崩溃时我的 logcat 所说的

12-29 13:02:55.057: E/AndroidRuntime(1113): FATAL EXCEPTION: AsyncTask #3
12-29 13:02:55.057: E/AndroidRuntime(1113): java.lang.RuntimeException: An error  occured while executing doInBackground()
12-29 13:02:55.057: E/AndroidRuntime(1113):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
12-29 13:02:55.057: E/AndroidRuntime(1113):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
12-29 13:02:55.057: E/AndroidRuntime(1113):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
12-29 13:02:55.057: E/AndroidRuntime(1113):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
12-29 13:02:55.057: E/AndroidRuntime(1113):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
12-29 13:02:55.057: E/AndroidRuntime(1113):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
12-29 13:02:55.057: E/AndroidRuntime(1113):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
12-29 13:02:55.057: E/AndroidRuntime(1113):     at java.lang.Thread.run(Thread.java:841)
12-29 13:02:55.057: E/AndroidRuntime(1113): Caused by: java.lang.OutOfMemoryError
12-29 13:02:55.057: E/AndroidRuntime(1113):     at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
12-29 13:02:55.057: E/AndroidRuntime(1113):     at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:530)
12-29 13:02:55.057: E/AndroidRuntime(1113):     at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:603)
12-29 13:02:55.057: E/AndroidRuntime(1113):     at com.hanselandpetal.catalog.FlowerAdapter$ImageLoader.doInBackground(FlowerAdapter.java:79)
12-29 13:02:55.057: E/AndroidRuntime(1113):     at com.hanselandpetal.catalog.FlowerAdapter$ImageLoader.doInBackground(FlowerAdapter.java:1)
12-29 13:02:55.057: E/AndroidRuntime(1113):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
12-29 13:02:55.057: E/AndroidRuntime(1113):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
12-29 13:02:55.057: E/AndroidRuntime(1113):     ... 4 more

如果有人知道我在哪里做错了,请帮忙。

非常感谢。

【问题讨论】:

  • 为了在后台加载图像,您可以使用一些库,如毕加索或通用图像加载器。
  • 是的,我知道 Picasso,但我不知道为什么我的应用在 5 张图片后崩溃。应用程序应该加载大约 30 张图像,但在第五张之后,应用程序崩溃了。如果应用加载 5 张图片,为什么应用无法加载全部 30 张图片。我认为这段代码工作正常,但也许有一些我看不到
  • 因为您设备上的法律内存。从日志中清除它显示 java.lang.OutOfMemoryError。因此,请检查您设备的内存。
  • 图片太大了尝试缩放位图,一些第三方库会减轻你的任务。
  • 是的,我知道,我解决了这个问题。还是谢谢你:)

标签: android performance android-activity android-asynctask


【解决方案1】:

您可以使用通用加载器库从服务器下载图像。

1) https://github.com/nostra13/Android-Universal-Image-Loader

2) http://square.github.io/picasso/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多