图像查看问题

时间:2011-09-06 13:32:04

标签: android android-imageview

ImageView img;
TextView tv;
Parser p= new Parser();

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

    tv = (TextView) findViewById(R.id.txt);
    img = (ImageView) findViewById(R.id.cover);


    new AsyncTask<Void, Double, Void>() {

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

            while (true) {
                publishProgress(Math.random());
                SystemClock.sleep(3000);

            }
        }

        @Override
        protected void onProgressUpdate(Double... values) {


            p.myHandler();
            img.setImageBitmap(p.bitmap);
            tv.setText("Artist : " + p.artist + "\n" + 
                       "Album : " + p.album + "\n" + 
                       "Song : " + p.title + "\n");
        }
    }.execute();
}

以及

p.bitmap =  BitmapFactory.decodeStream((InputStream)new URL(image).getContent());

但图片并不总是显示。图像会随机出现并随意消失吗?

1 个答案:

答案 0 :(得分:0)

根据this linkBitmapFactory.decodeStream的先前版本中存在错误。它至少存在于Android 2.1 SDK中。

这个类解决了这个问题:

class FlushedInputStream extends FilterInputStream {
    public FlushedInputStream(InputStream inputStream) {
        super(inputStream);
    }

    @Override
    public long skip(long n) throws IOException {
        long totalBytesSkipped = 0L;
        while (totalBytesSkipped < n) {
            long bytesSkipped = in.skip(n - totalBytesSkipped);
            if (bytesSkipped == 0L) {
                  int ibyte = read();
                  if (ibyte < 0) {
                      break;  // we reached EOF
                  } else {
                      bytesSkipped = 1; // we read one byte
                  }
           }
            totalBytesSkipped += bytesSkipped;
        }
        return totalBytesSkipped;
    }
}

应该下载图片:

//I'm not sure whether this line works, but just in case I use another approach
//InputStream is = (InputStream)new URL(image).getContent()
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(imageUrl);
HttpResponse response = client.execute(request);
InputStream is = response.getEntity().getContent();
//Use another stream
FlushedInputStream fis = new FlushedInputStream(is);
bmp = BitmapFactory.decodeStream(fis);