How to execute a method automatically outside Activity onCreate ()

3

I have a MainActivity that has 4 buttons, when the user selects one of them, the button method calls another Activity , which will display a query in an XML in a ListView of this new Activity . I'm doing this:

Method% of new Activity :

public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);
        setContentView(R.layout.refeicaoview);
        lstDados = (ListView)findViewById(R.id.lstDados);
        adpItens = new ArrayAdapter<String>(this, R.layout.item_lista);
        lstDados.setAdapter(adpItens);
        iniciaBusca(); //este método faz a consulta ao XML e retorna os dados para serem exibidos na listView acima
}

What I realize is that this way, when you click the button in MainActivity , it takes a while to create the new Activity , so I imagine running% first, load the listView and then display the screen.

What I want is for the screen to be created, and this onCreate method then starts and while it runs, a progressDialog appears in the user interface.

Does anyone have a tip? Solution? : D

I have. ;)

    
asked by anonymous 20.04.2016 / 23:43

1 answer

5

As @IgorMello said, you should use a Async Task . Basically, what an Async Task does is to execute a code on a thread other than the UIThread , which is the main thread and is responsible for building the activities. In this way, it is possible to execute a code in the background while the activity loads normally, avoiding the "freezing" of it.

The Async Task class has 3 important methods that run in that order:

  • onPreExecute : Called before the long-running task runs. It is usually used to show a progress bar.

  • doInBackground : Performs a long-running task (access to a local or external DB).

    Attention: Within this method, no access to elements of the view should be made. If this is done, you will get an error of type java.lang. RuntimeException: Can not create handler inside thread that has not called Looper.prepare () "

    If you want to manipulate the view, you should use the methods onPreExecute() and onPostExecute()

    If you really need to access the view within the doInBackground() method, place the view access method inside the runOnUiThread() method and place it within doInBackground() :

    @Override
    protected String doInBackground(String... parametros) {
    
        // Realiza tarefa de longa duração ...
    
        // Acessa a view
        runOnUiThread(new Runnable() {
    
            public void run() {
    
                // faça o acesso a view aqui
            }
        });
    } 
    
  • onPostExecute : Called as soon as the long-running task completes. It is used to access and handle the return variable of the long-running task

  • So to implement an Async Task , you can put the following code in your activity

    private class ConsultaXML extends AsyncTask<String, Void, String> {
    
        @Override
        protected void onPreExecute() {
    
            // Código para mostrar o progress bar
        }
    
        @Override
        protected String doInBackground(String... parametros) {
    
          // Código que realiza a consulta de um arquivoXML
        }
    
        @Override
        protected void onPostExecute(String arquivoXML) {
    
          // Código que será executado quando o XML for obtido
          // No seu caso, você para de mostrar o progress bar
          // e mostra o arquivoXML na tela
        }
    }
    

    Next, in the% w / w of your activity, after creating the views, do

    ConsultaXML consulta = new ConsultaXML();
    consulta.execute("");
    
        
    21.04.2016 / 04:39