考虑我有一个线程作为单独的类,例如SimpleThread.java,
class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {}
}
System.out.println("DONE! " + getName());
}
}
从我的android home.java我需要启动线程,
new SimpleThread("Jamaica").start();
一旦循环结束,我需要提示警报,但是当我使用
时 authalert = new AlertDialog.Builder(this);
它显示空指针执行,我在线程类中需要一个上下文,还有其他方法可以做到这一点。
答案 0 :(得分:4)
嘿,你应该使用Handler 这是代码......
ProgressDialog _progressDialog = ProgressDialog.show(this,"Saving Data","Please wait......");
settintAdater();
private void settingAdater(){
Thread _thread = new Thread(){
public void run() {
Message _msg = new Message();
_msg.what = 1;
// Do your task where you want to rerieve data to set in adapet
YourCalss.this._handle.sendMessage(_msg);
};
};
_thread.start();
}
Handler _handle = new Handler(){
public void handleMessage(Message msg) {
switch(msg.what){
case 1:
_progressDialog.dismiss();
listview.setAdapter();
}
}
}
答案 1 :(得分:2)
答案 2 :(得分:0)
问题是:当你启动线程时,编译器不会等到线程完成他的处理,他将执行下一条指令( authalert = new AlertDialog.Builder(this); )
所以有两种或三种方法可以做到这一点:
1),使用处理程序
2)为你的线程定义你自己的监听器,直到他完成了他的治疗,
3)您可以传递活动的上下文,并在run方法的最后一行显示AlertDialog(带Activity.runOnUiThread(new Runnable);
)
答案 3 :(得分:0)
您应该阅读http://www.aviyehuda.com/2010/12/android-multithreading-in-a-ui-environment/和http://developer.android.com/resources/articles/painless-threading.html
一种方法是在你的调用活动中放置一个处理程序:
final mContext=this;
final Handler mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
int yourIntReturnValue=msg.what;
//cast your object back to whatever it was lets say it was a string:
// String yourString=(String) msg.obj;
//do something like authalert = new AlertDialog.Builder(mContext);
}
};
然后
class SimpleThread extends Thread {
Handler mHandler;
public SimpleThread(String str, Handler h) {
super(str);
mHandler=h;
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {}
}
System.out.println("DONE! " + getName());
Message.obtain(mHandler, someIntRetValue,
"DONE" ).sendToTarget();
}
}