Android : Auto Refresh Image View to get image of same name from website

on Sunday, August 17, 2014


Hi all i have created an android application in which the device connects to the local network and get the latest image from the website. i have gotten the first image but i cannot make it run constantly because the image is constantly changing in the website all the images have the same name all i need to is restart my asynchronous task again and again. my code is below



import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import android.widget.ImageView;
public class S_car extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scar);
run();
}

private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {

protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}

// Sets the Bitmap returned by doInBackground
protected void onPostExecute(Bitmap result) {
imageviewA.setImageBitmap(result);
imageviewA.postInvalidateDelayed(500);
}

// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;

try {

stream = getHttpConnection(url);
bitmap = BitmapFactory.
decodeStream(stream, null, bmOptions);
stream.close();

// imageviewA.refreshDrawableState();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}

// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();

try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();

if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;

}

}

public void run()
{
final String URL = "http://192.168.1.106/jpg/image.jpg";
//for(int i = 0; i<1000;i++);
//{
GetXMLTask task = new GetXMLTask();
// Execute the task
task.execute(new String[] { URL });
//imageviewA.refreshDrawableState();
//imageviewA.postInvalidate();
//}

}


}


0 comments:

Post a Comment