App crashes when connection is lost while using HttpUrlConnection

Tags: , , ,



i’m making a class that get json data from an external url, it is working fine if there is a connection. also shows an error if there isn’t. the problem is if the connection lost while the class is getting data the app crashes.

here is my code:

//I always check connection before calling the class

class GetPost extends AsyncTask<String, String, String>
{
    
    Context c;
    String res;
    public GetPost(Context c){
        this.c=c;
    }

    @Override
    protected void onPreExecute()
    {
        
        super.onPreExecute();
        Earn.statu.setText("Loading post...");
    }
    
    
    
    @Override
    protected String doInBackground(String[] p1)
    {
        try{
        URL u = new URL(p1[0]);
        HttpURLConnection con = (HttpURLConnection) u.openConnection();
        InputStream is = con.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        res = br.readLine();
        }   
        catch (MalformedURLException e){}
        catch (IOException e){}
        
        
        return res;
    }

    @Override
    protected void onPostExecute(String result)
    {
        super.onPostExecute(result);    
        try{

            JSONObject   jo = new JSONObject(res);
            Earn.getVideoData(c,
            jo.getString("pid"),
            jo.getInt("duration"),
            jo.getInt("id")
            );

        }catch(JSONException a){}
        
    }
    

so guys is there any solution to prevent the app from crashing?

Answer

Set timeout on request by example:

try {
    HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
    con.setRequestMethod("HEAD");
    con.setConnectTimeout(5000); //set timeout to 5 seconds

    return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
    return false;
} catch (java.io.IOException e) {
    return false;
}


Source: stackoverflow