2011-09-06 89 views
0
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()); 

但图像并不总是显示。图像随机出现并消失,请你帮助我吗?

+0

做u得到的堆栈跟踪任何错误? – blessenm

+0

你有位图本身吗?请检查System.out.println(“Bitmap ::”+ p.bitmap); –

+0

您可能不应该在decodeStream方法内完成所有的逻辑。您拥有它的方式不仅无法调试任何问题(您目前拥有这些问题),但您无法处理故障。当下载远程URL是你逻辑的一部分时,几乎总是保证有这种情况发生,这是一个好主意,总是有代码来处理故障,并可选择记录它们,重试等。 – Rich

回答

0

根据this link,以前版本的BitmapFactory.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); 
+0

它工作得很好,非常感谢! – aamethk