正如问题所述..
我有一个Fragment,我从中创建并显示一个DialogFragment,同时将targetFragment设置为此,即当前片段。
DialogFragment_Progress fragmentProgressBar = new DialogFragment_Progress();
fragmentProgressBar.setTargetFragment(this, 0);
fragmentProgressBar.show(getFragmentManager(), null);
我做了一些进度条更新
// Thread that controls progress bar
final Thread progressThread = new Thread()
{
@Override
public void run()
{
active = true;
int cumulativetime = 0;
try
{
while (active && cumulativetime < TIME_TOTAL)
{
sleep(TIME_INTERVAL);
if (active)
{
cumulativetime += TIME_INTERVAL;
updateProgress(cumulativetime);
}
}
}
catch (InterruptedException e)
{
}
finally
{
onContinue();
}
}
};
当进度错误结束时,我尝试调用目标片段中的方法来显示Toast。 onContinue()代码和targetFragment中调用的方法可以在下面看到..
// Perform final operations
public void onContinue()
{
Fragment_Activate_Program_Specific targetFragment = (Fragment_Activate_Program_Specific) getTargetFragment();
targetFragment.operationComplete();
dismiss();
}
操作完成..
// Operation complete
public void operationComplete()
{
Toast.makeText(getActivity(), "Herp", Toast.LENGTH_SHORT).show();
Log.i("Hello: ", "Got here!");
}
当我不尝试Toast时,一切都很好,收到日志。在没有涉及UI之前,这种方法对我有用了好几次。
问题:当在targetFragment()中调用operationComplete()时,我得到以下异常..
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
相关堆栈跟踪..
05-31 12:21:53.024: W/dalvikvm(28494): threadid=13: thread exiting with uncaught exception (group=0x40cc9930)
05-31 12:21:53.034: E/AndroidRuntime(28494): FATAL EXCEPTION: Thread-14251
05-31 12:21:53.034: E/AndroidRuntime(28494): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
05-31 12:21:53.034: E/AndroidRuntime(28494): at android.os.Handler.<init>(Handler.java:197)
05-31 12:21:53.034: E/AndroidRuntime(28494): at android.os.Handler.<init>(Handler.java:111)
05-31 12:21:53.034: E/AndroidRuntime(28494): at android.widget.Toast$TN.<init>(Toast.java:324)
05-31 12:21:53.034: E/AndroidRuntime(28494): at android.widget.Toast.<init>(Toast.java:91)
05-31 12:21:53.034: E/AndroidRuntime(28494): at android.widget.Toast.makeText(Toast.java:238)
05-31 12:21:53.034: E/AndroidRuntime(28494): at com.mypackage.Activity_Activate_Program.activateOperationComplete(Activity_Activate_Program.java:90)
我尝试使用父Activity而不是调用片段来托管operationComplete()方法,但是我得到了同样的错误。
有什么想法吗?
答案 0 :(得分:4)
应该从UI线程调用Toasts。
试试这个。
public void operationComplete()
{
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), "Herp", Toast.LENGTH_SHORT).show();
}
});
Log.i("Hello: ", "Got here!");
}
答案 1 :(得分:0)
你可以简单地覆盖Dialog片段的dismiss方法,这只会调用一个。
@Override
Public void dismiss() {
Log.e(TAG,"dismiss";
super.dismiss();
}