Search code examples
javaandroidandroid-activityandroid-asynctask

AsyncTask vs MainThread


Well I wrote a program which uses internet access and makes https requests. So i had to use AsyncTask to do the request part. My issue is that in my main activity, I have a function that increments a spinner after every https request made. In my backgroundTask(that is my AsyncTask class), i have included an static integer called :resultTest which numbers every exception generated. I just want to pass a value(either 0/1 or true/false) depending on if the connection was successful to my main thread. This value that will be passed will determine if I should increment the spinner or not.

Here is the the OnPostExecute part of my backgroundTask, just to give you an idea how it works:

    @Override
protected void onPostExecute(String result) {
    //this method will be running on UI thread

    pdLoading.dismiss();

    if (resultTest == 0) {
        Toast.makeText(ctx,"Successfully Recorded",Toast.LENGTH_LONG).show();
    }
    else{
        String msg = "";
        switch(resultTest){

            case 1:msg = "Internal App Error";
            case 2:msg="Server Problem";
            case 3:msg="Server Returned Error";
            case 4:msg="Connection Problem";
        }

        Toast.makeText(ctx,msg,Toast.LENGTH_LONG).show();
    }

}

Here is the part in my main thread where I instantiated the BackgroundTask and the event which depends on the value returned:

BackgroundTaskWater backgroundTaskWater = new BackgroundTaskWater(getActivity());
backgroundTaskWater.execute(field, val);

// FIX THIS INCREMENT

if(code == 0) {
  meterItemIncrement(meters);
  screen.setText("");
}

How can I pass the value of the variable resultTest in the backgroundTask to the variable code in the main thread?

I have tried to use static method and getter function but failed. The value doesn't get passed I even tried to change the variable code in the main thread to public static and passed the value from the backgroundTask but when the backgroundTask gets destroyed, the value resets. the value does not get passed.

Any idea or suggestion will be greatly appreciated!!


Solution

  • Can't you move this code

    if(code == 0) {
      meterItemIncrement(meters);
      screen.setText("");
    }
    

    to onPostExecute method?