0

I wanna put timeout on connection attempt, for instance 10 seconds. But I'm not really good with threading or anything with the web technologies. And I don't know what should I do next.

This is my class:

 class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(RecipeActivity.this);
        dialog.setMessage("Loading, please wait");
        dialog.setTitle("Connecting to server");
        dialog.show();
        dialog.setCancelable(false);
    }


    @Override
    protected Boolean doInBackground(String... urls) {
        try {

            HttpGet httpPost = new HttpGet(urls[0]);
            HttpClient httpClient = new DefaultHttpClient();
            HttpResponse response = httpClient.execute(httpPost);


            int status = response.getStatusLine().getStatusCode();

            if (status == 200) {
                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity);

                JSONArray array = new JSONArray(data);

                for (int i = 0; i < array.length(); i++) {
                    JSONObject object = array.getJSONObject(i);

                    Recipe rec = new Recipe();
                    rec.setName(object.getString("name"));
                    rec.setImage(object.getString("image"));
                    rec.setCalories(object.getInt("calories"));
                    rec.setIngredients(object.getString("ingredients"));
                    rec.setInstructions(object.getString("instructions"));
                    rec.setTime(object.getString("time"));
                    rec.setDescription(object.getString("description"));
                    rec.setNumberIngred(object.getString("numberingred"));
                    recipes.add(rec);
                }
                return true;
            }

        } catch (ParseException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    protected void onPostExecute(Boolean result) {
        dialog.cancel();
        adapter.notifyDataSetChanged();
        if (result == false)
            Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();

    }
}
hyrulelink16
  • 389
  • 1
  • 5
  • 17

1 Answers1

3

I found an answer here on SO.

However, if you find AsyncTasks difficult, then you could simplify that by using a library such as Okhttp or Volley.

Community
  • 1
  • 1
Ruchira Randana
  • 4,021
  • 1
  • 27
  • 24