Pergunta

Eu tenho uma função que preenche meu banco de dados SQLite com entradas de uma consulta http:

try {
        stringEntity = new StringEntity(SQL);
        httpPost.setEntity(stringEntity);
        httpResponse = httpClient.execute(httpPost);
        httpEntity = httpResponse.getEntity();
        bos = new ByteArrayOutputStream();
        httpEntity.writeTo(bos);

        data = bos.toString();

        reader = new BufferedReader(
                  new StringReader(data));

        try {
            //SAVE DATA IN MY DB || WORKS
        } catch(IOException e) {
          e.printStackTrace();
        }

    } catch (IOException e3) {
        // TODO Auto-generated catch block
        e3.printStackTrace();
    }

O que tento fazer é definir o texto de um textview na minha atividade antes do início do procedimento (antes do primeiro "try {.." no meu código postado). mas o texto não mudará, porque minha atividade está muito ocupada para obter os dados (eu acho. Não tenho outra explicação ..)

alguma sugestão?

obrigado, prexx

ATUALIZAÇÃO '' Obter dados de AsyncTask ''

 txtAction.setText("Loading...");

    AsyncTask<String, String, String> test = new cAsyncTask();

    try {
        data = test.execute(URL).get();

        reader = new BufferedReader(
                  new StringReader(data));

        while ((line = reader.readLine()) != null) {
            //SAVE DATA IN DB || WORKS
            }
        }

    } catch(IOException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Minha tarefa assíncrona:

class cAsyncTask extends AsyncTask<String, String, String> {

protected String doInBackground(String... urls) {
    int count = urls.length;
    String data = "";
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost;
    StringEntity stringEntity;
    HttpResponse httpResponse;
    HttpEntity httpEntity;
    ByteArrayOutputStream bos;
    String line;
    BufferedReader reader;
    for (int i = 0; i < count; i++) {
        httpPost = new HttpPost(urls[i].toString());
        try {
            stringEntity = new StringEntity(SQL);
            httpPost.setEntity(stringEntity);
            httpResponse = httpClient.execute(httpPost);
            httpEntity = httpResponse.getEntity();
            bos = new ByteArrayOutputStream();
            httpEntity.writeTo(bos);

            data = bos.toString();

        } catch (IOException e3) {
            // TODO Auto-generated catch block
            e3.printStackTrace();
        }
    }
    return data;
}

protected void onProgressUpdate(String... progress) {

}

protected void onPostExecute(String result) {
    String test = result;
}
Foi útil?

Solução

Coloque a parte ocupada do seu código em um thread separado.

Veja o utilitário AsyncTask

Chame AsyncTask.execute() logo após textview.setText("foo") e você ficará bem :)

Atenciosamente

ATUALIZAR com amostra de código:

 txtAction.setText("Loading...");
 AsyncTask<String, String, String> test = new cAsyncTask();
 test.execute("http://...");

class cAsyncTask extends AsyncTask<String, String, String> {

protected String doInBackground(String... urls) {
    int count = urls.length;
    String data = "";
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost;
    StringEntity stringEntity;
    HttpResponse httpResponse;
    HttpEntity httpEntity;
    ByteArrayOutputStream bos;
    String line;
    BufferedReader reader;
    for (int i = 0; i < count; i++) {
        httpPost = new HttpPost(urls[i].toString());
        try {
            stringEntity = new StringEntity(SQL);
            httpPost.setEntity(stringEntity);
            httpResponse = httpClient.execute(httpPost);
            httpEntity = httpResponse.getEntity();
            bos = new ByteArrayOutputStream();
            httpEntity.writeTo(bos);

            data = bos.toString();

        } catch (IOException e3) {
            // TODO Auto-generated catch block
            e3.printStackTrace();
        }
    }
     reader = new BufferedReader(
                  new StringReader(data));
       String line = "";
        while ((line = reader.readLine()) != null) {
            //SAVE DATA IN DB || WORKS
     }
    return data;
}


protected void onPostExecute(String result) {
    String test = result;
   textView.setText("Done!");
}

}

A chave é colocar todo o código ocupado no método doInBackGround, que será executado em uma thread separada.Todas as modificações da IU devem estar no mesmo IU thread e isso pode ser feito no método onPostExecute, que será executado no mesmo IU thread.

Outras dicas

Você pode tentar chamar invalidate () em TextView.Mas usar tarefas assíncronas é uma prática recomendada para métodos de carregamento pesado de dados.Isso não interromperá o usuário nos controles da IU de operação.

Não tem nada a ver com "muito ocupado", mas com o fato de que o texto só será definido quando o método retornar.E com sua rede, isso será atrasado.

Btw.na rede Honeycomb no thread de IU lançará uma exceção e encerrará seu aplicativo.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top