我创建了一个Android应用程序来从我的本地服务器下载图像,但我没能做到。我尝试了几次,但我没有成功。这是我创建的确切类的源代码,用于执行我想要的功能:
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>(4);
public static final String URL = "http://localhost/img/";
Button load_img;
ImageView imageview;
Bitmap bitmap;
ProgressDialog pDialog;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monitor);
load_img = (Button)findViewById(R.id.load);
imageview = (ImageView)findViewById(R.id.img);
load_img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new LoadImage().execute(new String[]{URL});
//img.setImageBitmap(bitmapArray.ge);
}
});
}
private class LoadImage extends AsyncTask<String, Void, Bitmap> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Monitor.this);
pDialog.setMessage("Fetching Images ....");
pDialog.show();
}
protected Bitmap doInBackground(String... urls) {
bitmap = null;
for(String url : urls){
bitmap = downloadImage(url);
}
//List<Bitmap> bitmap = new ArrayList<Bitmap>;
// bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
return bitmap;
}
private Bitmap downloadImage(String arg0){
bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try{
stream = getHttpConnection(arg0);
bitmap = BitmapFactory.decodeStream(stream, null,bmOptions);
stream.close();
}catch(Exception e){
e.printStackTrace();
}
bitmapArray.add(bitmap);
return bitmap;
}
protected void onPostExecute(Bitmap result) {
if(result != null){
imageview.setImageBitmap(bitmap);
pDialog.dismiss();
}else{
pDialog.dismiss();
Toast.makeText(Monitor.this,"Failed in downloading the image", Toast.LENGTH_SHORT).show();
}
}
//creating open connection
private InputStream getHttpConnection(String urlString) throws IOException{
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if(httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
stream = httpConnection.getInputStream();
}
}catch(Exception e){
e.printStackTrace();
}
return stream;
}
}
}