Question

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();
}

and also

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

but the image doesn't always show. The image appears and disappears randomly can you help me please?

Was it helpful?

Solution

According to this link, there is a bug in the previous versions of BitmapFactory.decodeStream. It exists at least at the Android 2.1 SDK.

This class fixes the problem:

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;
    }
}

And image should be downloaded so:

//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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top