在HTTP连接超时时为TextView设置文本

时间:2018-08-13 11:01:19

标签: java android

当HTTP连接超时时,我需要为<?php /** * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages and that other * 'pages' on your WordPress site will use a different template. * * @package OceanWP WordPress theme */ get_header(); ?> <?php do_action( 'ocean_before_content_wrap' ); ?> <div id="content-wrap" class="container clr"> <?php do_action( 'ocean_before_primary' ); ?> <div id="primary" class="content-area clr"> <?php do_action( 'ocean_before_content' ); ?> <div id="content" class="site-content clr"> <?php do_action( 'ocean_before_content_inner' ); ?> <?php // Elementor `single` location if ( ! function_exists( 'elementor_theme_do_location' ) || ! elementor_theme_do_location( 'single' ) ) { // Start loop while ( have_posts() ) : the_post(); get_template_part( 'partials/page/layout' ); endwhile; } ?> <?php do_action( 'ocean_after_content_inner' ); ?> </div><!-- #content --> <?php do_action( 'ocean_after_content' ); ?> </div><!-- #primary --> <?php do_action( 'ocean_after_primary' ); ?> <?php do_action( 'ocean_display_sidebar' ); ?> </div><!-- #content-wrap --> <?php do_action( 'ocean_after_content_wrap' ); ?> <?php get_footer(); ?> 设置文本,这是一条错误消息 我需要在TextView上完成此操作,但请求是从MainActivity.java发出的 我尝试使用findViewByid做到这一点,但由于使用静态方法观看错误而出现错误 这是我的QueryUtils,java

QueryUtils.java

2 个答案:

答案 0 :(得分:1)

这可以使用回调(接口)完成。

以下代码段是您要做的:

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();
}

在MainActivity中,必须以这种方式调用makeHttpRequest

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

希望获得帮助。

答案 1 :(得分:0)

您可以使用interface来实现。

1)在您的interface类中创建一个QueryUtils

2)在您的活动中实现此interface

3)将接口的引用传递给QueryUtils类。

4)。每当超时时,调用interface方法。

请参见下面的代码

QueryUtils

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类代码

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
    }
}