2011-09-06 81 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