Question

In my Android project, I am attempting to send a Map of submitted form data from my main Activity class to a second class which extends asyncTask.

In my main activity, I have the following snippet of code:

Map<String, String> formData = new HashMap<String, String>();
formData.put("name", formName.getText().toString());
formData.put("test", "TESTING");

//formData.get("name"); - this test works

Connection connection = new Connection();
connection.execute(formData);

That sets up my Map of data, successfully tests the first element and sends the form data to my class responsible for working on that data on a separate thread.

But, in my async class, with the following snippet:

public class Connection extends AsyncTask<Map, Void, Void> {
    @Override
    protected Void doInBackground(Map... data) {
        // TODO Auto-generated method stub
        Log.i("TEST", "NEW THREAD FIRING !!!");
        Log.d("DATA", data.get("name"));

        return null;
    }

}

My second log call is attempting to extract the name element of the array map but my "data" object is no recognised as the Map I passed in.

Was it helpful?

Solution

The doInBackground() method is taking in a varargs parameter. Which means that more than one of the type can be passed in at once.

In this case, there could be more than one map passed in, also in this case, only one IS actually passed in. (You know this because you are initiating the call through AsyncTask's execute method). Notice the ... in the method signature? This means that you could pass in multiple Map objects.

Connection connection = new Connection();
connection.execute(formData1, formData2, formData3);

You access the values within as you would any array object, that is, with an indexer.

I believe if you change your code to look like this, it should work:

@Override
protected Void doInBackground(Map... data) {
    // TODO Auto-generated method stub
    Log.i("TEST", "NEW THREAD FIRING !!!");
    Map myMap = data[0];
    Log.d("DATA", myMap.get("name"));

    return null;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top