我正在使用下面的功能从服务器下载图像。这对除Android2.2Froyo设备之外的所有Android版本都是完美的。请帮忙。
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;
}
最佳答案
试试这个代码。
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);
}
关于java - 从服务器下载图像位图在Android 2.2上返回null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12246914/