I am working a demo for my project.
The XML file is as follow:
<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>
And my Activity
is following to load the image into ImageView
.
Implemented AsyncTask
as inner class.
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);
}
In Activity
's onCreate
method I called the AsyncTask
to load 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);
}
In AsyncTask
class I have the following code which is I followed the Stack Overflow link related to this.
The AsyncTask class is below which I implemented as inner class to the Activity class.
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);
}
}
What wrong I did? or anything missed?
What are all need to consider when working on images?
And after this will move to loading images with GridView
.