Reputation: 59
I have created a program that will connect to a database through PHP and echo back a response. My android program then makes a request to the PHP file and reads the echo in.
public class Read_Author extends AsyncTask<String, Void, String> {
String authorName = "";
@Override
public String doInBackground(String... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/scripts/read_information.php");
HttpResponse response = httpclient.execute(httppost);
authorName = String.valueOf(EntityUtils.toString(response.getEntity()));
String myStr = "ANSWER";
Log.v(myStr, authorName);
}
catch(Exception e){
}
return authorName;
}
public String returnAuthor(){
return authorName;
}
}
I successfully retrieve the echo string and put it in the author name string variable. But when I then try to call return author from my main activity I get no error but the code does not get run.
I call a function called "readValue" within my main activity and within that function, the execute function gets read and then what is supposed to happen is the returnauthor function is supposed to run. But instead, nothing happens Main Activity Code:
public void returnAuthor(){
loadAuthor.execute();
String a = loadAuthor.returnAuthor();
Log.v("HIT ME", a);
}
If anyone has any suggestion on why this could be happening and how to fix it that will be very much appreciated!
Upvotes: 1
Views: 45
Reputation: 16409
You seem to have misconception about AsyncTask
. The result of AsyncTask
may not be available instantly, because the background task might not have been completed.
You need to override the method onPostExecute
in your AsyncTask
to perform some task after the background task has been completed.
First show a progressDialog before executing the AsyncTask
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading..");
progressDialog.setCancelable(false);
progressDialog.show();
Then in the onPostExecute:
@Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
Log.d("author", result);
}
Upvotes: 1