2012-09-03 65 views
3

我使用下面的函數從服務器下載圖像。這適用於除Android 2.2 Froyo設備以外的所有Android版本。請幫忙。從服務器下載圖像位圖在Android 2.2上返回null

private Bitmap downloadImage(String url) { 
     System.out.println("Splash Ad downloadImage Url " + url); 
     Bitmap bm = null; 
     try { 
      URL aURL = new URL(url); 
      URLConnection conn = aURL.openConnection(); 
      conn.connect(); 
      InputStream is = conn.getInputStream(); 
      BufferedInputStream bis = new BufferedInputStream(is); 
      bm = BitmapFactory.decodeStream(bis); 
      bis.close(); 
      is.close(); 
     } catch (IOException e) { 
      Log.e("Hub", "Error getting the image from server : " 
        + e.getMessage().toString()); 
      e.printStackTrace(); 
     } 
     return bm; 
    } 
+0

什麼是錯誤?你有什麼嘗試? – njzk2

+0

沒有錯誤/異常它只是返回空位圖。 –

+0

你試過了什麼?你檢查過文件是否存在,輸入流是否被讀取,圖像是否可以被解碼? – njzk2

回答

0

試試看看這個代碼。

public class ImageDisplay extends Activity { 
     ImageView image; 
     ProgressBar spinner; 
     TextView message; 
     String path; 
@Override 
     public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_image_display); 
    image=(ImageView) findViewById(R.id.imageDisplay); 
    spinner=(ProgressBar)findViewById(R.id.progressBar_spinner); 
    message=(TextView)findViewById(R.id.textView1); 
    spinner.setVisibility(View.INVISIBLE); 
    displayImage(); 
} 
     private class DownloadImage extends AsyncTask<String, Void,Bitmap > 
      { 
Bitmap bitmap; 
String error_messsage="No error"; 
@Override 
protected Bitmap doInBackground(String... urls) { 
    for(String url:urls){ 
    HttpUriRequest request = new HttpGet(url.toString()); 
     HttpClient httpClient = new DefaultHttpClient(); 
     try { 
      HttpResponse response = httpClient.execute(request); 
      StatusLine statusLine = response.getStatusLine(); 
      int statusCode = statusLine.getStatusCode(); 
      if (statusCode == 200) { 
       HttpEntity entity = response.getEntity(); 
       byte[] bytes = EntityUtils.toByteArray(entity); 
      Log.e("here",""+bytes.length); 
       bitmap = BitmapFactory.decodeByteArray(bytes, 0,bytes.length); 
       Thread.sleep(1000); 
      } 
      else 
      { 
       error_messsage="Download failed, HTTP response code "+ statusCode + " - " + statusLine.getReasonPhrase();     
      } 
     } catch (Exception er) { 
      Log.e("Error",""+er); 
     }} 
     //image.setImageBitmap(bitmap); 
    return bitmap ; 
} 

@Override 
protected void onPostExecute(Bitmap result) { 
    spinner.setVisibility(View.INVISIBLE); 
    image.setImageBitmap(result); 

} 
    } 
    public void displayImage() 
    { 

    DownloadImage task = new DownloadImage(); 
    task.execute(new String[] { "http://team-android.com/wp-    content/uploads/2011/03/Android-3d_428.jpg" }); 
    snap.setVisibility(View.VISIBLE); 

    } 
相關問題