How to automatically run a method outside of Activity onCreate()

Asked

Viewed 2,073 times

3

I have a Mainactivity who owns 4 buttons, when the user selects some of them, the button method calls another Activity, which will display a query made in a XML in a Listview of this new Activity. I’m doing like this:

Method onCreate of the 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 understand is that way, when you click the button on Mainactivity, it takes time to create the new Activity, because I imagine that iniciaBusca() first, charge the listview and then display the screen.

What I want is for the screen to be created, and this method iniciaBusca() start then, and while it runs, appear a progressDialog in the user interface.

Anyone have a tip? Solution? D

I got. ;)

  • 1

    Can use a AsyncTask in its "new" Activity and run this method within it and add your progressDialog!

1 answer

5


As @Igormello said, you should use one Async Task. Basically, what a Async Task does is execute a code in a thread other than Uithread, which is the main thread and is responsible for building activities. This way, it is possible to execute a code in the background while Activity loads normally, avoiding the "freezing" of it.

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

  1. onPreExecute : called before the long-duration task is executed. It is usually used to show a bar Progress.

  2. doInBackground : performs a long-term task ( access to a local or external DB ) .

    Heed: Within this method there should be no access to view elements, if this is done, you will receive a type error java.lang.Runtimeexception: Can’t 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 method doInBackground() put the view access method inside the method runOnUiThread() and put it inside the 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
            }
        });
    } 
    
  3. onPostExecute : called as soon as the long-duration task is completed. It is used to access and treat the return variable of the long-duration task

So,to implement a Async Task , you can put the following code on 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
    }
}

As follows, no onCreate() from your site, after creating the views, do

ConsultaXML consulta = new ConsultaXML();
consulta.execute("");
  • Thanks @regmoraes, I’ll do here to see if this solves my problem. ;)

  • Every time I try to place threads this message appears "Caused by: java.lang.Runtimeexception: Can’t create Handler Inside thread that has not called Looper.prepare()". What do I do? : S

  • @Robledogomes, I edited the answer with the solution to this problem, take a look

  • Hey @regmoraes I put the part of the code that makes the search in XML, take a look please... : D

  • I got @regmoraes, with your help and a Youtube video worked. Now Activity is started, Progress appears and the search is done.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.