I have a class that I borrowed from here that loads and image from a URL. I am trying to use the class by calling it from a onClickListener (if that makes sense) But I am not sure how to call the class and show the results. Right now I am just working with a static URL but eventually I it will be dynamic.
OnclickListerner in MainActivity Java:
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){
showImage go = new showImage();
}
});
and this is my showImage class:
package com.flash_tattoo;
public class showImage extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fullimage);
ImageView imgView =(ImageView)findViewById(R.id.ImageView01);
String url = null;
Drawable drawable = LoadImageFromWebOperations("http://www.androidpeople.com/wp-content/uploads/2010/03/android.png");
imgView.setImageDrawable(drawable);
}
private Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
System.out.println("Exc="+e);
return null;
}
}
}
Do I need to call a new layout and then attach my showImage object to it? Any help would be great. Thanks in Advance.
First point, Java naming conventions have class names capitalised, this allows anybody reading the code to instantly know what’s what. Please rename the
showImageclass.Secondly, this will cause a long running operation to happen in the UI thread, this is best done with an AsyncTask – see this article on Painless Threading – or a new Thread with a Handler. Long running operations on the UI thread will block any input handler events from being processed in a timely fashion and could cause your application to become unresponsive, especially with a slow mobile connection. Consider adding a progress bar or some method of letting the user know that the application is still doing something while they wait.
To answer the original question, it looks like
showImageis anActivity. This means that inside the listener you don’t need to create a newshowImageobject, but rather fire off anIntentto view thatActivity. Assuming you have the correct layout files I don’t see anything that won’t work here.You also seem to have an unused variable,
String url = null;is not needed.Edit: You also shouldn’t really be using
System.out.println(), although it will have the desired results. The standard method of logging in Android is to use the LogCat system.As suri has mentioned, it’s also not necessary to have an entire new
Activityto show your image. If you move theshowImageclass functions into your firstActivityand add anImageViewto the first layout, you can load the image in the sameActivityas the button.