简体   繁体   中英

Why instead of two different AsyncTasks one executes two times?

So I have code where I send request to the server and get the response. Response depends on the set of parameters which I send to the server.But because of some reason I got the same result.Here is a code: I call sendDashboardRequest for two different set of parameters:

 LinkedHashMap<String, Object> serverParameters = new LinkedHashMap<String, Object>();
serverParameters.put("user_id", result.get("user_id"));
serverParameters.put("limit", Integer.valueOf(1000).toString());
serverParameters.put("type", Integer.valueOf(1).toString());
sendDashboardRequest(serverParameters);
 serverParameters.put("type", Integer.valueOf(2).toString());
sendDashboardRequest(serverParameters);//Executes only this AsyncTask twice!

And here is code of the method sendDashboardRequest which starts new AsyncTasks:

public void sendDashboardRequest(LinkedHashMap<String, Object> params) {

    new AsyncTask<LinkedHashMap<String, Object>, Void, LinkedHashMap<String, Object>>()
    {    
         NetworkOp lowLevelOps = new NetworkOp();
        @Override
        protected LinkedHashMap<String, Object> doInBackground (LinkedHashMap<String, Object>... params)    
       { 

        return  lowLevelOps.executeCommand(DASHBOARD_COMMAND, params[0]);
        }
        protected void onPostExecute(LinkedHashMap<String, Object> result)
        {   
                        //And here I gave the same result!But parameters which I send to the server are different!
        }
    }.execute(params);
} 

The most interesting thing is when I create two different methods with same body and call each for the different set of parameters everything works well and two different AsyncTasks starts.

You are sending the same LinkedHashMap in both requests. Since the requests are serviced in a background thread, the timing will be unpredictable and you can't guarantee that the background thread for the first request will execute before you issue the second request. In this case, by chance, the modified value in the second request is already in the map by the time the first request gets executed.

You should use a different map for each request, or else change sendDashboardRequest so that it copies the data it needs rather than relying on the passed-in map remaining constant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM