when I run a following code
Runnable r = new Runnable() {
@Override
public void run() {
final String urlString = "http://10.0.2.2/conn/s.png";
// URL newurl = null;
try{
do
{
if (ch==1)
{
//Thread.sleep(7000);
HttpGet httpRequest = new HttpGet(new URL(urlString).toURI());
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream is = bufHttpEntity.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(is);
im.destroyDrawingCache();
im.setImageBitmap(bitmap);
bitmap=null;
// Thread.sleep(3000);
out.write(1);
out.flush();
}
}
while(( ch=in.read()) == 1);
}
catch(IOException ex)
{
}
catch(URISyntaxException ex)
{}
}
};
and the thread is initialized like this:
t = new Thread(r);
t.start();
I am getting the following exception:
03-18 01:20:50.399: E/AndroidRuntime(305): at android.view.ViewRoot.checkThread(ViewRoot.java:2683)
03-18 01:20:50.399: E/AndroidRuntime(305): at android.view.ViewRoot.requestLayout(ViewRoot.java:557)
03-18 01:20:50.399: E/AndroidRuntime(305): at android.view.View.requestLayout(View.java:7918)
03-18 01:20:50.399: E/AndroidRuntime(305): at android.view.View.requestLayout(View.java:7918)
03-18 01:20:50.399: E/AndroidRuntime(305): at android.view.View.requestLayout(View.java:7918)
03-18 01:20:50.399: E/AndroidRuntime(305): at android.view.View.requestLayout(View.java:7918)
03-18 01:20:50.399: E/AndroidRuntime(305): at android.view.View.requestLayout(View.java:7918)
03-18 01:20:50.399: E/AndroidRuntime(305): at android.widget.ImageView.setImageDrawable(ImageView.java:306)
03-18 01:20:50.399: E/AndroidRuntime(305): at android.widget.ImageView.setImageBitmap(ImageView.java:320)
03-18 01:20:50.399: E/AndroidRuntime(305): at remote.presentation.rshare$1.run(rshare.java:124)
03-18 01:20:50.399: E/AndroidRuntime(305): at java.lang.Thread.run(Thread.java:1096)
You are changing the UI from a thread, can’t do that in Android. It has to be done on the UI thread. I prefer AsyncTasks to using Threads. This AsyncTask will get an image from a url.
The class
to use it
EDIT (reason for edit, see comments) – the following code will repeatedly download the same image as the question asker wanted
Create a class variable for the GetImage class
Modified class
To stop downloading
I don’t know what your app does but users will not like downloading unnecessary images which eats into their data allowance, perhaps think about a better way to do what you want to do.