Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8672999
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T19:20:41+00:00 2026-06-12T19:20:41+00:00

In a game application I have the following scenario: From the main game Activity

  • 0

In a game application I have the following scenario:

  • From the main game Activity, the player starts several game tasks that run in the background with varying duration.
  • The player should be able to view the progress of the running game tasks in a separate View.

To do this, I created two Activitys and a Service, defined as follows:

  • Service ProgressService handles several ProgressBars running simultaneously on parallel threads.

  • Activity WorkScreen2 creates a game task, starts the Service with startService() with task parameters passed in a Bundle.

  • Activity ProgressScreen binds to the Service to get and display the ProgressBars of the running tasks.

  • Both activities run under separate TabHosts of one TabActivity.


The problem I’m having is that the ServiceConnection.onServiceConnected() method is never called. I get a Java.lang.NullPointerException because I try to call a method of the Service object that should be assigned in this method. See code below.

I use getApplicationContext().bindService() to bind the Activity to the Service because TabSpec cannot bind to Services. This method returns true. Therefore, binding is successful.


Here is the Service:

public class ProgressService extends Service implements GameConstants {
    public static final String BROADCAST_PROGRESS = "com.mycompany.android.mygame.progressbroadcast";
    private static final long UPDATE_INTERVAL = 500;
    private IBinder mBinder;
    private List<ProgressBar> mProgressBarList;
    private List<String> mStaffNameList;

    private final class ServiceHandler extends Handler {

        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            ProgressBar progressBar = new ProgressBar(ProgressService.this);
            mProgressBarList.add(progressBar);

            Bundle bundle = msg.getData();
            String staffName = bundle.getString(WorkScreen2.STAFF_NAME);
            mStaffNameList.add(staffName);

            int taskDurationMillis = bundle.getInt(WorkScreen2.TASK_DURATION) * 1000;
            progressBar.setMax(taskDurationMillis / 1000);

            long startTimeMillis = SystemClock.uptimeMillis();
            long elapsedTimeMillis = SystemClock.uptimeMillis()
                    - startTimeMillis;

            Intent intent = new Intent();
            intent.setAction(BROADCAST_PROGRESS);

            while (elapsedTimeMillis < taskDurationMillis) {
                try {
                    Thread.sleep(UPDATE_INTERVAL);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                elapsedTimeMillis = SystemClock.uptimeMillis()
                        - startTimeMillis;
                int elapsedTimeSeconds = (int) elapsedTimeMillis / 1000;
                progressBar.setProgress(elapsedTimeSeconds);
                sendBroadcast(intent);
            }

            progressBar.setVisibility(View.GONE);
            mProgressBarList.remove(progressBar);
            mStaffNameList.remove(staffName);
            sendBroadcast(intent);

            if (mProgressBarList.isEmpty()) {
                stopSelf(msg.arg1);
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mBinder = new ProgressServiceBinder();
        mProgressBarList = Collections
                .synchronizedList(new ArrayList<ProgressBar>());
        mStaffNameList = Collections.synchronizedList(new ArrayList<String>());
    }

    /*
     * Creates a thread for each game task with parameters passed in
     * <code>intent</code>
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "starting service", Toast.LENGTH_LONG).show();

        HandlerThread thread = new HandlerThread("ServiceStartArguments",
                Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();

        Handler serviceHandler = new ServiceHandler(thread.getLooper());

        Message msg = serviceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.setData(intent.getExtras());
        serviceHandler.sendMessage(msg);

        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public class ProgressServiceBinder extends Binder {
        ProgressService getService() {
            return ProgressService.this;
        }
    }

    public List<ProgressBar> getProgressBarList() {
        return mProgressBarList;
    }

    public List<String> getStaffNameList() {
        return mStaffNameList;
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service done", Toast.LENGTH_SHORT).show();
    }
}

And this is the Activity that binds to it:

public class ProgressScreen extends ListActivity {
    private final String TAG = "ProgressScreen";

    private ProgressScreenAdapter mAdapter;
    private ProgressService mProgressService;
    private List<ProgressBar> mProgressBarList;
    private List<String> mStaffNameList;

    @Override
    public void onCreate(Bundle bundle) {
        Log.i(TAG, "ProgressScreen oncreate");

        super.onCreate(bundle);
        setContentView(R.layout.progress_screen_layout);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ProgressService.BROADCAST_PROGRESS);
        registerReceiver(receiver, filter);
        doBindService();

        mAdapter = new ProgressScreenAdapter(this, mStaffNameList, mProgressBarList);
        setListAdapter(mAdapter); // Returns true

        /*
         * This is where I get the NullPointerException
         * mProgressService is null here
         */
        mProgressBarList = mProgressService.getProgressBarList();
        mStaffNameList = mProgressService.getStaffNameList();
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ProgressService.BROADCAST_PROGRESS);
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }

    boolean doBindService() {
        return getApplicationContext().bindService(new Intent(this, ProgressService.class), mConnection, Context.BIND_AUTO_CREATE);
    }

    void doUnbindService() {
        getApplicationContext().unbindService(mConnection);
    }

    ServiceConnection mConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName className, IBinder binder) {
            mProgressService = ((ProgressService.ProgressServiceBinder) binder).getService();
            Toast.makeText(ProgressScreen.this, "Connected to ProgressService", Toast.LENGTH_SHORT).show();
        }

        public void onServiceDisconnected(ComponentName name) {
            mProgressService = null;
        }
    };

    private BroadcastReceiver receiver = new BroadcastReceiver () {
        @Override
        public void onReceive(Context context, Intent intent) {
            mAdapter.notifyDataSetChanged();
        }
    };
}

And the Service is started from the main Activity as follows:

Intent intent = new Intent(WorkScreen2.this, ProgressService.class);
intent.putExtra(TASK_DURATION, task.getDuration());
intent.putExtra(STAFF_NAME, staff.getName());
startService(intent);

The AndroidManifest.xml contains

<service
    android:name=".ProgressService"
    android:label="@string/progress_service">
</service>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T19:20:43+00:00Added an answer on June 12, 2026 at 7:20 pm

    ServiceConnection’s onServiceConnected() is called, but nobody guarantees that it will be called before onCreate continues execution. So, what happens here – you successfuly bind to the service (that’s why onBind returns true), but you’re not fully connected – onServiceConnected() has not yet been called, so your local mProgressService object is not yet initalized, and therefore you get the NullPointerException.

    Solution:

    Move these two lines:

    mProgressBarList = mProgressService.getProgressBarList();
    mStaffNameList = mProgressService.getStaffNameList();
    

    from onCreate() to onServiceConnected() function (use the service object after it is initialized in onServiceConnected()).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

In my game application I have several different activities that all can be accessed
I have a facebook game application that is released at facebook platform at the
I have the following ember.js code: app.js: Game = Ember.Application.create({ ready: function() { Game.gameController.getChallenge();
Let's say I have the following filesystem structure: /app/ Main application folder /app.js Server
I have written an application that is able to write posts from the command
I have following code in my Application. I am new to game development in
I have a game application made up of several different activities. The first to
I have a game application released at the Facebook platform. I need to set
I have a game server application (Java) and want to have PHP communicate directly
I built a TicTacToe game application (I'm using TCP protocol) that consist of server

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.