android - Теxtview不会立即改变

时间:2016-04-12 14:36:35

标签: java android textview

我从服务器接受数组,然后填充数据textview。

private class ReadMessages extends       AsyncTask<Void, Void, Integer>
{
    HttpURLConnection conn;
    String ansver, bfr_st;
    JSONArray JsonArray;
    protected Integer doInBackground(Void... params) {
        try {
        String post_url = server_name +"/chat.php?action=select";
        conn = (HttpURLConnection) new URL(post_url).openConnection();
        conn.setReadTimeout(10000); 
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0");
        conn.setDoInput(true);
        conn.connect();

        InputStream is = conn.getInputStream(); //канал
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); //буфер
        StringBuilder sb = new StringBuilder(); //сборщик строки
        while ((bfr_st = br.readLine()) != null) {
            sb.append(bfr_st); //получили массив в виде string
        }

        String json_bum = sb.toString(); 
        JsonArray = new JSONArray(json_bum); //преобразовали string обратно в массив

        for (int i=0; i<JsonArray.length(); i++) { 
             jsonObject = JsonArray.getJSONObject(i); //вынули все обьекты
        }
        tv_number.setText("Номер     - " + jsonObject.getInt("_id") + 
                    "\n"
                      + "Автор -      " + jsonObject.getString("author") +
                      "\n" 
                      + "Адресат     - " + jsonObject.getString("client") +
                      "\n"
                      + "Время -      " + jsonObject.getLong("data") +
                      "\n"
                      + "Текст - "      + jsonObject.getString("text") +
                      "\n");

            is.close();
            br.close();

            } catch (Exception e) { 

            } finally { 

                conn.disconnect();
            }
            return null;
        }


        }

当我折叠应用程序然后返回它时,文本会发生变化。但是当你按下一个没有发生的按钮时立即

4 个答案:

答案 0 :(得分:2)

您只能从app主线程更新GUI元素/小部件。 AsyncTask正在创建单独的线程,您无法从方法doInBackground执行此操作,请尝试使用publishProgressonProgressUpdate,或者在onPostExecute

中执行所有这些工作人员

答案 1 :(得分:0)

为什么你决定必须立即?这取决于你的互联网速度,ping等。良好的做法是使用progressBar向用户显示正在发生的事情,而不仅仅是空屏幕,然后在几秒钟后出现textView。

答案 2 :(得分:0)

您不允许在单独的线程上更新GUI。您应该在OnPostExecute中的AsyncTask内进行更新。此外,您必须@Override doInBackground

private class ReadMessages extends AsyncTask<Void, Void, Integer> {
    HttpURLConnection conn;
    String ansver, bfr_st;
    JSONArray JsonArray;

    @Override
    protected Integer doInBackground(Void... params) {
        try {
        String post_url = server_name +"/chat.php?action=select";
        conn = (HttpURLConnection) new URL(post_url).openConnection();
        conn.setReadTimeout(10000); 
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0");
        conn.setDoInput(true);
        conn.connect();

        InputStream is = conn.getInputStream(); //канал
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); //буфер
        StringBuilder sb = new StringBuilder(); //сборщик строки
        while ((bfr_st = br.readLine()) != null) {
            sb.append(bfr_st); //получили массив в виде string
        }

        String json_bum = sb.toString(); 
        JsonArray = new JSONArray(json_bum); //преобразовали string обратно в массив

        for (int i=0; i<JsonArray.length(); i++) { 
             jsonObject = JsonArray.getJSONObject(i); //вынули все обьекты
        }
            is.close();
            br.close();

            } catch (Exception e) { 

            } finally { 

                conn.disconnect();
            }
            return null;

        }

        @Override
        protected void onPostExecute(String result) {
           tv_number.setText("Номер     - " + jsonObject.getInt("_id") + 
                  "\n"
                    + "Автор -      " + jsonObject.getString("author") +
                    "\n" 
                    + "Адресат     - " + jsonObject.getString("client") +
                    "\n"
                    + "Время -      " + jsonObject.getLong("data") +
                    "\n"
                    + "Текст - "      + jsonObject.getString("text") +
                    "\n");
    }

答案 3 :(得分:0)

doInbackground中的行:

tv_number.setText("Номер     - " + jsonObject.getInt("_id") + 
                    "\n"
                      + "Автор -      " + jsonObject.getString("author") +
                      "\n" 
                      + "Адресат     - " + jsonObject.getString("client") +
                      "\n"
                      + "Время -      " + jsonObject.getLong("data") +
                      "\n"
                      + "Текст - "      + jsonObject.getString("text") +
                      "\n");

实际上会抛出异常,但空的catch语句会阻止应用程序崩溃。

您无法从后台线程更新视图,更新UI必须位于UI线程上。如果是AsyncTask,您可以在 onPostExecute onProgressUpdate 方法中执行此操作。

更改doInBackground实现,使其返回String:

protected String doInBackground(Void... params){
}

然后在onPostExecute中,更新textview

protected onPostExecute(String result){
tv_number.setText(result);
}