3

I have spent last couple of hours searching for answers here but nothing seems to make it clear for me.

Here's my problem: I have a simple app with a main menu. One of the options retrieves a list of comments from a PHP server, updates the database and then displays a ListView.

Everything functions properly inside. Now, every time I press back and then start the activity again, a new thread is started. I managed to get to more than 50+ waiting threads. I'm using the DDMS tab from Eclipse to monitor the treads.

If I try to call Looper.getLooper().quit() or Looper.myLooper().quit() I get an error saying "main thread not allowed to quit".

What am I doing wrong and where/how should I be stopping the thread?

Here's the code:

public class RequestActivity extends Activity {

    ProgressDialog pDialog;
    DatabaseHelper db;
    int userId;
    myCursorAdapter adapter;
    Thread runner = null;
    ListView list;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userId = myApplication.getInstance().getSession().getUserId();
        setContentView(R.layout.request_list);

        db = new myProvider.DatabaseHelper(this);
        Cursor cursor = db.getRequests(userId);
        startManagingCursor(cursor);
        adapter = new myCursorAdapter(RequestActivity.this, cursor);
        list = (ListView) findViewById(R.id.list);
        list.setVisibility(View.INVISIBLE);
        list.setAdapter(adapter);

        pDialog = ProgressDialog.show(RequestActivity.this, "", "Loading ...", true, false);

        runner = new Thread() {
            Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    adapter.getCursor().requery(); 
                }
            };  

            public void run() {
                Looper.prepare();
                // ... setup HttpGet
                try {
                    // ... get HTTP GET response 
                    if (response != null) {
                        // ... update database
                        handler.sendEmptyMessage(0);
                    }
                } catch(Exception e) {
                    // .. log exception
                }
                Looper.loop();
            }
        };
        runner.start();
    }

    private static class ViewHolder {
        // .. view objects
    }

    private class myCursorAdapter extends CursorAdapter {
        private LayoutInflater inflater;
        public myCursorAdapter(Context context, Cursor c) {
            super(context, c);
            inflater = LayoutInflater.from(context);
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            // .. bind data
            if (cursor.isLast()) {
                pDialog.dismiss();
                list.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View view = inflater.inflate(R.layout.request_list_item, parent, false);
            ViewHolder holder = new ViewHolder();
            // .. set holder View objects
            view.setTag(holder);
            return view;
        }
    }

}
eldarerathis
  • 35,455
  • 10
  • 90
  • 93

3 Answers3

2

You're calling quit() on your main thread's Looper. Not the thread's Looper.

You can try this. Create a separate private inner-class that extends Thread. In the run() method, do a call to Looper.myLooper() to save the thread's Looper instance in the class. Then have a quitting method that calls quit on that looper.

Example:

private class LooperThread extends Thread{
   private Looper threadLooper;

   @Override
   public void run(){
      Looper.prepare();
      threadLooper = Looper.myLooper();
      Looper.loop();
   }

   public void stopLooper(){
      if(threadLooper != null)
          threadLooper.quit();
   }
}
DeeV
  • 35,865
  • 9
  • 108
  • 95
  • That's it! I knew that you can't call `quit()` on the the activity's `Looper` but it never crossed my mind to get the the **thread** looper _inisde_ `run()`. Thanks again! – Dragoş Mandache Aug 12 '11 at 15:59
1

You are calling the Looper.quit() method within your main (UI) thread, which is not allowed. Try posting a Runnable to the handler inside your thread that calls Looper.quit(). This will cause the Looper within the thread context to quit.

Eugene S
  • 3,092
  • 18
  • 34
1

On your onDestroy method do you make any calls to stop the thread?

public void onDestroy()
{
    Thread moribund = runner;
    runner = null
    moribund.interrupt();

}
Jack
  • 9,156
  • 4
  • 50
  • 75
  • Jack I have done that, but the thread is still alive, and isInterrupted() returns false. – Dragoş Mandache Aug 12 '11 at 15:43
  • Something else I do is add a requestedStop boolean to my Thread class. And create a requestStop() method to set it to true. I add a conditional to my loop that says only continue IF !requestedStop – Jack Aug 12 '11 at 15:57
  • Also see http://stackoverflow.com/questions/6673687/specifics-on-using-looper-prepare-in-android – Jack Aug 12 '11 at 16:01
  • 1
    Thanks, I've nailed it. The problem was I was calling `Looper.myLooper()` in the Activity, **not** inside the Thread. I learned the hard way :) – Dragoş Mandache Aug 12 '11 at 16:03