如何每15分钟使用HTTP响应更新TextView?

时间:2014-10-03 00:06:27

标签: android json http android-studio

如何每隔15分钟运行此功能,以便检查已添加到数据库的新主题。 我在mainactivity中的一个非常简单的片段getData(),它将向PHP脚本发送HTTP请求,然后检索和更新TextView,结果示例是一个简单的主题。 现在我想让这个函数每15分钟运行一次,并将新结果设置为TextView。

public void getData() {
    String result = "";
    InputStream isr = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(""); //YOUR PHP SCRIPT ADDRESS
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        isr = entity.getContent();
    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
        topic.setText("Couldnt connect to database");
    }
    //convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(isr, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        isr.close();

        result = sb.toString();

    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    //parse json data
    try {
        String n = "";

        JSONArray jArray = new JSONArray(result);

        JSONObject json = jArray.getJSONObject(0);
        n = n + "Topic: " + json.getString("Topic") + "\n";
        topic.setText(n);
    } catch (Exception e) {
        Log.e("log_tag", "Error Parsing Data " + e.toString());
    }
}

1 个答案:

答案 0 :(得分:0)

回答Dave S.提供的问题。 刷新活动OnResume(); Using onResume() to refresh activity