• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Thread not working right away...

stubbzj12

Newbie
Hi! I'm starting to experiment with connecting apps to a hosted MySQL database. I'm doing it by sending HTTP requests (post requests while passing values along) and return results in JSON format. But, for some reason, I have to click a button twice to get a result back. Inside the OnClickListener is a thread. I'm also using OkHttp library.

Just want to make sure that you know that I am in no way a pro. I'm really new to android, so I'm trying to figure things out. The way I show you is probably bad practice, but if someone could help that'd be great.

Java:
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        usernameField = (EditText) findViewById(R.id.username_field);
        passwordField = (EditText) findViewById(R.id.password_field);
        loginButton = (Button) findViewById(R.id.login_button);

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                username = usernameField.getText().toString();
                password = passwordField.getText().toString();

                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        OkHttpClient client = new OkHttpClient();

                        FormBody body = new FormBody.Builder()
                                .add("username", username)
                                .add("password", password)
                                .build();

                        Request request = new Request.Builder()
                                .url("http://www.mysite.com/dir/login.php")
                                .post(body)
                                .build();

                        try {
                            Response response = client.newCall(request).execute();

                            result = response.body().string();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
                thread.start();
                test();

            }
        });
    }

    public void test () {
        Log.d("test", this.result.toString());
    }

I can get the results back just fine. However, I have to click the button twice for it to work and I'm not sure why.

I appreciate any help I could get!
 
To start with this is a bad idea

Code:
       catch IOException e) {
              e.printStackTrace();
        }

because you could be getting an exception, and you'll never see it.
Instead use

Code:
       catch IOException e) {
              Log.d("test", e.getMessage());
        }

The next thing is, don't use Log statements to debug your app. Instead run the app in debug mode, and set breakpoints in your code. This allows you to interactively step through execution of the code, and examine variable values.
 
Actually I this it works :)
But in the 1st run when the test() is called the thread.run() didn't finish his work.
What you can do is to call test() at the end of the try{} block.
Or eventually you can play with the AsyncTask , it may look a little bit difficult at the beginning, but once you get use with it it is very easy. In consist of 3 main steps/methods:
  1. onPreExecute(...) - called at the begining, you can leave it empty
  2. doInBackground(...) - main time consumming task
  3. onPostExecute(...) - automatically called at the end, used to show the results
There are a lot of tutorials about AsinkTask.
 
Actually I this it works :)
But in the 1st run when the test() is called the thread.run() didn't finish his work.
What you can do is to call test() at the end of the try{} block.
Or eventually you can play with the AsyncTask , it may look a little bit difficult at the beginning, but once you get use with it it is very easy. In consist of 3 main steps/methods:
  1. onPreExecute(...) - called at the begining, you can leave it empty
  2. doInBackground(...) - main time consumming task
  3. onPostExecute(...) - automatically called at the end, used to show the results
There are a lot of tutorials about AsinkTask.
Thanks a lot! That worked. But, what if I don't want to run all of my code inside the thread?
 
Sorry for double post. But I'm using AsyncTask and it's working fine. However, how can I update a variable in my MainActivity class from my AsyncTask class?
 
Last edited:
Regarding to "I don't want to run all of my code inside the thread", the recommendation is to execute the computations/time_consuming tasks not in main UI thread. You should do it in other threads, otherway you will get ANRs (Application Not Responding). See https://developer.android.com/training/articles/perf-anr.html

You can create a constructor of your AsyncTask class having as parameter an object of MainActivity.
And then onPostExecute() will call a setter of MainActivity.
More details here:
https://stackoverflow.com/questions/5523438/how-to-call-parent-activity-function-from-asynctask
 
Hello,
I would like to advice you to take the help from android app developers, who will surely find out the solution of your problem.
You can also try stackoverflow forum, it is one of the best question answer forum for developer.
 
Back
Top Bottom