Rico Harisin
Rico Harisin

Reputation: 3409

Handle connection timeout in async task

i have a problem that i haven't solved yet and i need a help

i made an app that sometimes connect to web service to get data and i do that using async task

i want to make alert dialog on connection timeout when user can choose whether they want to retry or cancel, if they choose retry it will try to connect again

the problem is, i don't know where i should put the alert dialog and the method for retry and cancel

i want to make asynctask to wait for the user input or until they choose retry or cancel,

i tried to put in doinbackground using runOnUiThread but the alert dialog won't appear and i tried to use publishProgress() and show alertdialog in onProgressUpdate, the alert dialog is appear but the async task keep going. if i use wait or notify it gave me error object not locked by thread before wait

is there any way to achieve this except to put in onPostExecute?

thanks before

Upvotes: 1

Views: 3531

Answers (3)

Raj
Raj

Reputation: 101

Just put your code in this try/catch and find the "Exception type" and show your dialog according to this.

try
{
    int timeout = 3000;
    URL myURL = //some valid URL

    AndroidHttpClient = AndroidHttpClient.newInstance("name");
    HttpGet httpGet = new HttpGet(myURL.toExternalForm());

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
    HttpConnectionParams.setSoTimeout(httpParams, timeout);

    HttpResponse response = httpClient.execute(httpGet);

    //...
}
catch (SocketTimeoutException e)
{
    e.printStackTrace();
}
catch (ConnectTimeoutException e)
{
    e.printStackTrace();
}
catch (Exception e)
{
    e.printStackTrace();
}

Upvotes: 2

Gajendra Rawat
Gajendra Rawat

Reputation: 3663

Use This

String host = "122.000.135.000";

int timeOut = 3000; // I recommend 3 seconds at least
boolean status;
try {
System.out.println("SERVER IS third");
status = InetAddress.getByName(host).isReachable(timeOut);
if(status == true)
{
System.out.println("SERVER IS "+status);
String UName = libertyID.getText().toString();
String Passwrd = password.getText().toString();

callAlertDialog();
                            sendPostRequest(UName,Passwrd);

//encryptPassword(); }

Upvotes: 0

Nitin Gupta
Nitin Gupta

Reputation: 287

start progressdialog in onpreexecute and stop on onpostexecute and if u get response null in any reason in doinbackgroung then display alert in onpostexecute and call asyntask again from alert dialog action

Upvotes: 0

Related Questions