简体   繁体   中英

Lost variable value inside ASyncTask

I'm trying to retrieve the GCM Registration ID. For that, i'm using ASyncTask. However, the variable is receiving the registration id (i'm logging it, and i can see it on LogCat), but when i need to put this variable inside another function, it's showing up empty value.

Here's the code:

private void registrarRegId() {
    regId = GCMRegistrar.getRegistrationId(getApplicationContext());

    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            if (regId.equals("")) {
                GoogleCloudMessaging gcm = GoogleCloudMessaging
                        .getInstance(getApplicationContext());
                try {
                    regId = gcm.register(SENDER_ID);
                    Log.d("REGID", regId);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }
            return null;
        }

    }.execute(null, null, null);

}

It sounds like your calling the registrarRegId() function to assign a value to regId (which I assume is global) and then trying to use this variable immediately after the function call(?) If that's the case, the issue may be that you are accessing the variable before the background thread created by AsyncTask has run to completion. Try using the onPostExecute() method to make sure you aren't accessing any of the variables set in doInBackground until you can be sure the background thread is completed. Hope this helps.

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