tags:

views:

320

answers:

2

Hi,

I had an activity which calls a thread for 10times one after another. However, if the network is slow or too much information loaded, force close will occur. Will adding sleep in each thread help to solve this problem? or is there any other ways to solve it?

   public void run() {
         if(thread_op.equalsIgnoreCase("xml")){
              readXML();
         }
         else if(thread_op.equalsIgnoreCase("getImg")){
              getWallpaperThumb();
         }
         handler.sendEmptyMessage(0);
    }

    private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                    int count = 0;
                    if (!myExampleHandler.filenames.isEmpty()){
                          count = myExampleHandler.filenames.size();
                    }
                    count = 5;
                    if(thread_op.equalsIgnoreCase("xml")){
                            pd.dismiss();
                            thread_op = "getImg";
                            btn_more.setBackgroundResource(R.drawable.btn_more);

                    }
                    else if(thread_op.equalsIgnoreCase("getImg")){
                            setWallpaperThumb();
                            index++;
                            if (index < count){
                                    Thread thread = new Thread(GalleryWallpapers.this);
                                    thread.start();

                            }
                    }
            }
    };
A: 

Are you getting the Application not responding dialog (ANR) or does your app force close?

ANR appears when the UI looper thread takes too long to return from a call. Having 10 or 100 threads should not cause any problem as long as the handleMessage function returns in a timely fashion.

If you really want to limit the number of threads that should be running in one go look up ExecutorService

ExecutorService executorService = Executors.newFixedThreadPool(5);
    executorService.submit(new Runnable() {
        public void run() {
            // This is your thread
        }
    });

You can submit all 10 jobs to the executor service and they'll run one after another with a maximum of 5 running simultaneously.

Prashast
the apps had force close
Lynnooi
In that case please edit your post to include the stack trace from logcat. That will give a clear indication of where the problem lies.
Prashast
+1  A: 

First step should be to check the stack trace which will give the offending line and cause. You can use Logcat for that.

Al