我正在爲我的項目進行演示。爲什麼圖像無法加載?
的XML文件如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<ImageView
android:id="@+id/imageview"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:visibility="visible"
android:layout_gravity="center"
android:contentDescription="@string/content_description"
/>
</LinearLayout>
而且我Activity
是繼到圖像加載到ImageView
。 作爲內部類實現AsyncTask
。
public class LoadImageActivity extends Activity {
ImageView image ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.load_image);
image = (ImageView)findViewById(R.id.imageview);
String url = "http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png";
LoadImageAsync loadImageAsync = new LoadImageAsync(url, image);
loadImageAsync.execute(url);
}
在Activity
的onCreate
方法我稱爲AsyncTask
加載圖像
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.load_image);
image = (ImageView)findViewById(R.id.imageview);
String url = "http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png";
LoadImageAsync loadImageAsync = new LoadImageAsync(url, image);
loadImageAsync.execute(url);
}
在AsyncTask
I類有以下代碼這是我跟着the Stack Overflow link related to this。
AsyncTask類低於此類,我將其作爲Activity類的內部類實現。
public class LoadImageAsync extends AsyncTask<String, Void, Bitmap>{
private String url;
private ImageView imageView;
public LoadImageAsync(String url, ImageView imageView) {
this.url = url;
this.imageView = imageView;
}
@Override
protected Bitmap doInBackground(String... params) {
try {
URL urlConnection = (URL) new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
super.onPostExecute(result);
}
}
我做了什麼錯?或者錯過了什麼?
處理圖像時需要考慮什麼?
然後,這將移動到GridView
加載圖像。
變化從這裏'loadImageAsync.execute(URL);''來loadImageAsync.execute();' – Piyush 2014-12-05 08:57:22