I have a piece of code that sets some network IP cameras parameters by simply calling some URLs. URLs are (to simplify) in this format “http://mydomain.com:portnumber/setalarm.cgi” and I use a normal HttpGet / HttpResponse mechanism to call URL and get result status (200 if it is good, other if bad).
Now: as URL to be called are 8 or more, in sequence (I use for loop), I would like to display a progress bar (or the simple progress indicator) to let the user know that the different URL calls are being performed. When all of the 8 calls are done, I would like a new Actity to be displayed with the result (OK, or KO with the list of KO cams).
I’ve tried many solutions, found on this site, but none of those where successful (Threads, progressbar , dialog bar, Asynchronous task, etc.). Either I get exceptions, or the bar does not show, or the new Activity display before the completion of the process.
Could anyone help ? This is the relevant part of my code now:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainlayout);
// ON button
Button myButton1 = (Button) findViewById (R.id.button1);
myButton1.setOnClickListener(new OnClickListener() {
public void onClick(final View arg0) {
intGoodCamera = 0;
intBadCamera = 0;
for (int i = 0; i<intNumCam; i++) {
System.out.println (intStartingPortNb+i);
String myurl = strIPAddress + ":" + (intStartingPortNb+i) + strSuffixSetAlarmOn;
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(myurl);
HttpResponse response = null;
try {
response = httpClient.execute(httpGet, localContext);
System.out.println (response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() == 200)
intGoodCamera++;
else {
intBadCamera++;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println ("OK: "+intGoodCamera + " KO: "+ intBadCamera);
Intent nextIntent = new Intent(MainActivity.this, Results.class);
MainActivity.this.startActivity(nextIntent);
}
});
…..
Just Use AsyncTask..
onPreExecute()of AsyncTask..doInBackGround()of AsyncTask.onPostExecute()andStart a new Activity in
onPostExecute().Simple..