How to load file from URL on every 2s (over and over )? Do I need to close connection or to stay connected ( I load one time with this code ) ? Do I need to use synchronized somewhere ?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView txt=(TextView)this.findViewById(R.id.lbl);
try {
URL url = new URL("http://10.0.2.2/test/dynamic/test.json");
URLConnection urlconnection = url.openConnection();
long l = urlconnection.getContentLength();
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
StringBuffer buffer=new StringBuffer();
while ((line = in.readLine()) != null)
{
buffer.append(line);
}
in.close();
System.out.println("bufer="+buffer.toString());
txt.setText(buffer.toString());
Object obj = JSONValue.parse(buffer.toString());
JSONArray array = (JSONArray) obj;
for(Object o:array){
JSONObject element_json = (JSONObject)o;
int id=Integer.parseInt(""+element_json.get("id"));
int type=Integer.parseInt(""+element_json.get("type"));
int device_type=Integer.parseInt(""+element_json.get("device_type"));
}
} catch (Exception exc) {
exc.printStackTrace();
}
}
You should be using an AsyncTask. The way you’re doing it you’re gonna get the “Application Is Not Responding” error because you’re blocking the UI thread. Any long-running operations (e.g. getting something from the cloud) should be done in the background. Once your asynctask completes, you can schedule another run in the onPostExecute method.
Also, I would recommend using RoboAsyncTask from the RoboGuice library, since it provides a much more developer (and newbie) friendly version of AsyncTask.