1

I need to set text for a TextView when http connection timeout as an error message I need this to be done on MainActivity.java but request is made from QueryUtils.java I tried to do that using findViewByid but I got an error because of using static method to watch errors here is my QueryUtils,java

package com.example.android.mynewsx2;


    import android.net.Uri;
    import android.util.Log;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.nio.charset.Charset;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.Locale;

    /**
     * Created by Person on 11/08/2018.
     */

    public class QueryUtils {

        public boolean connTimeout = false;
        static String createStringUrl() {
            Uri.Builder builder = new Uri.Builder();
            builder.scheme("http")
                    .encodedAuthority("content.guardianapis.com")
                    .appendPath("search")
                    .appendQueryParameter("order-by", "newest")
                    .appendQueryParameter("show-references", "author")
                    .appendQueryParameter("show-tags", "contributor")
                    .appendQueryParameter("page-size", "175")
                    .appendQueryParameter("q", "")
                    .appendQueryParameter("api-key", "c15d8295-7691-4172-a257-a7d065668eb4");
            String url = builder.build().toString();
            return url;
        }

        static URL createUrl() {
            String stringUrl = createStringUrl();
            try {
                return new URL(stringUrl);
            } catch (MalformedURLException e) {
                Log.e("Queryutils", "Error creating URL: ", e);
                return null;
            }
        }

        private static String formatDate(String rawDate) {
            String jsonDatePattern = "yyyy-MM-dd'T'HH:mm:ss'Z'";
            SimpleDateFormat jsonFormatter = new SimpleDateFormat(jsonDatePattern, Locale.US);
            try {
                Date parsedJsonDate = jsonFormatter.parse(rawDate);
                String finalDatePattern = "MMM d, yyy";
                SimpleDateFormat finalDateFormatter = new SimpleDateFormat(finalDatePattern, Locale.US);
                return finalDateFormatter.format(parsedJsonDate);
            } catch (ParseException e) {
                Log.e("QueryUtils", "Error parsing JSON date: ", e);
                return "";
            }
        }

        static String makeHttpRequest(URL url) throws IOException {
            String jsonResponse = "";

            if (url == null){
                return jsonResponse;
            }
            HttpURLConnection urlConnection = null;
            InputStream inputStream = null;

            try {
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.setReadTimeout(10000 /* milliseconds */);
                urlConnection.setConnectTimeout(15000 /* milliseconds */);
                urlConnection.connect();
                if (urlConnection.getResponseCode() == 200){
                    inputStream = urlConnection.getInputStream();
                    jsonResponse = readFromStream(inputStream);
                } else {
                    Log.e("mainActivity", "Error response code: " + urlConnection.getResponseCode());

                }
            } catch (IOException e) {
                Log.e("Queryutils", "Error making HTTP request: ", e);
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            }
            return jsonResponse;
        }

        private static String readFromStream(InputStream inputStream) throws IOException {
            StringBuilder output = new StringBuilder();
            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
                BufferedReader reader = new BufferedReader(inputStreamReader);
                String line = reader.readLine();
                while (line != null) {
                    output.append(line);
                    line = reader.readLine();
                }
            }
            return output.toString();
        }

        static List<News> parseJson(String response) {
            ArrayList<News> listOfNews = new ArrayList<>();
            try {
                JSONObject jsonResponse = new JSONObject(response);
                JSONObject jsonResults = jsonResponse.getJSONObject("response");
                JSONArray resultsArray = jsonResults.getJSONArray("results");

                for (int i = 0; i < resultsArray.length(); i++) {
                    JSONObject oneResult = resultsArray.getJSONObject(i);
                    String webTitle = oneResult.getString("webTitle");
                    String url = oneResult.getString("webUrl");
                    String date = oneResult.getString("webPublicationDate");
                    date = formatDate(date);
                    String section = oneResult.getString("sectionName");
                    JSONArray tagsArray = oneResult.getJSONArray("tags");
                    String author = "";

                    if (tagsArray.length() == 0) {
                        author = null;
                    } else {
                        for (int j = 0; j < tagsArray.length(); j++) {
                            JSONObject firstObject = tagsArray.getJSONObject(j);
                            author += firstObject.getString("webTitle") + ". ";
                        }
                    }
                    listOfNews.add(new News(webTitle, author, url, date, section));
                }
            } catch (JSONException e) {
                Log.e("Queryutils", "Error parsing JSON response", e);
            }
            return listOfNews;
        }
    }
Hemant Parmar
  • 3,924
  • 7
  • 25
  • 49
Ahmed Abdelazim
  • 717
  • 7
  • 14

2 Answers2

1

This can be done using the callback (interfaces).

The following code snippet is what you have to do :

static String makeHttpRequest(URL url, OnTimeOutListener listener) throws IOException {
    String jsonResponse = "";

    if (url == null) {
        return jsonResponse;
    }
    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;

    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.connect();
        if (urlConnection.getResponseCode() == 200) {
            inputStream = urlConnection.getInputStream();
            jsonResponse = readFromStream(inputStream);
        } else {

            //Call this when time out happens
            listener.onTimeOut();
            Log.e("mainActivity", "Error response code: " + urlConnection.getResponseCode());

        }
    } catch (IOException e) {
        Log.e("Queryutils", "Error making HTTP request: ", e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            inputStream.close();
        }
    }
    return jsonResponse;
}

