Wednesday, April 18, 2012

Android change view from other thread

I wrote a code to download an image from internet. And i have to show it in a ImageView which is dynamically created.

And i am getting an error that Only the original thread that created a view hierarchy can touch its views. I know i have to write a handle but how can i do that?


Here is my code :

public class ResimCek implements Runnable {

int resimID = 0;

public ResimCek(int parcaID) {
// store parameter for later user
resimID = parcaID;

public void run() {

int resID = getResources().getIdentifier(Integer.toString(resimID) , "tag", getPackageName());
ImageView resim = (ImageView) findViewById(resID);

Drawable image = ImageOperations(getBaseContext(),"" + Integer.toString(resimID) + ".jpg" ,"I" + Integer.toString(resimID) + ".jpg");

// I AM GETTING ERROR HERE ******************
resim.setImageDrawable(image); // *************************

private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(new URL(url).openConnection().getInputStream(),saveFilename);
return d;
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;

public Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
private void MalzemeEkle(String malzemeKodu, String malzemeTanimi) {
ImageView parcaresmi = new ImageView(this);
Runnable r = new ResimCek(Integer.parseInt(malzemeKodu));
new Thread(r).start();

No comments:

Post a Comment