0

So as the title probably suggests - I've done a lot of research on the topic, but I am still confused and unable of achieving what I want.

In very simplified scenario, I have a LoginActivity in which is method boolean validateUserInput(String mail, String password) and I want to do the check input in the separate thread. I suppose I will extend it in the future to do the log-in itself as well (http request). Naturally I would like to get boolean value if the operation was successful or not - and in the process of operation I want to show progressbar dialog.

Make a thread, run the code, return its result, show the progress bar in a meantime, piece of cake right?

Should I use asynctask or runnable? How do I do this so I do not block the UI thread?

This is code I tried to use in LoginActivity:

new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mUserInputValidated = validateUserInput(inputEmail.getText().toString(), inputPassword.getText().toString());
                    }
                }).start();

                if(mUserInputValidated)
                {
                    attemptUserLogin(inputEmail.getText().toString(), inputPassword.getText().toString());
                }

I also tried asynctask approach, but ended up with various errors since I started progress dialog in onPreExecute() and ended it in onPostExecute(), using reference like LoginActivity.this where was the problem with memory leak which I was also unable to fix?

I assume this is pretty usual scenarios, since almost every app use it, so - what are common approaches? How do I fix my code?

FanaticD
  • 1,416
  • 4
  • 20
  • 36

1 Answers1

0

You have to use asynctask this will take the work off from main-thread and place it on background thread once the work is done

This is a sample that shows how to do it

   private class LongOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.interrupted();
                }
            }
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("Executed"); // txt.setText(result);
            // might want to change "executed" for the returned string passed
            // into onPostExecute() but that is upto you
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }

Reference

Community
  • 1
  • 1
NaveenKumar
  • 600
  • 1
  • 5
  • 18