Search code examples
javaandroidandroid-asynctaskbackground-task

Set a variable in a class method to be accessed in a background (async) task class (Java/Android)


I am trying to set a variable 'election_id' from an intent get extra from a previous class. I need to use the id to parse it into a PHP URL in order to retrieve some JSON. What I want to be able to do is set a variable to equal the election ID as assigned in a previous class, to be used in a background task:

public class AdminFinishCandidateActivity extends AppCompatActivity {

String json_string;
String json_string_result;

String election_id;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_admin_finish_candidate);

    System.out.println("creating");

    Bundle electionData = getIntent().getExtras();
    if (electionData==null) {
        return;
    }

    election_id = electionData.getString("electionId");

}



public void getJson(View view){

    new BackgroundTask().execute();

}


class BackgroundTask extends AsyncTask<Void,Void,String> {



    String json_url="http://192.168.56.1/dan/db/getjson.php?election_id=" + election_id;


// code to retrieve JSON
    }
}
}

At the moment, election_id is being assigned in my onCreate method, however I know I cannot access it from this method in my BackgroundTask class, where I define the String json_url. How do I make it so that the election_id variable can be called in this class? The method to retrieve the intent extras does not work in this class. When I run the code as it is with the JSON code, nothing is retrieved. Thanks.


Solution

  • You can pass the string to the AsyncTask as follows:

    public class BackgroundTask extends AsyncTask<String,Void,String>{
    
        @Override
        protected String doInBackground(String... params) {
        String json_url="http://192.168.56.1/dan/db/getjson.php?election_id=" + params[0];
    
          //perform network operation and return response
          return response;
        }
    
        @Override
        protected void onPostExecute(String res){
          //Batman Rocks
        }
    }
    

    Now perform the task as follows:

    new BackgroundTask().execute(election_id);