interface OnTimeOutListener {
    void onTimeOut();
}

In your MainActivity you have to call makeHttpRequest that way

QueryUtils.makeHttpRequest(url, new OnTimeOutListener() {
        @Override
        public void onTimeOut() {
          //Handle your call timeout.
        }
    });

Hope this help.

Mohamed Yehia
  • 400
  • 1
  • 5
  • 15
0

You can achieve this by using interface.

1) Create a interface in your QueryUtils class.

2) Implements this interface in your activity.

3) Pass reference of your interface to QueryUtils class.

4). call interface method whenever timeout.

Please see below code

QueryUtils class

public class QueryUtils {

public interface OnConnectionTimeOut {
    void onTimeOut();
}

public static OnConnectionTimeOut objTimeOutListener;

public void setTimeOutListener(OnConnectionTimeOut listener) {
    objTimeOutListener = listener;
}

public boolean connTimeout = false;

public static String createStringUrl() {
    Uri.Builder builder = new Uri.Builder();
    builder.scheme("http")
            .encodedAuthority("content.guardianapis.com")
            .appendPath("search")
            .appendQueryParameter("order-by", "newest")
            .appendQueryParameter("show-references", "author")
            .appendQueryParameter("show-tags", "contributor")
            .appendQueryParameter("page-size", "175")
            .appendQueryParameter("q", "")
            .appendQueryParameter("api-key", "c15d8295-7691-4172-a257-a7d065668eb4");
    String url = builder.build().toString();
    return url;
}

static URL createUrl() {
    String stringUrl = createStringUrl();
    try {
        return new URL(stringUrl);
    } catch (MalformedURLException e) {
        Log.e("Queryutils", "Error creating URL: ", e);
        return null;
    }
}

private static String formatDate(String rawDate) {
    String jsonDatePattern = "yyyy-MM-dd'T'HH:mm:ss'Z'";
    SimpleDateFormat jsonFormatter = new SimpleDateFormat(jsonDatePattern, Locale.US);
    try {
        Date parsedJsonDate = jsonFormatter.parse(rawDate);
        String finalDatePattern = "MMM d, yyy";
        SimpleDateFormat finalDateFormatter = new SimpleDateFormat(finalDatePattern, Locale.US);
        return finalDateFormatter.format(parsedJsonDate);
    } catch (ParseException e) {
        Log.e("QueryUtils", "Error parsing JSON date: ", e);
        return "";
    }
}

static String makeHttpRequest(URL url) throws IOException {
    String jsonResponse = "";

    if (url == null) {
        return jsonResponse;
    }
    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;

    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.connect();
        if (urlConnection.getResponseCode() == 200) {
            inputStream = urlConnection.getInputStream();
            jsonResponse = readFromStream(inputStream);
        } else {
            objTimeOutListener.onTimeOut();
            Log.e("mainActivity", "Error response code: " + urlConnection.getResponseCode());

        }
    } catch (IOException e) {
        objTimeOutListener.onTimeOut();
        Log.e("Queryutils", "Error making HTTP request: ", e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            inputStream.close();
        }
    }
    return jsonResponse;
}

private static String readFromStream(InputStream inputStream) throws IOException {
    StringBuilder output = new StringBuilder();
    if (inputStream != null) {
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
        BufferedReader reader = new BufferedReader(inputStreamReader);
        String line = reader.readLine();
        while (line != null) {
            output.append(line);
            line = reader.readLine();
        }
    }
    return output.toString();
}

static List<News> parseJson(String response) {
    ArrayList<News> listOfNews = new ArrayList<>();
    try {
        JSONObject jsonResponse = new JSONObject(response);
        JSONObject jsonResults = jsonResponse.getJSONObject("response");
        JSONArray resultsArray = jsonResults.getJSONArray("results");

        for (int i = 0; i < resultsArray.length(); i++) {
            JSONObject oneResult = resultsArray.getJSONObject(i);
            String webTitle = oneResult.getString("webTitle");
            String url = oneResult.getString("webUrl");
            String date = oneResult.getString("webPublicationDate");
            date = formatDate(date);
            String section = oneResult.getString("sectionName");
            JSONArray tagsArray = oneResult.getJSONArray("tags");
            String author = "";

            if (tagsArray.length() == 0) {
                author = null;
            } else {
                for (int j = 0; j < tagsArray.length(); j++) {
                    JSONObject firstObject = tagsArray.getJSONObject(j);
                    author += firstObject.getString("webTitle") + ". ";
                }
            }
            listOfNews.add(new News(webTitle, author, url, date, section));
        }
    } catch (JSONException e) {
        Log.e("Queryutils", "Error parsing JSON response", e);
    }
    return listOfNews;
}

}

Activity class code

public class DataActivity extends Activity implements QueryUtils.OnConnectionTimeOut {


    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        QueryUtils obj = new QueryUtils();
        obj.setTimeOutListener(this);

    }

    @Override
    public void onTimeOut() {

        Log.e("This method will be called on timeout", "");
      //Set text here
    }
}
Sukhbir
  • 1,410
  • 14
  • 33