简体   繁体   中英

Android Displaying a Progress Dialog from a class which is not in the UI thread

I define this method in a RecordTable class, which is not an Activity.
I call it from the main UI thread and pass a valid UI thread context as parameter.
Of course, it does not work with the message:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

I saw in other post they recommend using runOnUiThread instead of new thread but since the class is not an activity runOnUiThread is not available.

Starting the Dialog outside the runnable() does not work either.

Has anyone got this problem and found how to solve it?

public synchronized void scrollUp(final Context context, final ArrayList<Record> list, final int count) {
    new Thread(new Runnable() {
        public void run() {
            setScrolling(true);
            ProgressDialog pd = ProgressDialog.show(context, "", context.getResources().getString(R.string.loading_msg), true);
            int n = Math.max(mViewStartIndex - count, 0);
            for(int i = mViewStartIndex - 1; i >= n; i--) {
                RecordTable.this.addFirstRow(list.get(i));
                RecordTable.this.removeViews(RecordTable.this.getChildCount() - 1, 1);
            }
            pd.dismiss();
            setScrolling(false);
        }
    }).start();
}

Given the code I would suggest use an AsyncTask . Take a look at the documentation for AsyncTask.

Carry out the work you want on a different thread in the doInBackground(....) function with periodic calls to progressUpdate , which always runs on the UI thread. Much simpler to implement and you don't have to worry about creating new threads. AsyncTask does it for you.

ProgressDialog pd;
Context context;

public synchronized void scrollUp(Context context, final ArrayList<Record> list, final int count) {
this.context = context;
new Thread(new Runnable() {
public void run() {
    setScrolling(true);
    hand.sendEmptyMessage(0);                
    }
  }
}).start();

int n = Math.max(mViewStartIndex - count, 0);
for(int i = mViewStartIndex - 1; i >= n; i--) {
RecordTable.this.addFirstRow(list.get(i));
RecordTable.this.removeViews(RecordTable.this.getChildCount() - 1, 1);

pd.dismiss();
setScrolling(false);
}


Handler hand = new Handler() 
{
    @Override
    public void handleMessage(Message msg) 
    {
              pd = ProgressDialog.show(context, "", context.getResources().getString(R.string.loading_msg), true);
    }
}

try this it may help you.... if you want to create any dialog or Toast in a class handler will handle this...

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