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?



Thanks.



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(),"http://141.11.11.206/parca/" + 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) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
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);
parcaresmi.setId(Integer.parseInt(malzemeKodu));
Runnable r = new ResimCek(Integer.parseInt(malzemeKodu));
new Thread(r).start();
}




No comments:

Post a Comment