-1

I'm trying to update a variable after running a background task with AsyncTask to the result of the background task. The variable updates, but not on time apparently. The toast I use to display the server response displays an empty toast at first and then a non empty toast the second time (which messes up everything in my code as the response being received on time is what it needs).

Before I post the code I need to point out that i have no issue whatsoever if i run an alternate version of the code on the UI thread (while forcing connection on UI thread). The variable gets updated with that one.

String databaseCheckResult = "";

private class AsyncCheckIfExists  extends AsyncTask<String, Integer, String> {
    String result = null;
    @Override
    protected void onPreExecute(){

    }

    @Override
    protected String doInBackground(String... formValues) {
        try {
            URL url = new URL(formValues[1]);
            try {
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setUseCaches (false);
                String urlParameters  = "date=" + formValues[0];
                byte[] postData = urlParameters.getBytes("UTF-8");
                OutputStream os = conn.getOutputStream();
                os.write(postData);
                os.flush();
                os.close();
                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // success, get result from server
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(conn.getInputStream()));
                    String inputLine;
                    StringBuilder response = new StringBuilder();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    conn.disconnect();
                    result = response.toString();
                    return result;
                } else {
                    // error
                    //TODO: let the user know that something is wrong with the network
                }
            } catch (java.io.IOException e) {
                //TODO: prevent app from crashing
            }
        } catch (java.net.MalformedURLException e){
            //TODO: prevent app from crashing
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... progress){

    }

    @Override
    protected void onPostExecute(String message){
        databaseCheckResult = message;
    }


}

I call it using:

    AsyncCheckIfExists check = new AsyncCheckIfExists();
    check.execute(date, "http://www.webaddress.com/script.php");
meshachviktor
  • 45
  • 1
  • 6
  • 1
    I do not see any `Toast`. For your question once the `doInbackground()` done it will return to `onPostExcceute()` with data which called on UI thread. And you can update a instance variable anywhere . Read [AsyncTask](https://developer.android.com/reference/android/os/AsyncTask.html) calling cycle. And clarify your question if problem still exists . – ADM Mar 27 '18 at 14:12
  • The Toast is initiated by another method in my activity. – meshachviktor Mar 27 '18 at 14:17

1 Answers1

0

@ADM, I've fixed it using a method I found in the link you provided (I really should read more).
databaseCheckResult = check.execute(date, "http://www.webaddress.com/script.php").get(); solved the problem (try,catch ommitted). Thank you.

meshachviktor
  • 45
  • 1
  • 6
  • That's the spirit . Make the concept clear before using a API class . Explain the answer appropriately. – ADM Mar 27 '18 at 15:36
  • I have new problem now. I cant use `ProgressDialog` because of the get() method which (as I've researched) turns the task from an `AsyncTask` to "NonAyncTask" (coined that just now) running on the ui thread. Is there any way around this? I really need to display the progress dialog while the activity is requesting data from server. – meshachviktor Mar 29 '18 at 13:31
  • You can do it in `onPreExecute()` . Or you can show `ProgressDialog` in Activity an notify Activity to `dismiss()` it . – ADM Mar 29 '18 at 16:52
  • I've tried both ways but the dialog only displays literally after the whole process (connecting to server and getting data) has finished. – meshachviktor Mar 29 '18 at 23:33