asmgx
asmgx

Reputation: 8004

Looper.prepare() error inside a thread

I am using handler to get GCM value I want to update this value in my database

so I call AsyncTask from the handler

but I get this Error

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

I checked other solutions they said I have to put the code in the run() section which I already do..

This is the code,

private void GetGCM(final String UserID) {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                GCMHelper gcmRegistrationHelper = new GCMHelper(getApplicationContext());
                String gcmRegID = "";
                gcmRegID = gcmRegistrationHelper.GCMRegister("123456");

                // Update using Web Service
                try {
                    UpdateGCMWSTask updateGCMWSTask = new UpdateGCMWSTask();


                    updateGCMWSTask.execute(UserID, gcmRegID);
                    // ************ HERE IS THE ERROR ***********************

                }catch (Exception e)
                {
                    e.printStackTrace();
                }


            } catch (Exception bug) {
                bug.printStackTrace();
            }
        }
    });


    thread.start();
}

Upvotes: 0

Views: 420

Answers (2)

Kingfisher Phuoc
Kingfisher Phuoc

Reputation: 8190

You can't create asynctask inside a thread. There are few ways to handle it:

  1. Create a new handler.

  2. Call function runOnUIThread of activity.

  3. Using broadcast.

Upvotes: 1

weithink
weithink

Reputation: 76

Add Looper.prepare() and Looper.loop() in you code, like this:

private void GetGCM(final String UserID) {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Looper.prepare();
                GCMHelper gcmRegistrationHelper = new GCMHelper(getApplicationContext());
                String gcmRegID = "";
                gcmRegID = gcmRegistrationHelper.GCMRegister("123456");

                // Update using Web Service
                try {
                    UpdateGCMWSTask updateGCMWSTask = new UpdateGCMWSTask();


                    updateGCMWSTask.execute(UserID, gcmRegID);
                    // ************ HERE IS THE ERROR ***********************

                }catch (Exception e)
                {
                    e.printStackTrace();
                }

              Looper.loop();
            } catch (Exception bug) {
                bug.printStackTrace();
            }
        }
    });

    thread.start();
}

Upvotes: 1

Related Questions