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.
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!
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!
