I tried connect a webservice by a AsyncTask on my android app. But it
dosen't give nothing and takes a lot of time to connect
This is the class that I have implemented to connect.
public class WebService extends AsyncTask<String, String, String> {
private ArrayList<SimpleObserver> listeners;
private int responseCode;
private String message;
private String response;
public enum RequestMethod {
GET, POST
}
public WebService() {
listeners = new ArrayList<SimpleObserver>();
}
public void addListener(SimpleObserver obs) {
listeners.add(obs);
}
public void removeListener(SimpleObserver obs) {
listeners.remove(obs);
}
public void notifyListener(String s) {
for (SimpleObserver listener : listeners)
listener.onChange(s);
}
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
@Override
protected void onPreExecute() {
notifyListener("A calcular");
}
@Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
notifyListener("A ligar ao Serviço");
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
notifyListener("Chegou aqui");
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
notifyListener("Ja tenho qualquer coisa");
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
@Override
protected void onPostExecute(String result) {
notifyListener(result);
}
}
This is the way that I call the AsyncTask:
public class ServiceController implements SimpleObserver {
private Activity act;
private WebService s;
private static final String URL = "http://ip and rest of the url!";
public ServiceController(MainActivity mainActivity) {
act = mainActivity;
s = new WebService();
s.addListener(this);
}
public void onChange(String s) {
((MainActivity) act).getTextView().setText(s);
}
public void executeService() {
try {
s.execute(new String[] { URL });
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
Someone can help me understand where is my mistake?
thanks.
--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en