I'm putting together my first Android application, which is also my introduction to the Java programming language, and so I'm stumbling over what may be some very basic concepts.
My plan is to set up a server full of php functions and place all the php calls within a single static function library. I could change that static class to singleton if it simplifies this issue.
From within an activity, I'm making the following call:
phpCalls.VerifyAccount(userName, password);
and within the phpCalls static class, I've got the following code:
PHP_AsyncTask validateAccountTask = new PHP_AsyncTask();
validateAccountTask.execute(new String[] {DOMAIN + PHP_confirm_account_exists, username, password});
and
private static class PHP_AsyncTask extends AsyncTask<String, Void, String>{
//This class should take the full URL of the php function to call and return the string result. Somehow.
@Override
protected String doInBackground(String... args)
{
String response = "";
try
{
String url = args[0];
String username = args[1];
String password = args[2];
URL validateURL = new URL(url);
String credentials = "Basic " + new String(Base64.encode((username + ":" + password).getBytes(), Base64.NO_WRAP)) ;
//TODO: handle 501 result
HttpURLConnection conn = (HttpURLConnection)validateURL.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Authorization",credentials);
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null)
{
response += line;
}
reader.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String result)
{
//have something happen when the php returns - need to pass the result somewhere
}
Sorry if the formatting on the code is less than ideal - I'm not a regular poster on Stackoverflow.
Anyway, I'm trying to determine how best to handle the result from the php call - it's being returned to the onPostExecute function of the PHP_AsyncTask class as result, but I need to somehow pass it back to the UI thread. Apparently I can't create a pointer to a function within my activity and pass that through to the async class. Is there a way to create a listener within my activity and pass that along so that I can pass the result from PHP_AsyncTask back to my activity? Or am I completely barking up the wrong tree - is there some preferable approach which I should be pursuing?